/* app.jsx — main production composition */

const { useEffect: useEff, useState: useAppState } = React;

function App(){
  const palette = PALETTES.terracotta;
  const fonts   = FONT_PAIRS.editorial;
  const density = "regular";
  const [path, setPath] = useAppState(() => normalizePathname(window.location.pathname));
  const [, setContentVersion] = useAppState(0);

  // load editable content from Supabase (falls back to bundled defaults), and
  // re-render whenever content changes (initial load or an admin save)
  useEff(() => {
    const bump = () => setContentVersion((v) => v + 1);
    window.addEventListener("content-updated", bump);
    if (window.loadContent) window.loadContent();
    return () => window.removeEventListener("content-updated", bump);
  }, []);

  // expose tokens to css
  useEff(() => {
    const r = document.documentElement;
    r.style.setProperty("--bg",      palette.bg);
    r.style.setProperty("--ink",     palette.ink);
    r.style.setProperty("--accent",  palette.accent);
    r.style.setProperty("--font-display", `"${fonts.display}"`);
    r.style.setProperty("--font-body",    `"${fonts.body}"`);
    r.setAttribute("data-density", density);
    document.body.style.background = palette.bg;
    document.body.style.color = palette.ink;
  }, [palette, fonts, density]);

  useEff(() => {
    updateSeoMeta(path);
  }, [path]);

  useEff(() => {
    const onPopState = () => setPath(normalizePathname(window.location.pathname));
    const onClick = (event) => {
      const link = event.target.closest && event.target.closest("a[href]");
      if (!link || link.target || link.hasAttribute("download")) return;
      const url = new URL(link.href, window.location.href);
      if (url.origin !== window.location.origin) return;
      if (url.hash && normalizePathname(url.pathname) === normalizePathname(window.location.pathname)) return;
      event.preventDefault();
      window.history.pushState({}, "", url.pathname + url.search + url.hash);
      setPath(normalizePathname(url.pathname));
      window.scrollTo({ top: 0, behavior: "smooth" });
    };
    window.addEventListener("popstate", onPopState);
    document.addEventListener("click", onClick);
    return () => {
      window.removeEventListener("popstate", onPopState);
      document.removeEventListener("click", onClick);
    };
  }, []);

  return (
    <div style={{ background: palette.bg, color: palette.ink, fontFamily: `"${fonts.body}", system-ui, sans-serif` }}>
      {path === "/admin"
        ? <AdminApp palette={palette}/>
        : (
          <PageShell palette={palette}>
            <SitePage path={path} palette={palette}/>
          </PageShell>
        )}
    </div>
  );
}

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