/* ============================================================
   App: routing, theme application, tweaks.
   ============================================================ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "midnight",
  "accent": "oklch(0.7 0.15 35)",
  "hero": "split",
  "density": "regular"
}/*EDITMODE-END*/;

const ACCENTS = [
  "oklch(0.7 0.15 35)",   // coral
  "oklch(0.72 0.15 70)",  // amber
  "oklch(0.68 0.15 150)", // green
  "oklch(0.65 0.15 250)", // blue
  "oklch(0.62 0.16 300)", // violet
];

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const games = window.GAMES;
  const newGame = games.find((g) => g.isNew) || games[0];

  // route: {name:'home'|'game'|'privacy'|'terms', id?, scroll?}
  // Legal pages use the same hash URLs as the live site: #privacypolicy and #terms.
  const ROUTE_HASH = { privacy: "privacypolicy", terms: "terms" };
  const HASH_ROUTE = { privacypolicy: "privacy", terms: "terms" };
  const routeFromHash = () => {
    const h = window.location.hash.replace(/^#/, "").toLowerCase();
    return HASH_ROUTE[h] ? { name: HASH_ROUTE[h] } : null;
  };

  const [route, setRoute] = React.useState(() => routeFromHash() || { name: "home" });

  const go = React.useCallback((r) => {
    const hash = ROUTE_HASH[r.name];
    if (hash) {
      if (window.location.hash !== "#" + hash) window.location.hash = hash;
    } else if (window.location.hash) {
      history.replaceState(null, "", window.location.pathname + window.location.search);
    }
    setRoute(r);
    if (r.name === "home") {
      if (r.scroll) {
        requestAnimationFrame(() => {
          const el = document.getElementById(r.scroll);
          if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 64, behavior: scrollBehavior() });
        });
      } else {
        window.scrollTo({ top: 0, behavior: "auto" });
      }
    } else {
      window.scrollTo({ top: 0, behavior: "auto" });
    }
  }, []);

  // Sync browser back/forward + direct hash loads.
  React.useEffect(() => {
    const onHash = () => { setRoute(routeFromHash() || { name: "home" }); window.scrollTo({ top: 0, behavior: "auto" }); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  useReveal();

  // SPA focus management: on a real page change (not in-page scroll), move focus
  // to the main landmark so screen-reader and keyboard users land on the new
  // content instead of being stranded on a control that just disappeared.
  const mainRef = React.useRef(null);
  const firstRender = React.useRef(true);
  React.useEffect(() => {
    if (firstRender.current) { firstRender.current = false; return; }
    if (mainRef.current) mainRef.current.focus({ preventScroll: true });
  }, [route.name, route.id]);

  const current = route.name === "game" ? games.find((g) => g.id === route.id) : null;
  const legalDoc = route.name === "privacy" ? window.LEGAL.privacy : route.name === "terms" ? window.LEGAL.terms : null;

  return (
    <div className="app" data-direction={t.direction} data-density={t.density} data-hero={t.hero} style={{ "--accent": t.accent }}>
      <a className="skip-link" href="#main">Skip to content</a>
      <Nav go={go} route={route} />
      <main id="main" tabIndex={-1} ref={mainRef}>
        {route.name === "home" ? (
          <React.Fragment>
            <Hero go={go} game={newGame} />
            <Why go={go} />
            <Catalog go={go} games={games} />
            <Reviews go={go} games={games} reviews={window.REVIEWS} />
            <CTABand game={newGame} />
          </React.Fragment>
        ) : legalDoc ? (
          <LegalPage go={go} doc={legalDoc} />
        ) : (
          <GamePage go={go} game={current} games={games} />
        )}
      </main>
      <Footer go={go} />

      <TweaksPanel>
        <TweakSection label="Direction" />
        <TweakRadio label="Theme" value={t.direction}
          options={[{ value: "midnight", label: "Midnight" }, { value: "daylight", label: "Daylight" }, { value: "editorial", label: "Editorial" }]}
          onChange={(v) => setTweak("direction", v)} />
        <TweakSection label="Style" />
        <TweakColor label="Accent" value={t.accent} options={ACCENTS} onChange={(v) => setTweak("accent", v)} />
        <TweakRadio label="Hero layout" value={t.hero}
          options={[{ value: "split", label: "Split" }, { value: "centered", label: "Centered" }]}
          onChange={(v) => setTweak("hero", v)} />
        <TweakRadio label="Density" value={t.density}
          options={[{ value: "compact", label: "Compact" }, { value: "regular", label: "Regular" }, { value: "comfy", label: "Comfy" }]}
          onChange={(v) => setTweak("density", v)} />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
