import type { Metadata } from "next";
import Script from "next/script";
import { Quicksand, Nunito, Playfair_Display } from "next/font/google";
import "./globals.css";
import { SiteHeader } from "@/components/site-header";
import { SiteFooter } from "@/components/site-footer";
import { SiteChrome } from "@/components/site-chrome";
import { getGlobalContent } from "@/lib/global";
import { WEDIGTECH_ICON_URL } from "@/lib/constants";

const gaId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;

const quicksand = Quicksand({
  variable: "--font-quicksand",
  subsets: ["latin"],
  weight: ["500", "600", "700"],
  display: "swap",
});

const nunito = Nunito({
  variable: "--font-nunito",
  subsets: ["latin"],
  weight: ["400", "500", "600", "700", "800"],
  display: "swap",
});

const playfair = Playfair_Display({
  variable: "--font-playfair",
  subsets: ["latin"],
  weight: ["400", "500", "600", "700"],
  style: ["normal", "italic"],
  display: "swap",
});

// Real domain isn't live yet (site is still on a raw IP) — SITE_URL lets every
// page's canonical/OG/sitemap URLs switch to the real domain later by just
// changing this one env var, no code change needed.
const SITE_URL = process.env.SITE_URL || "http://3.7.0.49:3000";

export async function generateMetadata(): Promise<Metadata> {
  const global = await getGlobalContent();
  return {
    metadataBase: new URL(SITE_URL),
    title: global.siteTitle,
    description: global.siteDescription,
    openGraph: {
      title: global.siteTitle,
      description: global.siteDescription,
      siteName: "wedigtech",
      type: "website",
      images: [{ url: WEDIGTECH_ICON_URL }],
    },
    twitter: {
      card: "summary_large_image",
      title: global.siteTitle,
      description: global.siteDescription,
      images: [WEDIGTECH_ICON_URL],
    },
  };
}

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const global = await getGlobalContent();

  return (
    <html
      lang="en"
      className={`${quicksand.variable} ${nunito.variable} ${playfair.variable} h-full`}
    >
      <body className="min-h-full flex flex-col bg-paper text-ink">
        {gaId && (
          <>
            <Script
              src={`https://www.googletagmanager.com/gtag/js?id=${gaId}`}
              strategy="afterInteractive"
            />
            <Script id="google-analytics" strategy="afterInteractive">
              {`
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${gaId}');
              `}
            </Script>
          </>
        )}
        {/*
          On-device debug console — ONLY active when the URL has ?debug=1.
          Written in hand-rolled ES5 so it parses on old Safari (15) even if the
          main app bundle does not, and registers its error listener before the
          bundle runs so it captures the SyntaxError that kills hydration.
          Surfaces errors in a red box at the top + loads Eruda for a full
          console. Safe to leave in: no-op for normal visitors.
        */}
        <Script
          id="ios-debug"
          strategy="beforeInteractive"
          dangerouslySetInnerHTML={{
            __html: `
              window.__errors = [];
              window.addEventListener('error', function(e) {
                window.__errors.push('ERROR: ' + (e.message || JSON.stringify(e)));
              });
              window.addEventListener('unhandledrejection', function(e) {
                window.__errors.push('REJECTION: ' + (e.reason && e.reason.message ? e.reason.message : JSON.stringify(e.reason)));
              });
              if (location.search.indexOf('debug=1') > -1) {
                var box = document.createElement('div');
                box.id = 'debug-box';
                box.style.position = 'fixed';
                box.style.top = '0';
                box.style.left = '0';
                box.style.right = '0';
                box.style.zIndex = '99999';
                box.style.background = '#b00';
                box.style.color = '#fff';
                box.style.padding = '10px';
                box.style.font = '11px monospace';
                box.style.overflowY = 'auto';
                box.style.maxHeight = '50%';
                box.textContent = 'Debug active. Waiting for errors...';
                document.body ? document.body.appendChild(box) : document.documentElement.appendChild(box);
                setInterval(function() {
                  if (window.__errors.length) {
                    box.textContent = window.__errors.join('\\n');
                  }
                }, 500);
              }
            `,
          }}
        />
        <SiteChrome
          header={<SiteHeader navLinks={global.navLinks} logo={global.logo} />}
          footer={<SiteFooter global={global} />}
        >
          {children}
        </SiteChrome>
      </body>
    </html>
  );
}
