// Man + Machine — root app
const { useState, useEffect, useRef } = React;

function App() {
  const [activePilot, setActivePilot] = useState(null);
  const [active, setActive] = useState("top");

  // scroll spy
  useEffect(() => {
    const ids = ["top", ...MM_DATA.nav.map((n) => n.id)];
    const f = () => {
      const y = window.scrollY + 140;
      let cur = "top";
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) cur = id;
      }
      setActive(cur);
    };
    f(); window.addEventListener("scroll", f, { passive: true });
    return () => window.removeEventListener("scroll", f);
  }, []);

  // reveal observer
  useEffect(() => {
    const els = document.querySelectorAll("[data-reveal]");
    // Immediate fallback: reveal anything already in or near the viewport on mount,
    // so users never see a blank page if IntersectionObserver fires late.
    const reveal = (el) => el.classList.add("in");
    const initialPass = () => {
      const vh = window.innerHeight || 800;
      els.forEach((el) => {
        const r = el.getBoundingClientRect();
        if (r.top < vh * 1.1) reveal(el);
      });
    };
    initialPass();

    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          reveal(e.target);
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.08, rootMargin: "0px 0px -10% 0px" });
    els.forEach((el) => io.observe(el));

    // Safety net: if observer never fires (some iframe contexts), reveal everything
    // after a short delay so content is always visible.
    const safety = setTimeout(() => els.forEach(reveal), 1200);

    return () => { io.disconnect(); clearTimeout(safety); };
  }, []);

  // lock scroll when drawer open
  useEffect(() => {
    document.body.style.overflow = activePilot ? "hidden" : "";
  }, [activePilot]);

  const nav = (id) => {
    const el = document.getElementById(id === "top" ? "top" : id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <React.Fragment>
      <Nav active={active} onNav={nav} />
      <main className="shell">
        <Hero />
        <Thesis />
        <WhyNow />
        <Slate onOpen={setActivePilot} />
        <Model />
        <Capital />
        <Engine />
        <Contact />
      </main>
      <Foot />
      <Drawer pilot={activePilot} onClose={() => setActivePilot(null)} />
    </React.Fragment>
  );
}

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