// Hero.jsx — Cinematic scroll-collapse hero.
// The hero is a 200vh-tall stage. Its inner content is pinned (position: sticky).
// As the user scrolls through that stage, the centered brand animates to the
// top-left nav slot, and the real hero content (eyebrow, title, sub, CTAs, meta)
// reveals in sequenced layers. A parent CSS var `--hero-collapse` (0→1) drives
// the Nav's own brand fade-in so the handoff is seamless.

const { useEffect: useEffectH, useRef: useRefH } = React;

function Hero({ onApply }) {
  const sectionRef = useRefH(null);
  const stageRef = useRefH(null);
  const brandRef = useRefH(null);
  const markRef = useRefH(null);
  const wmRef = useRefH(null);
  const contentRef = useRefH(null);
  const starsRef = useRefH(null);
  const pathWrapRef = useRefH(null);
  const pathRef = useRefH(null);
  const glowRef = useRefH(null);

  // Draw in the flight path once on mount
  useEffectH(() => {
    const p = pathRef.current;
    if (!p) return;
    const len = p.getTotalLength();
    p.style.strokeDasharray = len;
    p.style.strokeDashoffset = len;
    requestAnimationFrame(() => {
      p.style.transition = 'stroke-dashoffset 1800ms cubic-bezier(0.2, 0.8, 0.2, 1)';
      p.style.strokeDashoffset = 0;
    });
  }, []);

  useEffectH(() => {
    const scroller = document.querySelector('.site-scroll') || window;
    const section = sectionRef.current;
    const brand = brandRef.current;
    const mark = markRef.current;
    const wm = wmRef.current;
    const content = contentRef.current;
    if (!section || !brand || !mark || !wm || !content) return;

    const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
    const easeInOut    = (t) => t < 0.5 ? 2*t*t : 1 - Math.pow(-2*t + 2, 2) / 2;
    const clamp = (v, a=0, b=1) => Math.max(a, Math.min(b, v));
    const range = (v, a, b) => clamp((v - a) / (b - a));

    let ticking = false;

    const update = () => {
      ticking = false;
      const y = scroller === window ? window.scrollY : scroller.scrollTop;
      const vh = window.innerHeight;
      const collapseTravel = vh * 1.0;
      const p = clamp(y / collapseTravel);

      document.documentElement.style.setProperty('--hero-collapse', p.toFixed(4));

      const navBrandTarget = document.querySelector('.al-nav-brand-slot');
      const stage = stageRef.current;
      if (!stage) return;

      const stageRect = stage.getBoundingClientRect();

      let targetX = 32, targetY = 20, targetScale = 0.18;
      if (navBrandTarget) {
        const t = navBrandTarget.getBoundingClientRect();
        targetX = t.left - stageRect.left;
        targetY = t.top - stageRect.top;
        targetScale = 32 / 180;
      }

      const stageW = stageRect.width;
      const stageH = stageRect.height;
      const brandNaturalW = brand.offsetWidth;
      const brandNaturalH = brand.offsetHeight;
      const startX = (stageW - brandNaturalW) / 2;
      const startY = (stageH - brandNaturalH) / 2 - stageH * 0.08;

      const eased = easeInOut(p);
      const tx = startX + (targetX - startX) * eased;
      const ty = startY + (targetY - startY) * eased;
      const scale = 1 + (targetScale - 1) * eased;

      brand.style.transform = `translate3d(${tx}px, ${ty}px, 0) scale(${scale})`;
      brand.style.transformOrigin = '0 0';
      brand.style.opacity = (1 - clamp(range(p, 0.88, 1.0)) * 1).toFixed(3);

      // Content reveal: sequenced layers
      const reveal = (start, end) => easeOutCubic(range(p, start, end));
      const layers = content.querySelectorAll('[data-layer]');
      const steps = [
        [0.18, 0.38],
        [0.26, 0.50],
        [0.36, 0.60],
        [0.46, 0.70],
        [0.56, 0.80],
      ];
      layers.forEach((el, i) => {
        const [a, b] = steps[i] || [0, 1];
        const t = reveal(a, b);
        el.style.opacity = t.toFixed(3);
        el.style.transform = `translate3d(0, ${(1 - t) * 24}px, 0)`;
      });

      // Background parallax
      if (starsRef.current) starsRef.current.style.transform = `translate3d(0, ${y * 0.18}px, 0)`;
      if (pathWrapRef.current) pathWrapRef.current.style.transform = `translate3d(0, ${-y * 0.08}px, 0)`;
      if (glowRef.current) {
        glowRef.current.style.transform = `translate3d(0, ${-y * 0.22}px, 0)`;
        glowRef.current.style.opacity = (1 - p * 0.6).toFixed(3);
      }
    };

    const onScroll = () => { if (!ticking) { requestAnimationFrame(update); ticking = true; } };
    const onResize = () => update();

    update();
    scroller.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResize);
    return () => {
      scroller.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
      document.documentElement.style.removeProperty('--hero-collapse');
    };
  }, []);

  return (
    <section id="top" className="al-hero al-hero-cinematic" ref={sectionRef}>
      <div className="al-hero-stage" ref={stageRef}>
        {/* Backgrounds */}
        <div className="al-hero-bg">
          <div className="al-stars" ref={starsRef} />
          <div className="al-flightpath-wrap" ref={pathWrapRef}>
            <svg className="al-flightpath" viewBox="0 0 1440 720" preserveAspectRatio="none">
              <path ref={pathRef} d="M -40 620 Q 420 380 780 340 T 1500 120"
                    fill="none" stroke="#60A5FA" strokeWidth="2" strokeDasharray="6 6" opacity="0.8"/>
            </svg>
          </div>
          <div className="al-sun-glow" ref={glowRef} />
        </div>

        {/* Collapsing brand — starts huge centered, lands in nav slot */}
        <div className="al-hero-brand" ref={brandRef}>
          <img ref={markRef} className="al-hero-mark" src="assets/logomark-white.png" alt=""/>
          <span ref={wmRef} className="al-hero-wm">AeroLabs</span>
        </div>

        {/* Hero content that reveals in sequence */}
        <div className="al-hero-content" ref={contentRef}>
          <div className="al-eyebrow al-eyebrow-hero" data-layer="eyebrow">
            ENGINEERING THE FUTURE · AUSTIN, TX · SATURDAYS · 100% FREE
          </div>
          <h1 className="al-hero-h1" data-layer="title">
            Aviation & aerospace<br/>
            engineering, <em>for you.</em>
          </h1>
          <p className="al-hero-sub" data-layer="sub">
            AeroLabs is a free, student-led academy that removes the barriers between
            curious young students and the aviation and aerospace careers they dream of.
            Hands-on, from day one.
          </p>
          <div className="al-hero-ctas" data-layer="ctas">
            <button className="al-btn al-btn-primary al-btn-lg" onClick={onApply}>
              Join the program (free)
              <i data-lucide="arrow-right" />
            </button>
            <a href="#program" className="al-btn al-btn-ghost-on-dark al-btn-lg">
              Learn more
            </a>
          </div>
          <div className="al-hero-meta" data-layer="meta">
            <div><span className="al-meta-k">8-WEEK</span><span className="al-meta-v">program</span></div>
            <div><span className="al-meta-k">10+</span><span className="al-meta-v">min age</span></div>
            <div><span className="al-meta-k">SAT</span><span className="al-meta-v">10:00–12:00</span></div>
          </div>
        </div>

        {/* Soft transition into next section */}
        <div className="al-hero-fade" aria-hidden="true" />

        {/* Scroll hint */}
        <div className="al-scroll-hint" aria-hidden="true">
          <span>Scroll</span>
          <div className="al-scroll-hint-track"><div className="al-scroll-hint-dot"/></div>
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
