"use client";

import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { defaultLocale, hasLocale } from "@/i18n/config";
import { loadDictionary, type Dictionary } from "@/i18n/load-dictionary";
import { Footer } from "@/components/layout/footer/footer";
import { Header } from "@/components/layout/header/header";
import { PageContentPlaceholder } from "@/components/shared/page-content-placeholder";
import { ErrorSection } from "./error-section";

type ErrorPageProps = { error: unknown; retry: () => void };

/**
 * The site's "Something went wrong" page (app/[lang]/error.tsx and app/global-error.tsx).
 * Error pages run in the browser and get no server data, so the texts load here, only when an error happens.
 */
export function ErrorPage({ error, retry }: ErrorPageProps) {
  const params = useParams<{ lang?: string }>();
  const locale = params.lang && hasLocale(params.lang) ? params.lang : defaultLocale;
  const [dict, setDict] = useState<Dictionary | null>(null);

  useEffect(() => {
    console.error(error);
  }, [error]);

  useEffect(() => {
    let active = true;
    loadDictionary[locale]().then((loaded) => active && setDict(loaded));
    return () => {
      active = false;
    };
  }, [locale]);

  if (!dict) return <PageContentPlaceholder />;
  const title = `${dict.errorPage.metaTitle} | ${dict.brand.name}`;

  return (
    <>
      <title>{title}</title>
      <Header locale={locale} nav={dict.nav} />
      <main>
        <ErrorSection locale={locale} t={dict.errorPage} backgroundAlt={dict.career.hero.imageAlt} onRetry={retry} />
      </main>
      <Footer locale={locale} t={dict.footer} brandName={dict.brand.name} className="mt-0 md:mt-0 lg:mt-0" />
    </>
  );
}
