"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { useLanguageStore } from "@/store/languageStore";
import Button from "@/components/ui/Button";

interface ErrorStateProps {
  error: Error & { digest?: string };
  /**
   * Next 16 renamed this from `reset`. It re-fetches and re-renders the
   * boundary's children rather than only clearing the error state, which is
   * what a transient API failure actually needs.
   */
  onRetry: () => void;
}

/**
 * The fallback every `error.tsx` renders. Deliberately shaped like
 * `NotFound` — same centred column, same button pair — so an unexpected
 * failure does not look like a different product from a missing page.
 */
export default function ErrorState({ error, onRetry }: ErrorStateProps) {
  const { t } = useTranslation();
  const router = useRouter();
  const selectedLanguage = useLanguageStore((s) => s.language);

  useEffect(() => {
    // The only record of what happened. In production Next replaces a Server
    // Component's message with a generic one, so `digest` is the handle that
    // matches this render to the server log.
    console.error("Route error boundary caught:", error);
  }, [error]);

  return (
    <div
      className={`min-h-screen flex items-center justify-center bg-gray-50 px-4 ${
        selectedLanguage === "ar" ? "rtl" : "ltr"
      }`}
    >
      <div className="max-w-md w-full text-center">
        <div className="mb-8">
          <h2 className="text-3xl font-bold text-gray-800 mb-4">
            {t("COMMON.SOMETHING_WENT_WRONG")}
          </h2>
          <p className="text-lg text-gray-600">
            {t("COMMON.SOMETHING_WENT_WRONG_MESSAGE")}
          </p>
          {/*
            Shown so a user can quote it in a support request — it is the only
            thing that ties their screen to a line in the server log. It is a
            hash, not error content, so it leaks nothing.
          */}
          {error.digest && (
            <p className="mt-3 text-sm text-gray-400" dir="ltr">
              {error.digest}
            </p>
          )}
        </div>

        <div className="flex flex-col sm:flex-row gap-4 justify-center">
          <Button
            variant="primary"
            size="medium"
            onClick={onRetry}
            className="w-full"
          >
            {t("COMMON.TRY_AGAIN")}
          </Button>
          <Button
            variant="secondary"
            size="medium"
            onClick={() => router.push("/")}
            className="w-full"
          >
            {t("COMMON.GO_TO_HOME")}
          </Button>
        </div>
      </div>
    </div>
  );
}
