import type { Metadata } from "next";
import localFont from "next/font/local";
import { notFound } from "next/navigation";
import { getMessages, getTranslations } from "next-intl/server";
import { NextIntlClientProvider } from "next-intl";

import { DirectionProvider } from "@/components/layout/DirectionProvider";
import { SiteChrome } from "@/components/layout/SiteChrome";
import { getNavUser } from "@/lib/auth/session";
import { routing } from "@/i18n/routing";
import type { Locale } from "@/i18n/routing";

import "../globals.css";

/* ── Fonts (self-hosted via @fontsource — no Google CDN required) ── */

const vazirmatn = localFont({
  src: [
    { path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-400-normal.woff2", weight: "400" },
    { path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-500-normal.woff2", weight: "500" },
    { path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-600-normal.woff2", weight: "600" },
    { path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-700-normal.woff2", weight: "700" },
    { path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-800-normal.woff2", weight: "800" },
  ],
  variable: "--font-vazirmatn",
  display: "swap",
});

const plusJakartaSans = localFont({
  src: "../../../node_modules/@fontsource-variable/plus-jakarta-sans/files/plus-jakarta-sans-latin-wght-normal.woff2",
  variable: "--font-heading",
  display: "swap",
});

const inter = localFont({
  src: "../../../node_modules/@fontsource-variable/inter/files/inter-latin-wght-normal.woff2",
  variable: "--font-body",
  display: "swap",
});

/* ── Metadata ───────────────────────────────────────────────────── */

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: Locale }>;
}): Promise<Metadata> {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: "metadata" });
  const brand = locale === "fa" ? "فلت‌رندر" : "FlatRender";

  return {
    title: {
      default: t("homeTitle"),
      template: `%s — ${brand}`,
    },
    description: t("homeDescription"),
    metadataBase: new URL("https://flatrender.com"),
    openGraph: {
      siteName: brand,
    },
  };
}

export function generateStaticParams() {
  return routing.locales.map((locale) => ({ locale }));
}

/* ── Layout ─────────────────────────────────────────────────────── */

interface LocaleLayoutProps {
  children: React.ReactNode;
  params: Promise<{ locale: Locale }>;
}

export default async function LocaleLayout({
  children,
  params,
}: LocaleLayoutProps) {
  const { locale } = await params;

  // Validate locale — show 404 for unknown values
  if (!(routing.locales as readonly string[]).includes(locale)) {
    notFound();
  }

  const messages = await getMessages();
  const isRtl = locale === "fa";
  const navUser = await getNavUser();

  /**
   * Font class strategy:
   *  - Persian (fa): Vazirmatn handles both Arabic/Persian + Latin fallback
   *  - English (en):  Plus Jakarta Sans (headings) + Inter (body)
   */
  const fontVars = isRtl
    ? `${vazirmatn.variable}`
    : `${plusJakartaSans.variable} ${inter.variable} ${vazirmatn.variable}`;

  return (
    <html
      lang={locale}
      dir={isRtl ? "rtl" : "ltr"}
      suppressHydrationWarning
      className={fontVars}
    >
      <head>
        <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
      </head>
      <body
        className={`min-h-screen bg-white text-neutral-900 dark:bg-neutral-950 dark:text-neutral-50 ${
          isRtl ? "font-vazirmatn" : "font-body"
        }`}
      >
        <NextIntlClientProvider messages={messages} locale={locale}>
          <DirectionProvider dir={isRtl ? "rtl" : "ltr"}>
            <SiteChrome user={navUser}>{children}</SiteChrome>
          </DirectionProvider>
        </NextIntlClientProvider>
      </body>
    </html>
  );
}
