// karm.dev — Intro animation
// Phase 1: K-logo appears (0-800ms)
// Phase 2: "a", "r", "m", ".", "d", "e", "v" type in one-by-one to the right (800-2200ms)
// Phase 3: Full hold (2200-2700ms)
// Phase 4: Fade out (2700-3200ms)

function IntroAnimation({ onDone }) {
  const [phase, setPhase] = React.useState('logo');
  const [typed, setTyped] = React.useState(0);

  const REST = ['a', 'r', 'm', '.', 'd', 'e', 'v'];

  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase('typing'), 750);
    return () => clearTimeout(t1);
  }, []);

  React.useEffect(() => {
    if (phase !== 'typing') return;
    if (typed >= REST.length) {
      const t = setTimeout(() => setPhase('fade'), 650);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setTyped(n => n + 1), 140);
    return () => clearTimeout(t);
  }, [phase, typed]);

  React.useEffect(() => {
    if (phase !== 'fade') return;
    const t = setTimeout(() => { onDone?.(); }, 550);
    return () => clearTimeout(t);
  }, [phase, onDone]);

  return (
    <div className={`intro-v2 intro-v2--${phase}`} aria-hidden="true">
      <div className="intro-v2__stage">
        <div className="intro-v2__mark">
          <svg width="112" height="112" viewBox="0 0 32 32" fill="none">
            <rect width="32" height="32" rx="8" fill="#0F172E"/>
            <path
              className="intro-v2__k-path"
              d="M10 9v14M10 16l7-7M10 16l7 7"
              stroke="#10B981"
              strokeWidth="2.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>
        <span className="intro-v2__wordmark">
          {REST.slice(0, typed).map((ch, i) => (
            <span
              key={i}
              className={`intro-v2__char${ch === '.' ? ' intro-v2__dot' : ''}`}
            >
              {ch}
            </span>
          ))}
          {phase === 'typing' && typed < REST.length && (
            <span className="intro-v2__caret" />
          )}
        </span>
      </div>
      <div className="intro-v2__sub">
        <span className="intro-v2__sub-prompt">$</span>
        <span>
          {phase === 'logo' && 'booting portfolio...'}
          {phase === 'typing' && 'loading modules'}
          {(phase === 'fade') && 'ready ✓'}
        </span>
      </div>
    </div>
  );
}

window.IntroAnimation = IntroAnimation;
