import type { Metadata, Viewport } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { ReduxProvider } from "@/components/common/ReduxProvider";
import { GeneralSettingsProvider } from "@/lib/GeneralSettingsContext";
import { SidebarProvider } from "@/lib/SidebarContext";
import PlayerController from "@/components/player/PlayerController";
import { SplashWrapper } from "@/components/splash/SplashWrapper";
import { OneSignalInit } from "@/components/common/OneSignalInit";
import { LoginPromptProvider } from "@/lib/LoginPromptContext";
import { LoginPromptModal } from "@/components/auth/LoginPromptModal";
import { TEXT } from "@/branding/text";
import { COLORS, buildCssVars } from "@/branding/colors";
import { PersistentPlayerProvider } from "@/lib/PersistentPlayerContext";
import { LanguageProvider } from "@/i18n";
import { ThemeProvider } from "@/components/common/ThemeProvider";
import { GoogleAdsProvider } from "@/context/GoogleAdsContext";
import { MotionProvider } from "@/components/motion/MotionProvider";
import OnboardingScreen from "@/components/onboarding/OnboardingScreen";
import { WishlistProvider } from "@/lib/WishlistContext";
import { WishlistToast } from "@/components/marketplace/buyer/WishlistToast";
import { MessagingProvider } from "@/lib/MessagingContext";
import { PaymentProvider } from "@/lib/PaymentContext";
import { OrderProvider } from "@/lib/OrderContext";
import { FirebaseAuthSync } from "@/components/auth/FirebaseAuthSync";
import { Toaster } from "react-hot-toast";

const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH || "";

/* ─── Viewport (theme-color, safe area, etc.) ─────────────────────────────── */
export const viewport: Viewport = {
  themeColor: COLORS.primary,
  width: "device-width",
  initialScale: 1,
  maximumScale: 1,
  userScalable: false,
};

/* ─── Static Metadata ─────────────────────────────────────────────────────── */
export const metadata: Metadata = {
  /* Base URL — required for Open Graph / Twitter card image resolution.
     Falls back to localhost only in local dev. */
  metadataBase: new URL(
    process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000",
  ),

  /* Title */
  title: {
    default: `${TEXT.app.name} — ${TEXT.app.tagline}`,
    template: `%s | ${TEXT.app.name}`,
  },

  /* Basic */
  description: TEXT.app.description,
  applicationName: TEXT.app.name,
  keywords: [
    "Doliplay",
    "streaming",
    "video streaming",
    "short films",
    "music videos",
    "shorts",
    "podcast",
    "live radio",
    "watch online",
  ],
  authors: [{ name: "Doliplay" }],
  creator: "Doliplay",
  publisher: "Doliplay",
  category: "entertainment",

  /* Icons — mapped from actual files in /public */
  icons: {
    icon: [
      { url: `${BASE_PATH}/favicon.ico`, sizes: "any" },
      {
        url: `${BASE_PATH}/favicon-16x16.png`,
        sizes: "16x16",
        type: "image/png",
      },
      {
        url: `${BASE_PATH}/favicon-32x32.png`,
        sizes: "32x32",
        type: "image/png",
      },
      {
        url: `${BASE_PATH}/favicon-96x96.png`,
        sizes: "96x96",
        type: "image/png",
      },
    ],
    apple: [
      { url: `${BASE_PATH}/apple-icon-57x57.png`, sizes: "57x57" },
      { url: `${BASE_PATH}/apple-icon-60x60.png`, sizes: "60x60" },
      { url: `${BASE_PATH}/apple-icon-72x72.png`, sizes: "72x72" },
      { url: `${BASE_PATH}/apple-icon-76x76.png`, sizes: "76x76" },
      { url: `${BASE_PATH}/apple-icon-114x114.png`, sizes: "114x114" },
      { url: `${BASE_PATH}/apple-icon-120x120.png`, sizes: "120x120" },
      { url: `${BASE_PATH}/apple-icon-144x144.png`, sizes: "144x144" },
      { url: `${BASE_PATH}/apple-icon-152x152.png`, sizes: "152x152" },
      { url: `${BASE_PATH}/apple-icon-180x180.png`, sizes: "180x180" },
    ],
    other: [
      {
        rel: "apple-touch-icon-precomposed",
        url: "/apple-icon-precomposed.png",
      },
      { rel: "msapplication-TileImage", url: "/ms-icon-144x144.png" },
    ],
  },

  /* PWA manifest */
  manifest: `${BASE_PATH}/manifest.json`,

  /* Open Graph */
  openGraph: {
    type: "website",
    siteName: TEXT.app.name,
    title: `${TEXT.app.name} — ${TEXT.app.tagline}`,
    description: TEXT.app.description,
    images: [
      {
        url: `${BASE_PATH}/android-icon-192x192.png`,
        width: 192,
        height: 192,
        alt: TEXT.app.name,
      },
    ],
  },

  /* Twitter card */
  twitter: {
    card: "summary",
    title: `${TEXT.app.name} — ${TEXT.app.tagline}`,
    description: TEXT.app.description,
    images: [`${BASE_PATH}/android-icon-192x192.png`],
  },

  /* iOS web-app */
  appleWebApp: {
    capable: true,
    title: TEXT.app.name,
    statusBarStyle: "black-translucent",
    startupImage: `${BASE_PATH}/apple-icon-180x180.png`,
  },

  /* Windows tile */
  other: {
    "msapplication-TileColor": COLORS.primary,
    "msapplication-config": "/browserconfig.xml",
  },

  formatDetection: { telephone: false },
};

/* ─── Root Layout ─────────────────────────────────────────────────────────── */
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const cssVars = buildCssVars(COLORS);
  return (
    <html lang="en" suppressHydrationWarning>
      {/* suppressHydrationWarning: browser extensions (e.g. Polymer, Grammarly,
          LastPass) may inject <style> or <meta> tags into <head> before React
          hydrates, causing a text-content mismatch. This prop tells React to
          skip diffing <head> children — safe because <head> is static content. */}
      <head suppressHydrationWarning>
        <style suppressHydrationWarning>{`:root { ${cssVars} }`}</style>
        <meta name="msapplication-TileColor" content={COLORS.primary} />
        <meta name="msapplication-config" content="/browserconfig.xml" />
        {/* Modern equivalent of apple-mobile-web-app-capable (deprecated) */}
        <meta name="mobile-web-app-capable" content="yes" />
        {/* FOUC prevention: read persisted theme before React hydrates and
            apply the correct class so the first paint matches the user's choice */}
        <script
          suppressHydrationWarning
          dangerouslySetInnerHTML={{
            __html: `(function(){try{var r=localStorage.getItem('persist:doliplay-root');var m='light';if(r){var p=JSON.parse(r);if(p.theme){var t=JSON.parse(p.theme);if(t.mode)m=t.mode;}}var d=m==='dark'||(m==='system'&&matchMedia('(prefers-color-scheme: dark)').matches);if(d)document.documentElement.classList.add('dark');}catch(e){}})();`,
          }}
        />
      </head>
      {/* suppressHydrationWarning: browser extensions (Grammarly, Chext, LastPass etc.)
          inject data-* attributes into <body> before React hydrates, triggering a
          spurious mismatch warning. This prop suppresses it — safe because we don't
          render server-only children directly in <body>. */}
      <body
        suppressHydrationWarning
        className={`${inter.variable} font-sans antialiased`}
      >
        <ReduxProvider>
          <FirebaseAuthSync />
          <Toaster
            position="bottom-center"
            toastOptions={{
              duration: 3000,
              style: {
                marginBottom: "calc(84px + env(safe-area-inset-bottom, 0px))",
                background: "#1c1c1e",
                color: "#fff",
                maxWidth: "90vw",
              },
            }}
          />
          <OrderProvider>
            <PaymentProvider>
              <MessagingProvider>
                <WishlistProvider>
                  <WishlistToast />
                  <MotionProvider>
                    <ThemeProvider>
                      <LanguageProvider>
                        <PersistentPlayerProvider>
                          <LoginPromptProvider>
                            <GeneralSettingsProvider>
                              <GoogleAdsProvider>
                                <OneSignalInit />
                                <LoginPromptModal />
                                <SidebarProvider>
                                  <SplashWrapper>
                                    <PlayerController />
                                    <OnboardingScreen />
                                    {children}
                                  </SplashWrapper>
                                </SidebarProvider>
                              </GoogleAdsProvider>
                            </GeneralSettingsProvider>
                          </LoginPromptProvider>
                        </PersistentPlayerProvider>
                      </LanguageProvider>
                    </ThemeProvider>
                  </MotionProvider>
                </WishlistProvider>
              </MessagingProvider>
            </PaymentProvider>
          </OrderProvider>
        </ReduxProvider>
      </body>
    </html>
  );
}
