import type { Metadata, Viewport } from "next";
import { headers } from "next/headers";
import { Cairo } from "next/font/google";
import { dir } from "@/lib/i18n";
import { getCurrentUser } from "@/lib/api";
import { LocaleProvider } from "@/components/providers";
import { PwaRegister } from "@/components/PwaRegister";
import "./globals.css";

const cairo = Cairo({
  subsets: ["arabic", "latin"],
  variable: "--font-cairo",
  display: "swap",
});

export const metadata: Metadata = {
  title: {
    default: "بوصلة — اتحاد شباب الديمقراطى الاجتماعى | الذراع الشبابى للحزب المصرى الديمقراطى الاجتماعى",
    template: "%s — بوصلة",
  },
  description: "المنصة الرقمية لاتحاد شباب الحزب المصرى الديمقراطى الاجتماعى: العضوية، الهياكل والأمانات، التقارير، والمؤشرات — عربية وإنجليزية.",
};

export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  themeColor: "#072727",
};

/** Runs before first paint: restores the saved theme without a flash. */
const themeInit = `(function(){try{var t=localStorage.getItem("bousla_theme");if(t==="dark"||(!t&&window.matchMedia("(prefers-color-scheme: dark)").matches)){document.documentElement.classList.add("dark")}}catch(e){}})();`;

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  // CSP nonce issued per request by src/middleware.ts — attached to <html> (so Next
  // propagates it to its bootstrap scripts) and to our inline theme-init script.
  const nonce = (await headers()).get("x-nonce") ?? undefined;
  const user = await getCurrentUser();
  const cookieHeader = (await headers()).get("cookie") ?? "";
  const cookieLocale = /bousla_locale=en(?:;|$)/.test(cookieHeader) ? "en" : /bousla_locale=ar(?:;|$)/.test(cookieHeader) ? "ar" : null;
  const locale = user?.preferences?.locale ?? cookieLocale ?? "ar";
  const cookieTheme = /bousla_theme=dark/.test(cookieHeader) ? "dark" : /bousla_theme=light/.test(cookieHeader) ? "light" : null;
  const theme = user?.preferences?.theme ?? cookieTheme;
  // For signed-out visitors the early script restores the device theme before paint;
  // for signed-in users the server already resolved the persisted preference above.
  return (
    <html
      lang={locale}
      dir={dir(locale)}
      nonce={nonce}
      className={`${cairo.variable} ${theme === "dark" ? "dark" : ""}`.trim()}
      suppressHydrationWarning
    >
      <head>
        <link rel="manifest" href="/manifest.json" />
        <link rel="apple-touch-icon" href="/icon-192.png" />
        {!user && <script nonce={nonce} dangerouslySetInnerHTML={{ __html: themeInit }} />}
      </head>
      <body className="font-sans">
        <LocaleProvider locale={locale}>
          {children}
          <PwaRegister />
        </LocaleProvider>
      </body>
    </html>
  );
}
