/* Pinned parallax transformation ⭐ — the vehicle stays fixed while the world
   shifts through four phases: Warning → Scan → Translate → Decide.
   Scroll-scrubbed, with a scan line and progress dots. */
function PinnedTransform() {
  const { Ic } = window;
  const light = window.useTheme() === 'light';
  const wrapRef = React.useRef(null);
  const [p, setP] = React.useState(0); // 0..1 overall progress

  React.useEffect(() => {
    const wrap = wrapRef.current; if (!wrap) return;
    let last = -1;
    const update = (sy, vh) => {
      const r = wrap.getBoundingClientRect();
      // cull: only compute while the pinned section is on/near screen
      if (r.bottom < 0 || r.top > vh) {
        const edge = r.top > vh ? 0 : 1;
        if (last !== edge) { last = edge; setP(edge); }
        return;
      }
      const total = r.height - vh;
      const prog = total > 0 ? Math.min(Math.max(-r.top / total, 0), 1) : 0;
      const q = Math.round(prog * 400) / 400; // quantize → skip redundant renders
      if (q !== last) { last = q; setP(q); }
    };
    return window.ALEROQScroll.subscribe(update);
  }, []);

  const phases = [
    { key: 'warn', label: 'Warning', icon: 'TriangleAlert', col: 'var(--accent)',
      head: 'A light comes on.', sub: 'Something\u2019s wrong \u2014 but the dashboard won\u2019t say what, how serious, or what it costs.' },
    { key: 'scan', label: 'Scan', icon: 'ScanLine', col: 'var(--accent)',
      head: 'ALEROQ reads the car.', sub: 'Live fault codes and sensor data pulled straight from the OBD-II port in seconds.' },
    { key: 'translate', label: 'Translate', icon: 'Languages', col: 'var(--silver-300)',
      head: 'Plain English, instantly.', sub: 'P0301 becomes \u201ccylinder 1 misfire \u2014 likely a worn ignition coil. Not urgent.\u201d' },
    { key: 'decide', label: 'Decide', icon: 'BadgeCheck', col: 'var(--positive-bright)',
      head: 'You decide with clarity.', sub: 'Compare real, vetted offers scored on value \u2014 then book with confidence.' },
  ];
  const seg = Math.min(Math.floor(p * 4), 3);
  const local = Math.min((p * 4) - seg, 1); // 0..1 within current phase
  const cur = phases[seg];

  // glow eases red -> green across the whole journey
  const glow = `radial-gradient(closest-side, ${seg >= 3
    ? 'rgba(22,214,128,0.34), rgba(22,214,128,0.06) 58%, transparent 78%'
    : 'rgba(255,46,63,0.32), rgba(255,46,63,0.06) 56%, transparent 76%'})`;

  return (
    <section ref={wrapRef} aria-label="How a warning becomes a decision" style={{
      position: 'relative', height: '420vh',
    }}>
      <div style={{
        position: 'sticky', top: 0, height: '100vh', overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {/* vehicle (pinned), subtle counter-zoom as you progress */}
        <div style={{
          position: 'absolute', inset: 0, zIndex: 0,
          backgroundImage: 'url("hero-car.png")', backgroundSize: 'cover', backgroundPosition: 'center',
          transform: `scale(${1.08 + p * 0.06})`, transition: 'transform 0.1s linear',
          filter: seg >= 3 ? 'saturate(1.05)' : 'saturate(0.92)',
        }} />
        {/* darkening / lightening wash — tinted to the active theme so the
            pinned car reads against the page in both modes, fading to the
            page colour at top and bottom */}
        <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none',
          background: light
            ? 'linear-gradient(180deg, #f3f3f7, rgba(243,243,247,0.42) 30%, rgba(243,243,247,0.5) 70%, #f3f3f7)'
            : 'linear-gradient(180deg, rgba(11,11,13,0.7), rgba(11,11,13,0.45) 30%, rgba(11,11,13,0.55) 70%, rgba(11,11,13,0.92))' }} />
        <div style={{ position: 'absolute', top: '50%', left: '50%', width: 'min(1100px, 120vw)', height: 760,
          transform: 'translate(-50%,-50%)', zIndex: 1, pointerEvents: 'none',
          background: glow, mixBlendMode: 'screen', transition: 'background 0.5s var(--ease-out)' }} />

        {/* scan line — visible mainly during the Scan phase */}
        <div style={{
          position: 'absolute', left: 0, right: 0, height: 3, zIndex: 2, pointerEvents: 'none',
          top: `${12 + local * 76}%`,
          opacity: seg === 1 ? 1 : 0, transition: 'opacity 0.4s var(--ease-out)',
          background: 'linear-gradient(90deg, transparent, var(--accent), transparent)',
          boxShadow: '0 0 22px rgba(255,46,63,0.8)',
        }} />

        {/* progress dots */}
        <div className="pin-dots" style={{
          position: 'absolute', left: 'clamp(20px, 5vw, 56px)', top: '50%', transform: 'translateY(-50%)', zIndex: 4,
          display: 'flex', flexDirection: 'column', gap: 22,
        }}>
          {phases.map((ph, i) => {
            const active = i === seg, done = i < seg;
            return (
              <div key={ph.key} style={{ display: 'flex', alignItems: 'center', gap: 12, opacity: active ? 1 : done ? 0.7 : 0.38,
                transition: 'opacity 0.4s var(--ease-out)' }}>
                <span style={{
                  width: 11, height: 11, borderRadius: '50%',
                  background: active || done ? ph.col : 'transparent',
                  border: `1px solid ${active || done ? ph.col : 'var(--border-hover)'}`,
                  boxShadow: active ? `0 0 12px ${ph.col}` : 'none', transition: 'all 0.4s var(--ease-out)',
                }} />
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.12em',
                  textTransform: 'uppercase', color: active ? 'var(--text-strong)' : 'var(--text-muted)' }}>{ph.label}</span>
              </div>
            );
          })}
        </div>

        {/* phase content card */}
        <div style={{ position: 'relative', zIndex: 3, maxWidth: 620, padding: '0 clamp(20px, 5vw, 48px)', textAlign: 'center' }}>
          <div key={cur.key} className="phase-pop" style={{
            display: 'inline-flex', alignItems: 'center', gap: 9, padding: '7px 15px', marginBottom: 22,
            borderRadius: 'var(--radius-pill)', border: `1px solid ${cur.col}`, color: cur.col,
            background: light ? 'rgba(255,255,255,0.72)' : 'rgba(14,14,18,0.6)', backdropFilter: 'blur(10px)',
            fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase',
          }}>
            <Ic name={cur.icon} size={15} color={cur.col} /> {cur.label}
          </div>
          <h2 key={cur.key + 'h'} className="phase-pop" style={{
            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'clamp(34px, 5.5vw, 68px)',
            letterSpacing: 'var(--ls-tight)', lineHeight: 1.04, color: 'var(--text-strong)', margin: '0 0 18px', textWrap: 'balance',
            textShadow: light ? '0 2px 30px rgba(243,243,247,0.7)' : '0 4px 50px rgba(0,0,0,0.6)',
          }}>{cur.head}</h2>
          <p key={cur.key + 'p'} className="phase-pop" style={{
            fontSize: 'var(--fs-lead)', lineHeight: 1.55, color: 'var(--text-body)', margin: '0 auto', maxWidth: 460, textWrap: 'pretty',
          }}>{cur.sub}</p>
        </div>

        <div style={{ position: 'absolute', bottom: 26, left: '50%', transform: 'translateX(-50%)', zIndex: 4,
          fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: 'var(--text-faint)' }}>
          {Math.round(p * 100)}%
        </div>
      </div>
    </section>
  );
}
window.PinnedTransform = PinnedTransform;
