/* App.jsx — full portfolio composition.
   Single morphing nav (transparent at hero → floating pill on scroll).
   Sections snap. Active section is tracked by IntersectionObserver. */
function App() {
  const heroRef    = React.useRef(null);
  const workRef    = React.useRef(null);
  const meaiRef    = React.useRef(null);
  const aboutRef   = React.useRef(null);
  const contactRef = React.useRef(null);
  const scrollerRef = React.useRef(null);

  const [active, setActive] = React.useState('hero');

  React.useEffect(() => {
    const root = scrollerRef.current;
    if (!root) return;

    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const mid = root.scrollTop + root.clientHeight * 0.5;
        const sections = [
          ['hero',    heroRef.current],
          ['work',    workRef.current],
          ['meai',    meaiRef.current],
          ['about',   aboutRef.current],
          ['contact', contactRef.current],
        ].filter(([, el]) => el);

        let current = sections[0][0];
        for (const [id, el] of sections) {
          if (el.offsetTop <= mid) current = id;
        }
        setActive(current);
      });
    };

    root.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => root.removeEventListener('scroll', onScroll);
  }, []);

  const scrollTo = (id, instant = false) => {
    const map = { hero: heroRef, work: workRef, meai: meaiRef, about: aboutRef, contact: contactRef };
    const el = map[id]?.current;
    if (!el) return;
    el.scrollIntoView({ behavior: instant ? 'instant' : 'smooth', block: 'start' });
  };

  React.useEffect(() => {
    const hash = window.location.hash.replace('#', '');
    if (!hash) return;
    setTimeout(() => scrollTo(hash, true), 50);
  }, []);

  return (
    <div className="page" ref={scrollerRef}>
      <Nav active={active} scrollerRef={scrollerRef} onNav={scrollTo} />

      <section ref={heroRef} data-section="hero" data-screen-label="01 Hero" className="snap-section section-hero">
        <Hero
          onSeeWork={() => scrollTo('work')}
          onContact={() => scrollTo('contact')}
        />
      </section>

      <section ref={workRef} data-section="work" data-screen-label="02 Case studies" className="snap-section section-work">
        <Work />
      </section>

      <section ref={meaiRef} data-section="meai" data-screen-label="03 Me & AI" className="snap-section section-meai">
        <MeAI />
      </section>

      <section ref={aboutRef} data-section="about" data-screen-label="04 About me" className="snap-section section-about">
        <About />
      </section>

      <PinGate />
      <section ref={contactRef} data-section="contact" data-screen-label="05 Get in touch" className="snap-section section-contact">
        <Contact />
        <Footer />
      </section>
    </div>
  );
}
window.App = App;
