// App entrypoint: active-section tracking, smooth scrolling, IO reveals.

function useScrollSpy(ids, offset = 120) {
  const [active, setActive] = React.useState(ids[0]);
  React.useEffect(() => {
    function onScroll() {
      const y = window.scrollY + offset;
      let current = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) current = id;
      }
      // bottom of page → last section
      if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 4) {
        current = ids[ids.length - 1];
      }
      setActive(current);
    }
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, [ids.join(","), offset]);
  return active;
}

function useReveals() {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("is-visible");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

function App() {
  const ids = NAV_ITEMS.map(n => n.id);
  const active = useScrollSpy(ids, 140);
  useReveals();

  const onJump = React.useCallback((id) => {
    const el = document.getElementById(id);
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - 80;
    window.scrollTo({ top, behavior: "smooth" });
  }, []);

  return (
    <React.Fragment>
      <Header active={active} onJump={onJump}/>
      <main>
        <Hero onJump={onJump}/>
        <Reasons/>
        <Works onJump={onJump}/>
        <Pricing/>
        <Flow/>
        <Profile/>
        <Contact/>
      </main>
      <Footer onJump={onJump}/>
    </React.Fragment>
  );
}

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