// Registers whichever theme this build was compiled with.
// Set by npm run theme:use.
import "@/lib/theme-active";

import Script from "next/script";
import type { Metadata } from "next";
import "./globals.css";
import { LocaleProvider } from "@/lib/locale-context";
import { ModulesProvider } from "@/lib/modules";
import { SiteProvider } from "@/lib/site-context";
import { ConfirmProvider } from "@/components/ConfirmDialog";
import { AuthProvider } from "@/lib/auth-context";
import { CurrencyProvider } from "@/lib/currency";
import { ThemeProvider } from "@/lib/theme-context";
import { AppShell } from "@/components/AppShell";

export const metadata: Metadata = {
  title: "XRcoin Clone — local dev",
  description: "Local scaffold replicating xrcoin.social's UI",
};

// Runs before paint so there's no flash of the wrong theme on load.
/** The analytics snippet an admin pasted, if any. */
async function trackingSnippet() {
  const { getDb } = await import("@/lib/db");
  const db = await getDb();
  const s = db.data.siteSettings as Record<string, unknown>;
  if (s.analyticsEnabled !== true) return null;
  const code = String(s.trackingCode ?? "").trim();
  return code || null;
}

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className="h-full antialiased" suppressHydrationWarning>
      <head>
        {/* A file rather than inline: React won't run a script it renders
            itself, and the theme has to be applied before the first paint
            or a dark page flashes white on the way in. */}
        <script src="/theme-init.js" />

        {/* The active theme, served rather than compiled in — which is
            what lets a bought theme take effect without a rebuild. */}
        <link rel="stylesheet" href="/api/theme" />
      </head>
      <body className="min-h-full flex bg-neutral-100 text-neutral-900 dark:bg-neutral-950 dark:text-neutral-50">
        {await trackingSnippet().then((code) =>
          code ? (
            // Pasted by an admin, so it goes in as given.
            <Script
              id="xr-tracking"
              strategy="afterInteractive"
              dangerouslySetInnerHTML={{ __html: code }}
            />
          ) : null
        )}
        <ThemeProvider>
          <CurrencyProvider>
          <AuthProvider>
          <ConfirmProvider>
          <SiteProvider>
          <ModulesProvider>
          <LocaleProvider>
            <AppShell>{children}</AppShell>
            </LocaleProvider>
          </ModulesProvider>
          </SiteProvider>
          </ConfirmProvider>
        </AuthProvider>
        </CurrencyProvider>
        </ThemeProvider>
      </body>
    </html>
  );
}
