"use client";

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

type Props = {
  children: React.ReactNode;
};

type State = {
  hasError: boolean;
};

export default class ClientErrorBoundary extends React.Component<Props, State> {
  state: State = { hasError: false };

  static getDerivedStateFromError(): State {
    return { hasError: true };
  }

  componentDidCatch(error: unknown) {
    console.error("[ClientErrorBoundary]", error);
  }

  render() {
    if (this.state.hasError) {
      const lang = readStoredLanguagePreference() ?? resolveBrowserLanguage();
      const t = (key: string) => i18n.t(key, { lng: lang, ns: "common" });

      return (
        <div className="flex min-h-[50vh] flex-col items-center justify-center gap-4 px-6 text-center">
          <p className="text-base font-bold">{t("errors.pageLoad")}</p>
          <p className="text-sm text-neutral-500">{t("errors.safariHint")}</p>
          <button
            type="button"
            onClick={() => window.location.reload()}
            className="rounded-xl bg-[#0095f6] px-5 py-2.5 text-sm font-bold text-white"
          >
            {t("errors.retry")}
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}
