import type { Metadata } from "next";
import { ThemeProvider } from "next-themes";
import { Toaster } from "sonner";
import { SkipLink } from "@/components/layout/skip-link";
import { I18nProvider, LOCALE_COOKIE, LOCALE_STORAGE_KEY } from "@/lib/i18n";
import { QueryProvider } from "@/lib/query-client";
import { siteConfig } from "@/lib/site-config";
// Self-hosted variable fonts (no CDN dependency): shipped as static assets by the
// bundler, so builds stay offline-safe. Cairo carries the Arabic glyphs — Latin
// text keeps using Inter, so numbers and dates stay in their Latin form.
import "@fontsource-variable/inter";
import "@fontsource-variable/cairo";
import "@fontsource-variable/jetbrains-mono";
import "./globals.css";

export const metadata: Metadata = {
  metadataBase: new URL(siteConfig.url),
  title: {
    default: `${siteConfig.fullName} | ${siteConfig.name}`,
    template: `%s | ${siteConfig.name}`,
  },
  description: siteConfig.description,
  applicationName: siteConfig.name,
  keywords: [
    "whatsapp backup",
    "archive",
    "messages",
    "media",
    "search",
    "نسخ احتياطي واتساب",
    "أرشفة محادثات",
  ],
  openGraph: {
    type: "website",
    title: siteConfig.fullName,
    description: siteConfig.description,
    url: siteConfig.url,
    siteName: siteConfig.name,
  },
  twitter: {
    card: "summary",
    title: siteConfig.fullName,
    description: siteConfig.description,
  },
  robots: { index: false, follow: false },
};

/**
 * Applied BEFORE first paint (the trick next-themes uses for the dark class):
 * a stored English preference flips `<html>` to ltr/en immediately, so nobody
 * ever sees an Arabic right-to-left frame before React takes over.
 */
const LOCALE_BOOTSTRAP = `(function(){try{var m=document.cookie.match(/(?:^|;\\s*)${LOCALE_COOKIE}=([^;]+)/);var l=m?m[1]:localStorage.getItem("${LOCALE_STORAGE_KEY}");if(l==="en"||l==="ar"){var d=document.documentElement;d.lang=l;d.dir=l==="ar"?"rtl":"ltr";}}catch(e){}})();`;

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="ar" dir="rtl" suppressHydrationWarning className="h-full antialiased">
      <head>
        <script dangerouslySetInnerHTML={{ __html: LOCALE_BOOTSTRAP }} />
      </head>
      <body className="flex min-h-full flex-col font-sans" suppressHydrationWarning>
        <I18nProvider>
          <SkipLink />
          <QueryProvider>
            <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
              {children}
              <Toaster position="top-center" richColors closeButton />
            </ThemeProvider>
          </QueryProvider>
        </I18nProvider>
      </body>
    </html>
  );
}
