"use client";

import { useEffect, useState } from "react";
import i18n from "@/lib/i18n";
import { readStoredLanguagePreference, resolveBrowserLanguage } from "@/lib/i18n/clientLanguage";

export default function GlobalError({
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  const [lang, setLang] = useState(readStoredLanguagePreference() ?? resolveBrowserLanguage());

  useEffect(() => {
    const stored = readStoredLanguagePreference() ?? resolveBrowserLanguage();
    setLang(stored);
    void i18n.changeLanguage(stored);
  }, []);

  const t = (key: string) => i18n.t(key, { lng: lang, ns: "common" });
  const dir = lang === "fa" ? "rtl" : "ltr";

  return (
    <html lang={lang} dir={dir}>
      <body className="flex min-h-screen flex-col items-center justify-center gap-4 bg-white px-6 text-center text-neutral-900">
        <p className="text-lg font-bold">{t("errors.appLoad")}</p>
        <p className="max-w-md text-sm text-neutral-600">{t("errors.safariIosHint")}</p>
        <button
          type="button"
          onClick={() => reset()}
          className="rounded-xl bg-[#0095f6] px-5 py-2.5 text-sm font-bold text-white"
        >
          {t("errors.retry")}
        </button>
      </body>
    </html>
  );
}
