"use client";

import { useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { IconArrowLeft, IconRefresh } from "@tabler/icons-react";

import { Button } from "@/components/ui/button";
import { defaultLocale, locales, type Locale } from "@/lib/i18n";

// Error copy is kept inline (not in the shared dictionaries) so this boundary
// stays self-contained and renders even when data loading is what failed.
const COPY: Record<
  Locale,
  { title: string; subtitle: string; retry: string; back: string }
> = {
  en: {
    title: "Something went wrong",
    subtitle:
      "We couldn't load this documentation page. Try again, or head back to the docs home.",
    retry: "Try again",
    back: "Back to docs",
  },
  fr: {
    title: "Une erreur est survenue",
    subtitle:
      "Nous n'avons pas pu charger cette page de documentation. Réessayez ou revenez à l'accueil de la documentation.",
    retry: "Réessayer",
    back: "Retour à la documentation",
  },
};

function resolveLang(pathname: string): Locale {
  const segment = pathname.split("/")[1] ?? "";
  return (locales as readonly string[]).includes(segment)
    ? (segment as Locale)
    : defaultLocale;
}

export default function DocsError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  // Surface the error so it's still captured by logging/monitoring.
  useEffect(() => {
    console.error(error);
  }, [error]);

  const pathname = usePathname();
  const lang = resolveLang(pathname ?? "");
  const t = COPY[lang];

  return (
    <div className="flex min-h-[60svh] flex-col items-center justify-center px-6 py-16 text-center">
      <div className="mx-auto w-full max-w-lg">
        <h1 className="text-ink-1 text-3xl font-bold tracking-tight text-balance sm:text-4xl">
          {t.title}
        </h1>
        <p className="text-ink-3 mt-5 text-lg text-pretty">{t.subtitle}</p>

        <div className="mt-10 flex items-center justify-center gap-4">
          <Button onClick={() => reset()}>
            <IconRefresh aria-hidden className="size-4" />
            {t.retry}
          </Button>
          <Link
            href={`/${lang}/docs`}
            className="text-brand-orange inline-flex items-center gap-2 text-sm font-semibold hover:underline"
          >
            <IconArrowLeft aria-hidden className="size-4" />
            {t.back}
          </Link>
        </div>
      </div>
    </div>
  );
}
