// Intro.jsx — quirky branded opening curtain.
// Data dots rain + converge into the decision peak, MYRA snaps in,
// a counter ticks 0→100, then the curtain splits and wipes away.
function Intro() {
  const [phase, setPhase] = React.useState('run'); // run -> lift -> gone
  const [count, setCount] = React.useState(0);
  const doneRef = React.useRef(false);

  const finish = React.useCallback(() => {
    if (doneRef.current) return;
    doneRef.current = true;
    setCount(100);
    setPhase('lift');
    document.body.classList.add('w-loaded');
    setTimeout(() => setPhase('gone'), 1150); // after curtain wipe
  }, []);

  React.useEffect(() => {
    // lock scroll while the curtain is up
    document.body.classList.add('w-intro-lock');
    const start = performance.now();
    const DUR = 1700;
    let raf = 0;
    const tick = (now) => {
      const p = Math.min(1, (now - start) / DUR);
      // easeOutCubic
      const eased = 1 - Math.pow(1 - p, 3);
      setCount(Math.round(eased * 100));
      if (p < 1) raf = requestAnimationFrame(tick);
      else finish();
    };
    raf = requestAnimationFrame(tick);
    const safety = setTimeout(finish, 3200); // never trap the user
    return () => { cancelAnimationFrame(raf); clearTimeout(safety); };
  }, [finish]);

  React.useEffect(() => {
    if (phase === 'gone') document.body.classList.remove('w-intro-lock');
  }, [phase]);

  if (phase === 'gone') return null;

  // dot grid coords (5 → 3 → 2) matching the logo mark
  const dots = [
    [8,11],[20,11],[32,11],[44,11],[56,11],
    [20,25],[32,25],[44,25],
    [26,39],[38,39],
  ];

  return (
    <div className={`w-intro${phase === 'lift' ? ' is-lift' : ''}`} onClick={finish} role="presentation">
      <div className="w-intro__panel w-intro__panel--t" />
      <div className="w-intro__panel w-intro__panel--b" />
      <div className="w-intro__core">
        <svg className="w-intro__mark" viewBox="0 0 64 64" aria-hidden="true">
          {dots.map(([cx, cy], i) => (
            <circle key={i} cx={cx} cy={cy} r="3" className="w-intro__dot" style={{ animationDelay: (i * 70) + 'ms' }} />
          ))}
          <path d="M 32 47 L 41 61 L 23 61 Z" className="w-intro__peak" />
        </svg>
        <div className="w-intro__word" aria-label="Myra">
          {'MYRA'.split('').map((ch, i) => (
            <span key={i} className="w-intro__char" style={{ animationDelay: (480 + i * 90) + 'ms' }}>{ch}</span>
          ))}
        </div>
        <div className="w-intro__meter">
          <span className="w-intro__meter-label">Decoding data</span>
          <span className="w-intro__meter-count">{String(count).padStart(3, '0')}</span>
        </div>
        <div className="w-intro__bar"><span className="w-intro__bar-fill" style={{ width: count + '%' }} /></div>
      </div>
      <span className="w-intro__skip">Click to skip</span>
    </div>
  );
}
Object.assign(window, { Intro });
