/* ============================================================
   APP — router, page transitions, motion glue
   ============================================================ */
function App() {
  const { Header, Home, CaseStudy, About, Contact } = window;
  const [route, setRoute] = useState({ page: "home" });
  const [wipe, setWipe] = useState(null);        // null | 'cover' | 'reveal'
  const [contactOpen, setContactOpen] = useState(false);
  const [mutedMap, setMutedMap] = useState({});  // slug -> false if unmuted
  const pendingRoute = useRef(null);
  const timers = useRef([]);

  const toggleMute = useCallback((slug) => {
    setMutedMap((m) => ({ ...m, [slug]: m[slug] === false ? true : false }));
  }, []);

  // navigate with a timed ink wipe (cover -> swap -> reveal)
  const go = useCallback((next) => {
    if (next.page === route.page && next.slug === route.slug) return;
    timers.current.forEach(clearTimeout);
    timers.current = [];
    pendingRoute.current = next;
    setWipe("cover");
    timers.current.push(setTimeout(() => {
      setRoute(pendingRoute.current);
      window.scrollTo(0, 0);
      setWipe("reveal");
      timers.current.push(setTimeout(() => setWipe(null), 620));
    }, 540));
  }, [route]);

  useEffect(() => () => timers.current.forEach(clearTimeout), []);

  // header blends over the dark wordmark / dark hero on home + case pages near top
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const blend = false; // keep header in ink on warm paper for legibility

  return (
    <React.Fragment>
      <Header route={route} go={go} openContact={() => setContactOpen(true)} blend={blend} />

      <main className={"view view-" + route.page} key={route.page + (route.slug || "")}>
        {route.page === "home" && <Home go={go} mutedMap={mutedMap} toggleMute={toggleMute} />}
        {route.page === "case" && <CaseStudy slug={route.slug} go={go} mutedMap={mutedMap} toggleMute={toggleMute} />}
        {route.page === "about" && <About go={go} openContact={() => setContactOpen(true)} />}
      </main>

      <Contact open={contactOpen} onClose={() => setContactOpen(false)} />

      {wipe && (
        <div className={"page-wipe " + wipe}></div>
      )}
    </React.Fragment>
  );
}

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