import type { Metadata } from "next";
import { headers } from "next/headers";
import Script from "next/script";
import "./markup/loading-style.css";
import { BodyContent } from "./markup/body-content";
import { waterfallScript } from "./markup/waterfall-script";
import { domPatchScript } from "./markup/dom-patch-script";
import { SITE_URL, metadataForPath } from "./lib/seo";
import { SiteNavigationJsonLd, SiteOrganizationJsonLd } from "./markup/seo/json-ld";
import { cspMode } from "@/proxy";

/**
 * Site-wide defaults, which double as the home page's own metadata. Each route
 * below overrides title/description/canonical with its own entry.
 *
 * No title `template` here on purpose: buildPageMetadata already appends the
 * brand for non-root paths, so a template would render "Contact Us | Oxyfinz |
 * Oxyfinz".
 */
export const metadata: Metadata = {
  metadataBase: new URL(SITE_URL),
  ...metadataForPath("/"),
  other: {
    "pw:has-visual-script": "false",
  },
};

export function generateViewport() {
  return { themeColor: "#000000" };
}

export default async function RootLayout({ children }: LayoutProps<"/">) {
  /*
   * Only reach for the nonce when a CSP is actually being sent. Reading
   * headers() opts the whole tree into dynamic rendering, so with CSP_MODE=off
   * this branch is what keeps the eight prerendered routes static.
   */
  const nonce =
    cspMode() === "off" ? undefined : (await headers()).get("x-nonce") ?? undefined;

  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        {/* The PeachWeb 3D scene (script.js) loads its Draco decoder from a
            relative "draco/" path, resolved against the current URL. That's
            fine at "/contact" (one segment strips to root) but breaks on any
            deeper route like "/blogs/[slug]" ("/blogs/draco/..." 404s). A
            base tag pins every relative resolution on the page to site root
            regardless of route depth - the app's own links are already all
            root-relative or absolute, so this doesn't change their behavior. */}
        <base href="/" />
        <link href="/website-base.css" rel="stylesheet" />
        <link href="/styles.css" rel="stylesheet" />
        <link href="/fonts.css" rel="stylesheet" />
        {/* PeachWeb pins its router to "/" via _pwInitialPath, then rewrites
            the address bar to "/". Keep that pin so its homepage animations
            still init, but restore the real Next.js path after each rewrite. */}
        <Script
          id="pwb-init"
          nonce={nonce}
          strategy="beforeInteractive"
          dangerouslySetInnerHTML={{
            __html: `window._pwInitialPath = "/"; window.process = window.process || { env: {} };
(function () {
  var real = location.pathname + location.search + location.hash;
  if (real === "/" || real === "") return;
  var replace = history.replaceState.bind(history);
  var push = history.pushState.bind(history);
  function keep(orig) {
    return function () {
      orig.apply(null, arguments);
      if (location.pathname === "/") replace(history.state, "", real);
    };
  }
  history.replaceState = keep(replace);
  history.pushState = keep(push);
})();`,
          }}
        />
        {process.env.NODE_ENV === "development" && (
          <Script
            id="dom-patch"
            nonce={nonce}
            strategy="beforeInteractive"
            dangerouslySetInnerHTML={{ __html: domPatchScript }}
          />
        )}
        <Script id="pwb-runtime" src="/script.js" nonce={nonce} strategy="beforeInteractive" />
        <link rel="preload" href="/scene-state/a8b60272-8f15-49e5-8c0e-b1f124eb5086.json" as="fetch" crossOrigin="anonymous" />
        <link rel="preload" href="/pw-assets/website/526f7f45-ddce-4dea-8944-feeeabe4a0a8/shape-three-coin-v2-optimize.glb" as="fetch" crossOrigin="anonymous" />
        <link rel="preload" href="/pw-assets/website/661425f6-869f-468d-8b75-b910d858dc96/coin-v2-optimize.glb" as="fetch" crossOrigin="anonymous" />
        <link rel="preload" href="/ui-state.json" as="fetch" crossOrigin="anonymous" />
      </head>
      <body id="i6mb" suppressHydrationWarning>
        <SiteOrganizationJsonLd />
        <SiteNavigationJsonLd />
        <BodyContent>{children}</BodyContent>
        <Script id="pwb-waterfall" nonce={nonce} strategy="beforeInteractive" dangerouslySetInnerHTML={{ __html: waterfallScript }} />
      </body>
    </html>
  );
}
