// Play section — typing test + mini chess

const SAMPLE_TEXTS = [
  "the quick brown fox jumps over the lazy dog while the engineer ships another build into production at three in the morning.",
  "neural networks learn by gradient descent, but the real lesson is in the loss curves you stared at for hours before they finally cooperated.",
  "in chess as in code, the strongest move is often the quietest one — a pawn pushed two squares, a function refactored three lines smaller.",
];

function PlaySection({ dark, accent, font }) {
  return (
    <section id="play" style={{
      position: 'relative', padding: '120px 60px 80px', zIndex: 2,
    }}>
      <window.SectionHeader dark={dark} accent={accent} font={font}
        eyebrow="Play"
        title="Off-hours obsessions."
        subtitle="Two things I do when I'm not at a keyboard. Or, well, one of them is at a keyboard." />

      <div style={{
        display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24,
        marginTop: 56,
      }}>
        <TypingTest dark={dark} accent={accent} font={font} />
        <ChessWidget dark={dark} accent={accent} font={font} />
      </div>
    </section>
  );
}

function TypingTest({ dark, accent, font }) {
  const fg = dark ? '#f0eef9' : '#0c0a14';
  const muted = dark ? 'rgba(240,238,249,0.55)' : 'rgba(20,18,30,0.55)';
  const dim = dark ? 'rgba(240,238,249,0.35)' : 'rgba(20,18,30,0.35)';

  const [textIdx, setTextIdx] = useState(0);
  const [typed, setTyped] = useState('');
  const [start, setStart] = useState(null);
  const [finished, setFinished] = useState(false);
  const [now, setNow] = useState(0);
  const inputRef = useRef(null);

  const text = SAMPLE_TEXTS[textIdx];

  useEffect(() => {
    if (!start || finished) return;
    const id = setInterval(() => setNow(Date.now()), 200);
    return () => clearInterval(id);
  }, [start, finished]);

  const onChange = (e) => {
    const v = e.target.value;
    if (!start) setStart(Date.now());
    if (v.length > text.length) return;
    setTyped(v);
    if (v === text) {
      setFinished(true);
    }
  };

  const reset = (next = false) => {
    setTyped(''); setStart(null); setFinished(false); setNow(0);
    if (next) setTextIdx((textIdx + 1) % SAMPLE_TEXTS.length);
    setTimeout(() => inputRef.current?.focus(), 50);
  };

  const elapsed = start ? ((finished ? now : Date.now()) - start) / 1000 : 0;
  const wordsTyped = typed.trim().split(/\s+/).filter(Boolean).length;
  const wpm = elapsed > 0 ? Math.round((wordsTyped / elapsed) * 60) : 0;
  let correct = 0;
  for (let i = 0; i < typed.length; i++) if (typed[i] === text[i]) correct++;
  const acc = typed.length > 0 ? Math.round((correct / typed.length) * 100) : 100;

  return (
    <div style={{
      padding: 28,
      background: dark ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.6)',
      border: `1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)'}`,
      borderRadius: 24, backdropFilter: 'blur(28px)',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: -60, right: -60, width: 220, height: 220,
        borderRadius: '50%',
        background: `radial-gradient(circle, ${accent}40, transparent 70%)`,
        filter: 'blur(40px)', pointerEvents: 'none',
      }} />

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18, position: 'relative' }}>
        <div>
          <div style={{
            fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase',
            color: accent, fontWeight: 600,
          }}>Typing test</div>
          <div style={{
            fontFamily: font.display, fontSize: 22, fontWeight: 700,
            letterSpacing: '-0.02em', marginTop: 4, color: fg,
          }}>Try to keep up. (I do 100.)</div>
        </div>
        <button onClick={() => reset(true)} style={{
          padding: '8px 14px', fontSize: 12, fontWeight: 600,
          background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)',
          color: fg, border: `1px solid ${dark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.06)'}`,
          borderRadius: 999, cursor: 'pointer',
        }}>↻ New text</button>
      </div>

      {/* Text display */}
      <div onClick={() => inputRef.current?.focus()} style={{
        fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
        fontSize: 19, lineHeight: 1.65, letterSpacing: '0.01em',
        padding: 20,
        background: dark ? 'rgba(0,0,0,0.25)' : 'rgba(0,0,0,0.04)',
        border: `1px solid ${dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)'}`,
        borderRadius: 14, cursor: 'text', userSelect: 'none',
        minHeight: 110,
      }}>
        {text.split('').map((ch, i) => {
          let color = dim;
          let bg = 'transparent';
          if (i < typed.length) {
            color = typed[i] === ch ? fg : '#ff6b9e';
            if (typed[i] !== ch) bg = 'rgba(255,107,158,0.18)';
          }
          if (i === typed.length && !finished) {
            return <span key={i} style={{ color: dim, borderLeft: `2px solid ${accent}`, marginLeft: -1, paddingLeft: 1, animation: 'cursorBlink 1s infinite' }}>{ch}</span>;
          }
          return <span key={i} style={{ color, background: bg, borderRadius: 2 }}>{ch}</span>;
        })}
      </div>
      <input ref={inputRef} value={typed} onChange={onChange}
        autoFocus={false}
        style={{
          position: 'absolute', opacity: 0, pointerEvents: 'none',
          width: 1, height: 1,
        }} />

      {/* live stats */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8,
        marginTop: 18,
      }}>
        <Metric dark={dark} font={font} k={wpm} v="WPM" highlight={wpm >= 100 ? accent : null} />
        <Metric dark={dark} font={font} k={`${acc}%`} v="ACC" />
        <Metric dark={dark} font={font} k={Math.round(elapsed)} v="SEC" />
        <Metric dark={dark} font={font} k={`${typed.length}/${text.length}`} v="CHARS" />
      </div>

      {finished && (
        <div style={{
          marginTop: 16, padding: 14,
          background: `linear-gradient(135deg, ${accent}25, transparent)`,
          border: `1px solid ${accent}55`,
          borderRadius: 12, fontSize: 13, color: fg,
        }}>
          {wpm >= 100
            ? <><b>Nice. {wpm} WPM.</b> You've matched (or beat) my pace.</>
            : <><b>{wpm} WPM</b> — keep going. <span onClick={() => reset(false)} style={{ textDecoration: 'underline', cursor: 'pointer', marginLeft: 6 }}>retry</span></>}
        </div>
      )}
    </div>
  );
}

function Metric({ k, v, dark, font, highlight }) {
  const fg = dark ? '#f0eef9' : '#0c0a14';
  const muted = dark ? 'rgba(240,238,249,0.5)' : 'rgba(20,18,30,0.5)';
  return (
    <div style={{
      padding: '10px 12px',
      background: dark ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.03)',
      border: `1px solid ${dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)'}`,
      borderRadius: 10,
    }}>
      <div style={{
        fontFamily: font.display, fontSize: 22, fontWeight: 700,
        letterSpacing: '-0.02em',
        color: highlight || fg,
      }}>{k}</div>
      <div style={{ fontSize: 9.5, letterSpacing: '0.1em', color: muted, fontWeight: 600, marginTop: 2 }}>{v}</div>
    </div>
  );
}

// Mini chess board — knight tour puzzle: tap squares to make legal knight moves
function ChessWidget({ dark, accent, font }) {
  const fg = dark ? '#f0eef9' : '#0c0a14';
  const muted = dark ? 'rgba(240,238,249,0.55)' : 'rgba(20,18,30,0.55)';
  const lightSq = dark ? '#2a2540' : '#f0e8d8';
  const darkSq = dark ? '#1a1628' : '#b89868';

  const [knight, setKnight] = useState({ r: 4, c: 4 });
  const [visited, setVisited] = useState([{ r: 4, c: 4 }]);

  const isVisited = (r, c) => visited.some(v => v.r === r && v.c === c);
  const isLegalKnight = (fr, fc, tr, tc) => {
    const dr = Math.abs(fr - tr), dc = Math.abs(fc - tc);
    return (dr === 2 && dc === 1) || (dr === 1 && dc === 2);
  };
  const isLegalNext = (r, c) => isLegalKnight(knight.r, knight.c, r, c) && !isVisited(r, c);

  const onSquareClick = (r, c) => {
    if (isLegalNext(r, c)) {
      setKnight({ r, c });
      setVisited([...visited, { r, c }]);
    }
  };

  const reset = () => {
    setKnight({ r: 4, c: 4 });
    setVisited([{ r: 4, c: 4 }]);
  };

  return (
    <div style={{
      padding: 22,
      background: dark ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.6)',
      border: `1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)'}`,
      borderRadius: 24, backdropFilter: 'blur(28px)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <div>
          <div style={{
            fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase',
            color: accent, fontWeight: 600,
          }}>Knight's tour</div>
          <div style={{
            fontFamily: font.display, fontSize: 18, fontWeight: 700,
            letterSpacing: '-0.02em', marginTop: 4, color: fg,
          }}>How far can you take it?</div>
        </div>
        <button onClick={reset} style={{
          padding: '6px 12px', fontSize: 11, fontWeight: 600,
          background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)',
          color: fg, border: `1px solid ${dark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.06)'}`,
          borderRadius: 999, cursor: 'pointer',
        }}>↻ Reset</button>
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)',
        aspectRatio: '1', borderRadius: 10, overflow: 'hidden',
        boxShadow: dark ? '0 0 0 1px rgba(255,255,255,0.08)' : '0 0 0 1px rgba(0,0,0,0.08)',
      }}>
        {Array.from({ length: 64 }, (_, i) => {
          const r = Math.floor(i / 8), c = i % 8;
          const isLight = (r + c) % 2 === 0;
          const isKnight = knight.r === r && knight.c === c;
          const visitedHere = isVisited(r, c) && !isKnight;
          const legal = isLegalNext(r, c);
          return (
            <div key={i}
              onClick={() => onSquareClick(r, c)}
              style={{
                background: isLight ? lightSq : darkSq,
                position: 'relative',
                cursor: legal ? 'pointer' : 'default',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 24, color: isLight ? '#0c0a14' : '#f0eef9',
                transition: 'background .15s',
              }}>
              {visitedHere && (
                <div style={{
                  width: '30%', height: '30%', borderRadius: '50%',
                  background: accent, opacity: 0.45,
                }} />
              )}
              {legal && (
                <div style={{
                  width: '32%', height: '32%', borderRadius: '50%',
                  background: 'transparent',
                  border: `2px dashed ${accent}`,
                  opacity: 0.85,
                }} />
              )}
              {isKnight && (
                <div style={{ color: dark ? '#f0eef9' : '#0c0a14', filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.3))' }}>
                  <window.KnightPiece size={28} color="currentColor" />
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginTop: 14, fontSize: 12, color: muted,
      }}>
        <span>Squares visited: <b style={{ color: fg }}>{visited.length}</b> / 64</span>
        <span>{visited.length === 64 ? '🏁 You did it.' : 'Tap a dotted square to move.'}</span>
      </div>
    </div>
  );
}

window.PlaySection = PlaySection;
