import type { Metadata, Viewport } from "next";
import { Cairo, Inter } from "next/font/google";
import "./globals.css";
import { LANGS, SITE, UI, type Lang } from "@/lib/config";
import { getAppBaseUrl, getAlternateUrls } from "@/lib/url";
import SystemMessagePopup from "@/components/SystemMessagePopup";
import { getCspNonce } from "@/lib/csp";
import { CspNonceProvider } from "@/hooks/useCspNonce";
import { ClerkProvider } from "@clerk/nextjs";

// Clerk is only active when the publishable key is configured.
// When absent, the app falls back to NextAuth (default auth provider).
const CLERK_ENABLED = Boolean(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY);

// Optimized font loading with display swap for better performance
// Preload only critical fonts, fallback for others
const cairo = Cairo({
  subsets: ["arabic"],
  variable: "--font-ar",
  display: "swap",
  preload: true,
  fallback: ["system-ui", "arial"],
  adjustFontFallback: true,
});

const inter = Inter({
  subsets: ["latin"],
  variable: "--font-en",
  display: "swap",
  preload: true,
  fallback: ["system-ui", "arial"],
  adjustFontFallback: true,
});

export const metadata: Metadata = {
  metadataBase: new URL(`https://${SITE.domain}`),
  title: {
    default: SITE.brand,
    template: `%s | ${SITE.brand}`,
  },
  description: "GCC AI receptionist for clinics & aesthetics.",
};

type LayoutParams = {
  lang?: Lang;
};

export default function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: LayoutParams;
}) {
  const nonce = getCspNonce();
  // For non-localized routes (e.g., /staff), force English
  // Only use defaultLang when we have a valid lang param from [lang] routes
  const lang = params.lang && LANGS.includes(params.lang) ? params.lang : "en";
  const dict = UI[lang];

  return (
    <html
      lang={lang}
      dir={dict.dir}
      className={`${cairo.variable} ${inter.variable}`}
      suppressHydrationWarning
    >
      <head>
        {/* DNS Prefetch for faster external resource loading */}
        <link rel="dns-prefetch" href="https://fonts.googleapis.com" />
        <link
          rel="preconnect"
          href="https://fonts.gstatic.com"
          crossOrigin="anonymous"
        />
        {/* Preconnect to Clerk for faster auth widget loading */}
        <link
          rel="preconnect"
          href="https://clerk.accounts.dev"
          crossOrigin="anonymous"
        />
        <link
          rel="preconnect"
          href="https://img.clerk.com"
          crossOrigin="anonymous"
        />
        <meta name="csp-nonce" content={nonce} />
      </head>
      <body className="antialiased bg-white text-brand-ink transition-colors dark:bg-slate-950 dark:text-slate-100">
        {CLERK_ENABLED ? (
          <ClerkProvider
            nonce={nonce}
            afterSignOutUrl={`/${lang}/clerk-login`}
            signInUrl={`/${lang}/clerk-login`}
            signUpUrl={`/${lang}/clerk-signup`}
          >
            <CspNonceProvider nonce={nonce}>
              {children}
              <SystemMessagePopup />
            </CspNonceProvider>
          </ClerkProvider>
        ) : (
          <CspNonceProvider nonce={nonce}>
            {children}
            <SystemMessagePopup />
          </CspNonceProvider>
        )}
      </body>
    </html>
  );
}
