/* App — hash router, view transitions, mount */

function readHash() {
  const h = (location.hash || "").replace(/^#\/?/, "");
  if (!h || h === "home" || h === "index") return { name: "home" };
  if (h === "manifesto" || h === "how-i-think") return { name: "manifesto" };
  if (h === "contact") return { name: "contact" };
  const m = h.match(/^project\/(.+)$/);
  if (m) {
    const exists = DATA.projects.some((p) => p.id === m[1]);
    return exists ? { name: "project", id: m[1] } : { name: "notfound" };
  }
  return { name: "notfound" };
}
function writeHash(v) {
  if (v.name === "notfound") return; // keep the bad URL the visitor typed
  const h = v.name === "home" ? "#/" : v.name === "manifesto" ? "#/manifesto" : v.name === "contact" ? "#/contact" : `#/project/${v.id}`;
  if (location.hash !== h) location.hash = h;
}

function App() {
  const [view, setView] = useState(readHash());

  useEffect(() => { history.scrollRestoration = "manual"; }, []);
const go = useCallback((v) => {
  const veil = document.getElementById("veil");
  veil.classList.add("veil-in");
  setTimeout(() => {
    ReactDOM.flushSync(() => setView(v));
    writeHash(v);
    requestAnimationFrame(() => requestAnimationFrame(() => {
      scrollTo({ top: 0, behavior: "instant" })
      veil.classList.remove("veil-in");
    }));
  }, 200);
}, []);

  useEffect(() => {
    const onHash = () => setView(readHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Dismiss the initial loading screen once above-the-fold (non-lazy) images
  // have settled. Lazy images don't block; a timeout guards against stalls.
  useEffect(() => {
    const hide = () => window.__hideLoader && window.__hideLoader();
    const imgs = Array.from(document.images).filter((img) => img.loading !== "lazy");
    if (!imgs.length) { hide(); return; }

    let remaining = imgs.length;
    let done = false;
    const settle = () => { if (--remaining <= 0 && !done) { done = true; hide(); } };

    imgs.forEach((img) => {
      if (img.complete) settle();
      else {
        img.addEventListener("load", settle, { once: true });
        img.addEventListener("error", settle, { once: true });
      }
    });

    const t = setTimeout(() => { if (!done) { done = true; hide(); } }, 5000);
    return () => clearTimeout(t);
  }, []);

  return (
    <>
      <Nav view={view} go={go} />
      {view.name === "home" && <Home key="home" go={go} />}
      {view.name === "project" && <CaseStudy key={"p-" + view.id} id={view.id} go={go} />}
      {view.name === "manifesto" && <Manifesto key="man" go={go} />}
      {view.name === "contact" && <Contact key="contact" go={go} />}
      {view.name === "notfound" && <NotFound key="404" go={go} />}
    </>
  );
}

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