// Hero.jsx — pinned hero that scales down as you scroll, hint fades in.
function Hero() {
  const wrapRef = React.useRef(null);
  const centerRef = React.useRef(null);
  const hintRef = React.useRef(null);
  const ctaRef = React.useRef(null);
  const pillRef = React.useRef(null);
  const isoRef = React.useRef(null);
  const flowRef = React.useRef(null);

  React.useEffect(() => {
    let raf = 0;
    const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const wrap = wrapRef.current;
        if (!wrap || !centerRef.current) return;
        const rect = wrap.getBoundingClientRect();
        const total = rect.height - window.innerHeight;
        const p = total > 0 ? clamp(-rect.top / total, 0, 1) : 0;
        const scale = 1 - p * 0.42;
        centerRef.current.style.transform = `scale(${scale}) translateY(${-p * 40}px)`;
        const fadeOut = String(clamp(1 - p / 0.28, 0, 1));
        if (ctaRef.current) ctaRef.current.style.opacity = fadeOut;
        if (pillRef.current) pillRef.current.style.opacity = fadeOut;
        if (flowRef.current) flowRef.current.style.opacity = fadeOut;
        if (hintRef.current) hintRef.current.style.opacity = String(clamp((p - 0.4) / 0.32, 0, 1));
        if (isoRef.current) isoRef.current.style.transform = `translateY(${p * -80}px) rotate(${-8 + p * 30}deg)`;
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); cancelAnimationFrame(raf); };
  }, []);

  return (
    <header className="w-hero" id="top" ref={wrapRef} style={{ height: '178vh' }}>
      <div className="w-hero__sticky">
        <div className="w-hero__bg" />
        <span className="w-spark w-hero__spark1" />
        <span className="w-spark w-hero__spark2" />
        <span className="w-spark w-hero__spark3" />
        <div className="w-hero__tokens" aria-hidden="true">
          <span className="w-tok w-tok--l1">users.csv</span>
          <span className="w-tok w-tok--r1">legacy.db</span>
          <span className="w-tok w-tok--l2">SELECT *</span>
          <span className="w-tok w-tok--r2">api/v2</span>
          <span className="w-tok w-tok--l3">churn?</span>
          <span className="w-tok w-tok--r3">$2.4M</span>
        </div>

        <div className="w-hero__flow" ref={flowRef} aria-hidden="true">
          <span className="w-flow__stream w-flow__stream--l">
            <i></i><i></i><i></i><i></i>
          </span>
          <span className="w-flow__core">
            <span className="w-flow__ring"></span>
            <span className="w-flow__ring"></span>
            <span className="w-flow__node">
              <span className="w-flow__bar w-flow__bar--s"></span>
              <span className="w-flow__bar w-flow__bar--l"></span>
            </span>
          </span>
          <span className="w-flow__stream w-flow__stream--r">
            <i></i><i></i><i></i><i></i>
          </span>
        </div>

        <div className="w-hero__iso" ref={isoRef}>
          <div className="w-iso"><div className="w-iso__check"><span className="w-iso__bar w-iso__bar--short" /><span className="w-iso__bar w-iso__bar--long" /></div></div>
        </div>

        <div className="w-hero__inner">
          <div className="w-hero__center" ref={centerRef}>
            <p className="w-eyebrow w-hero__eyebrow">Boutique data &amp; AI consultancy</p>
            <h1 className="w-hero__line">
              <Spell text="We turn raw data" base={0} />
              <br />
              <Spell text="into " base={16} />
              <FlipWord words={['decisions', 'dashboards', 'clarity', 'revenue', 'answers']} base={21} />
            </h1>
          </div>
          <div className="w-hero__cta" ref={ctaRef}>
            <a href="#contact" className="w-btn w-btn--dark" data-cursor="let's talk">Book a discovery call <span className="w-btn__arrow" aria-hidden>→</span></a>
            <a href="#services" className="w-btn w-btn--outline">See what we do</a>
          </div>
        </div>

        <p className="w-hero__hint" ref={hintRef}>But what does that actually mean?</p>
        <a href="#services" className="w-hero__scroll-pill" ref={pillRef}>
          Scroll and see how <span className="dot"><span aria-hidden>↓</span></span>
        </a>
      </div>
    </header>
  );
}

// Spell — splits text into spring-in letters (fire after .w-loaded).
function Spell({ text, base = 0 }) {
  return text.split('').map((ch, i) => (
    <span
      key={i}
      className="w-letter"
      style={{ animationDelay: (260 + (base + i) * 28) + 'ms' }}
    >{ch === ' ' ? '\u00A0' : ch}</span>
  ));
}

// FlipWord — the outcome word cycles with a snappy vertical flip.
// Spells in first (joining the hero intro), then begins rotating.
function FlipWord({ words, base = 0 }) {
  const [i, setI] = React.useState(0);
  const [spin, setSpin] = React.useState(false); // false during intro spell-in
  React.useEffect(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) return;
    let to, iv;
    // begin cycling after the headline has fully spelled in
    to = setTimeout(() => {
      setSpin(true);
      iv = setInterval(() => setI(p => (p + 1) % words.length), 2100);
    }, 2600);
    return () => { clearTimeout(to); clearInterval(iv); };
  }, [words.length]);

  // longest word reserves the box width so layout never jumps
  const longest = words.reduce((a, b) => (b.length > a.length ? b : a), '');
  return (
    <span className="w-hl w-flip" data-cursor="∞">
      <span className="w-flip__clip">
        <span className="w-flip__ghost" aria-hidden>{longest}</span>
        {spin ? (
          <span key={i} className="w-flip__word">{words[i]}</span>
        ) : (
          <span className="w-flip__word w-flip__word--intro">
            {words[0].split('').map((ch, k) => (
              <span key={k} className="w-letter" style={{ animationDelay: (260 + (base + k) * 28) + 'ms' }}>{ch}</span>
            ))}
          </span>
        )}
      </span>
    </span>
  );
}
Object.assign(window, { Hero });
