import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { onFirstPageReady } from "@/lib/prerenderState";

declare global {
  interface Window { SEO_REDIRECT_HOSTS?: Record<string, string> }
}

// After a new deploy, an open tab may request page chunks that no longer exist.
// Reload once to pick up the fresh build instead of showing a blank screen.
const RELOAD_KEY = "chunk-reload-at";
const recoverStaleChunk = () => {
  const last = Number(sessionStorage.getItem(RELOAD_KEY) || 0);
  if (Date.now() - last < 10_000) return false;
  sessionStorage.setItem(RELOAD_KEY, String(Date.now()));
  window.location.reload();
  return true;
};
window.addEventListener("vite:preloadError", (event) => {
  if (recoverStaleChunk()) event.preventDefault();
});
window.addEventListener("unhandledrejection", (event) => {
  const msg = String((event.reason as Error)?.message || event.reason || "");
  if (/Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module/i.test(msg)) {
    if (recoverStaleChunk()) event.preventDefault();
  }
});

// A connected host that must never serve this site: the inline head script has
// already sent the visitor to the Ops Club homepage, so nothing here may mount.
if (window.SEO_REDIRECT_HOSTS?.[window.location.hostname]) {
  document.getElementById("root")?.replaceChildren();
} else {
  mount();
}

function mount() {
  const container = document.getElementById("root")!;
  const staticPage = container.querySelector(":scope > [data-prerender]");
  // The inline head script sets pr-on only on hosts that show ops-lab.co content.
  const keepStatic = !!staticPage && document.documentElement.classList.contains("pr-on");

  if (staticPage && !keepStatic) staticPage.remove();
  // No prerendered screen to preserve: keep today's entrance animations.
  if (!keepStatic) document.documentElement.classList.remove("pr-on", "pr-nobanner");

  if (staticPage && keepStatic) {
    // Render the live app off-screen, then swap it in once the first page has
    // committed, so the prerendered screen never blanks or replays.
    const live = document.createElement("div");
    // Same layout width as #root (it lives inside it), hidden from pointer and
    // assistive tech until the swap so only one tree is ever exposed.
    live.style.cssText = "position:absolute;top:0;left:0;width:100%;visibility:hidden;pointer-events:none";
    live.setAttribute("aria-hidden", "true");
    live.setAttribute("inert", "");
    container.appendChild(live);

    // First-click capture lives in the inline head script (it must run before
    // this bundle loads); it stores the control's data-pr-click on window.__prClick.
    const w = window as Window & { __prClick?: string | null };

    const replay = () => {
      const key = w.__prClick;
      w.__prClick = null;
      if (!key) return;
      const target = live.querySelector<HTMLElement>(`[data-pr-click="${CSS.escape(key)}"]`);
      if (!target) return;
      // Radix menu triggers open on pointerdown; plain buttons and links on click.
      target.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, button: 0, pointerType: "mouse", isPrimary: true }));
      target.click();
    };

    let swapped = false;
    const swap = () => {
      if (swapped) return;
      swapped = true;
      const y = window.scrollY;
      staticPage.remove(); // removed before exposing live tree: no duplicate IDs
      live.removeAttribute("style");
      live.removeAttribute("aria-hidden");
      live.removeAttribute("inert");
      window.scrollTo(0, y);
      // Next frame: let the live tree settle as the visible, interactive copy first.
      requestAnimationFrame(() => setTimeout(replay, 0));
    };
    onFirstPageReady(() => requestAnimationFrame(swap));
    // Safety net: if the ready signal never comes, show the app if it rendered;
    // otherwise keep the static screen (error fallback).
    window.setTimeout(() => {
      if (swapped) return;
      console.warn("[prerender] swap timed out after 10s", { rendered: live.childElementCount > 0 });
      if (live.childElementCount) swap();
    }, 10000);
    createRoot(live).render(<App />);
  } else {
    createRoot(container).render(<App />);
  }
}
