function App() {
  const [page, setPage] = useState(() => {
    try { return localStorage.getItem("stz_page") || "home"; }
    catch { return "home"; }
  });
  const [openPost, setOpenPost] = useState(null);

  function go(p) {
    setPage(p);
    setOpenPost(null);
    try { localStorage.setItem("stz_page", p); } catch {}
    window.scrollTo({ top: 0, behavior: "smooth" });
    history.replaceState(null, "", "#" + p);
  }
  function openPostFn(post) {
    setOpenPost(post);
    setPage("post");
    window.scrollTo({ top: 0, behavior: "smooth" });
    history.replaceState(null, "", "#post");
  }

  useEffect(() => {
    const onClick = (e) => {
      const a = e.target.closest("[data-nav]");
      if (a) { e.preventDefault(); go(a.dataset.nav); }
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  useEffect(() => {
    const h = location.hash.replace("#", "");
    if (h && ["home", "about", "work", "services", "insights", "contact"].includes(h)) {
      setPage(h);
    }
  }, []);

  useEffect(() => {
    const fab = document.querySelector(".fab");
    if (!fab) return;
    const onScroll = () => {
      if (window.scrollY > 600 && page !== "contact") fab.classList.add("is-visible");
      else fab.classList.remove("is-visible");
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [page]);

  useEffect(() => {
    const bar = document.getElementById("scroll-bar");
    if (!bar) return;
    const onScroll = () => {
      const h = document.documentElement;
      const p = (h.scrollTop) / (h.scrollHeight - h.clientHeight);
      bar.style.width = Math.min(100, Math.max(0, p * 100)) + "%";
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const Pages = {
    home: window.HomePage,
    about: window.AboutPage,
    work: window.WorkPage,
    services: window.ServicesPage,
    insights: window.InsightsPage,
    contact: window.ContactPage,
  };

  let content;
  if (page === "post" && openPost) {
    content = <window.PostPage post={openPost} onGo={go} onOpenPost={openPostFn} />;
  } else {
    const Cur = Pages[page] || Pages.home;
    content = <Cur onGo={go} onOpenPost={openPostFn} />;
  }

  return (
    <>
      <Nav current={page === "post" ? "insights" : page} onGo={go} />
      <main key={page + (openPost?.title || "")}>{content}</main>
      <Footer onGo={go} />
    </>
  );
}

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