import type { Metadata, Viewport } from "next";
import { cookies } from "next/headers";
import { Providers } from "@/components/providers";
import AgeGate from "@/components/shared/age-gate";
import CookieConsent from "@/components/shared/cookie-consent";
import PwaInstallPrompt from "@/components/shared/pwa-install-prompt";
import ServiceWorkerRegistrar from "@/components/shared/service-worker-registrar";
import AiChatWidget from "@/components/shared/ai-chat-widget";
// Self-hosted fonts via @fontsource. R13 C.4: dropped Inter weight 500
// (~28 KB WOFF2) — the codebase has no `font-medium` in custom CSS, and
// Tailwind's medium utility interpolates between 400/600 from the variable
// font without a measurable visible difference. Round 11 reverted next/font
// when the build host couldn't reach Google Fonts; fontsource ships the
// WOFF2 inside the npm package so builds never hit the network.
import "@fontsource/inter/400.css";
import "@fontsource/inter/600.css";
import "@fontsource/inter/700.css";
import "@fontsource/playfair-display/400.css";
import "@fontsource/playfair-display/600.css";
import "@fontsource/playfair-display/700.css";
import "./globals.css";

export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  viewportFit: "cover",
};

export const metadata: Metadata = {
  title: {
    default: "AdultWorld - Premium Escort Directory & Adult Services",
    template: "%s | AdultWorld",
  },
  description:
    "AdultWorld is a premium adult services directory featuring verified escorts, webcam performers, and content creators worldwide.",
  metadataBase: new URL(process.env.NEXT_PUBLIC_APP_URL || "https://www.adultworld.ai"),
  openGraph: {
    type: "website",
    siteName: "AdultWorld",
    locale: "en_US",
  },
  robots: {
    index: true,
    follow: true,
  },
  other: {
    "apple-mobile-web-app-title": "AdultWorld",
  },
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const cookieStore = await cookies();
  const ageVerified = cookieStore.get("age_verified_uk")?.value === "1";
  const locale = cookieStore.get("locale")?.value || "en";

  let messages = {};
  try {
    messages = (await import(`../../messages/${locale}.json`)).default;
  } catch {
    messages = (await import("../../messages/en.json")).default;
  }

  const baseUrl = "https://www.adultworld.ai";
  const organizationLd = {
    "@context": "https://schema.org",
    "@type": "Organization",
    name: "AdultWorld",
    url: baseUrl,
    logo: `${baseUrl}/logo.png`,
    description:
      "Premium adult services directory featuring verified escorts, webcam performers, and content creators worldwide.",
    contactPoint: {
      "@type": "ContactPoint",
      email: "hello@adultworld.ai",
      contactType: "Customer Support",
      availableLanguage: ["English", "Spanish", "German", "French"],
    },
  };
  const websiteLd = {
    "@context": "https://schema.org",
    "@type": "WebSite",
    name: "AdultWorld",
    url: baseUrl,
    inLanguage: ["en", "es", "de", "fr"],
    potentialAction: {
      "@type": "SearchAction",
      target: {
        "@type": "EntryPoint",
        urlTemplate: `${baseUrl}/search?keyword={search_term_string}`,
      },
      "query-input": "required name=search_term_string",
    },
  };

  return (
    <html lang={locale} className="dark">
      <head>
        {/* C.11: warm up the storage origin so the first image round-trip
            skips DNS+TLS handshake (saves 60–120 ms). */}
        {process.env.R2_PUBLIC_URL && (
          <>
            <link rel="preconnect" href={process.env.R2_PUBLIC_URL} />
            <link rel="dns-prefetch" href={process.env.R2_PUBLIC_URL} />
          </>
        )}
        <link rel="manifest" href="/manifest.json" />
        <meta name="theme-color" content="#c9a96e" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
        <link rel="apple-touch-icon" href="/icons/icon-192.png" />
        {/* R17 B.6: iPad Add-to-Home-Screen prefers 180×180. Point at
            the same source PNG — iOS scales without visible artifacts
            and avoids the blurry-icon issue from missing this size. */}
        <link rel="apple-touch-icon" sizes="180x180" href="/icons/icon-192.png" />
        <meta name="apple-mobile-web-app-title" content="AdultWorld" />
        <link rel="alternate" hrefLang="en" href="https://www.adultworld.ai" />
        <link rel="alternate" hrefLang="es" href="https://www.adultworld.ai" />
        <link rel="alternate" hrefLang="de" href="https://www.adultworld.ai" />
        <link rel="alternate" hrefLang="fr" href="https://www.adultworld.ai" />
        <link rel="alternate" hrefLang="x-default" href="https://www.adultworld.ai" />
        {/* Site-wide Organization + WebSite JSON-LD. Helps Google attach a
            sitelinks-search-box to organic results and gives AI crawlers a
            stable identity for the brand. */}
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(organizationLd) }}
        />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(websiteLd) }}
        />
      </head>
      <body className="bg-background text-text antialiased">
        {/* Keyboard-only users land here first; activating jumps past the
            navigation/sidebar to the page content (#main lives in (main)/layout). */}
        <a
          href="#main"
          className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 focus:z-50 focus:rounded-md focus:bg-primary focus:px-4 focus:py-2 focus:text-white focus:outline-2 focus:outline-white"
        >
          Skip to content
        </a>
        <ServiceWorkerRegistrar />
        {!ageVerified && <AgeGate />}
        <Providers locale={locale} messages={messages}>
          {children}
        </Providers>
        {ageVerified && <CookieConsent />}
        {ageVerified && <PwaInstallPrompt />}
        {ageVerified && <AiChatWidget />}
      </body>
    </html>
  );
}
