/* app.jsx — routes between the public site (site.jsx) and /admin (admin.jsx) */

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

/* colours for the admin panel, matching the site */
const ADMIN_PALETTE = {
  bg: "#FFFBF8",
  surface: "#FFFFFF",
  ink: "#34343D",
  ink2: "#57545E",
  accent: "#983F5B",
  line: "rgba(52,52,61,.13)",
};

function normalizePath(p){
  p = String(p || "/").replace(/\/+$/, "");
  return p || "/";
}

function App(){
  const [path, setPath] = useAppState(() => {
    // old single-file links (#/book, #/blog-amit) → clean addresses
    const h = window.location.hash;
    if (/^#\/[\w-]+/.test(h)) {
      let page = h.slice(2).split("/")[0];
      page = page === "index" ? "/home" : page.startsWith("blog-") ? "/blog/" + page.slice(5) : "/" + page;
      window.history.replaceState({}, "", page);
      return page;
    }
    return normalizePath(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);
  }, []);

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

  if (path === "/admin") {
    return <div className="admin-root" style={{ background: ADMIN_PALETTE.bg, color: ADMIN_PALETTE.ink }}><AdminApp palette={ADMIN_PALETTE}/></div>;
  }
  return <Site path={path}/>;
}

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