// Pawnprint landing page — shared React components
const { useState, useEffect, useRef, useMemo } = React;

// Unicode chess pieces
const P = {
  wK: '♔', wQ: '♕', wR: '♖', wB: '♗', wN: '♘', wP: '♙',
  bK: '♚', bQ: '♛', bR: '♜', bB: '♝', bN: '♞', bP: '♟'
};

// Parse a simple FEN-lite: 8 rank strings separated by '/'. Use dots for empty. Uppercase=white, lowercase=black.
function parseBoard(rows) {
  const map = { K: 'wK', Q: 'wQ', R: 'wR', B: 'wB', N: 'wN', P: 'wP', k: 'bK', q: 'bQ', r: 'bR', b: 'bB', n: 'bN', p: 'bP' };
  return rows.map(r => r.split('').map(c => map[c] || null));
}

function Board({ rows, highlights = [], threats = [], targets = [], className = '' }) {
  const grid = parseBoard(rows);
  return (
    <div className={`board ${className}`}>
      {grid.map((row, r) => row.map((cell, c) => {
        const isLight = (r + c) % 2 === 0;
        const key = `${r}-${c}`;
        const hl = highlights.includes(key);
        const th = threats.includes(key);
        const tg = targets.includes(key);
        return (
          <div key={key} className={`sq ${isLight ? 'light' : 'dark'} ${hl ? 'highlight' : ''} ${th ? 'threat' : ''} ${tg ? 'target' : ''}`}>
            {cell && <span className={`piece ${cell[0] === 'b' ? 'black' : ''}`}>{P[cell]}</span>}
          </div>
        );
      }))}
    </div>
  );
}

// Ornamental flourish
function Flourish({ glyph = '✦' }) {
  return (
    <div className="flourish" style={{ margin: '0 auto', maxWidth: 300 }}>
      <span className="line"></span>
      <span className="glyph">{glyph}</span>
      <span className="line"></span>
    </div>
  );
}

// Pawnprint logo mark — pawn-crown, gold gradient
let _ppGradSeq = 0;
function Mark({ size = 34 }) {
  const gradId = useMemo(() => `pp-logo-gold-${++_ppGradSeq}`, []);
  return (
    <svg viewBox="0 0 34 34" width={size} height={size} style={{ overflow: 'visible', marginTop: -4 }}>
      <defs>
        <linearGradient id={gradId} x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%"  stopColor="#f4d989"/>
          <stop offset="55%" stopColor="#d4af37"/>
          <stop offset="100%" stopColor="#7a5e28"/>
        </linearGradient>
      </defs>
      <path d="M 10 8 L 12 4 L 14 8 L 17 3 L 20 8 L 22 4 L 24 8 L 24 11 L 10 11 Z"
            fill={`url(#${gradId})`} stroke="#5a4416" strokeWidth="0.7" strokeLinejoin="round"/>
      <circle cx="12" cy="4"  r="1" fill="#8b1c2b"/>
      <circle cx="17" cy="3"  r="1" fill="#8b1c2b"/>
      <circle cx="22" cy="4"  r="1" fill="#8b1c2b"/>
      <circle cx="17" cy="16" r="5" fill={`url(#${gradId})`} stroke="#5a4416" strokeWidth="0.7"/>
      <ellipse cx="17" cy="20" rx="5.5" ry="1.3" fill={`url(#${gradId})`} stroke="#5a4416" strokeWidth="0.6"/>
      <path d="M 11 22 Q 9 26 11 30 L 23 30 Q 25 26 23 22 Z"
            fill={`url(#${gradId})`} stroke="#5a4416" strokeWidth="0.7" strokeLinejoin="round"/>
      <rect x="9" y="30" width="16" height="3" rx="0.6"
            fill={`url(#${gradId})`} stroke="#5a4416" strokeWidth="0.6"/>
    </svg>);
}

// Pawnprint wordmark — "Pawn" in white, "print" in gold gradient
function Wordmark({ size = 26 }) {
  return (
    <span className="pp-wordmark" style={{ fontSize: size }}>
      <span className="pp-word-pawn">Pawn</span><span className="pp-word-print">print</span>
    </span>);
}

// Loop cycle SVG — 6 nodes in circle, animated active state
function LoopCycle({ active, onHover }) {
  const nodes = ['Play', 'Import', 'Analyze', 'Puzzle', 'Coach', 'Repeat'];
  const cx = 250, cy = 250, r = 180;
  return (
    <svg viewBox="0 0 500 500" style={{ width: '100%', height: 'auto' }}>
      {/* Outer ring */}
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--gold-line)" strokeWidth="1" strokeDasharray="2 6" />
      <circle cx={cx} cy={cy} r={r - 40} fill="none" stroke="var(--gold-faint)" strokeWidth="1" />
      {/* Cardinal lines */}
      {[0,60,120,180,240,300].map(deg => {
        const rad = (deg - 90) * Math.PI / 180;
        const x1 = cx + (r - 60) * Math.cos(rad);
        const y1 = cy + (r - 60) * Math.sin(rad);
        const x2 = cx + (r + 10) * Math.cos(rad);
        const y2 = cy + (r + 10) * Math.sin(rad);
        return <line key={deg} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--gold-faint)" strokeWidth="1" />;
      })}
      {/* Center crest */}
      <g>
        <circle cx={cx} cy={cy} r="58" fill="var(--ink-1)" stroke="var(--gold-line)" strokeWidth="1" />
        <text x={cx} y={cy + 2} textAnchor="middle" dominantBaseline="central" fill="var(--gold)" fontSize="48" fontFamily="var(--f-head)">♘</text>
        <text x={cx} y={cy + 42} textAnchor="middle" fill="var(--ivory-mute)" fontSize="9" fontFamily="var(--f-mono)" letterSpacing="2">THE LOOP</text>
      </g>
      {/* Connecting arc arrow */}
      {nodes.map((_, i) => {
        const a1 = (i * 60 - 90) * Math.PI / 180;
        const a2 = ((i + 1) * 60 - 90) * Math.PI / 180;
        const ar = r - 20;
        const x1 = cx + ar * Math.cos(a1 + 0.2);
        const y1 = cy + ar * Math.sin(a1 + 0.2);
        const x2 = cx + ar * Math.cos(a2 - 0.2);
        const y2 = cy + ar * Math.sin(a2 - 0.2);
        const isActiveArc = i === active;
        return (
          <path
            key={`arc-${i}`}
            d={`M ${x1} ${y1} A ${ar} ${ar} 0 0 1 ${x2} ${y2}`}
            fill="none"
            stroke={isActiveArc ? 'var(--gold)' : 'var(--gold-faint)'}
            strokeWidth={isActiveArc ? 2 : 1}
            markerEnd={isActiveArc ? 'url(#arrow)' : undefined}
          />
        );
      })}
      <defs>
        <marker id="arrow" viewBox="0 0 10 10" refX="6" refY="5" markerWidth="6" markerHeight="6" orient="auto">
          <path d="M 0 0 L 10 5 L 0 10 z" fill="var(--gold)" />
        </marker>
      </defs>
      {/* Nodes */}
      {nodes.map((label, i) => {
        const rad = (i * 60 - 90) * Math.PI / 180;
        const x = cx + r * Math.cos(rad);
        const y = cy + r * Math.sin(rad);
        const isActive = i === active;
        return (
          <g key={label} className="cycle-node" onMouseEnter={() => onHover(i)} style={{ cursor: 'pointer' }}>
            <circle cx={x} cy={y} r={isActive ? 26 : 20} fill={isActive ? 'var(--gold)' : 'var(--ink-2)'} stroke="var(--gold)" strokeWidth="1" />
            <text x={x} y={y + 1} textAnchor="middle" dominantBaseline="central" fontSize="16" fill={isActive ? 'var(--ink-0)' : 'var(--gold)'} fontFamily="var(--f-head)">{i + 1}</text>
            <text x={x} y={y + (y < cy ? -38 : 42)} textAnchor="middle" className={`cycle-label ${isActive ? 'active' : ''}`}>{label}</text>
          </g>
        );
      })}
    </svg>
  );
}

// Vocab tooltip — wrap a term; host can wire data-term → definition later.
// Appears on hover/focus with a floating card. Defs live in VOCAB_DEFS and can be
// overridden via window.__ppVocab = { term: { title, body } }.
const VOCAB_DEFS = {
  fork: {
    title: 'Fork',
    body: 'A single move that attacks two or more enemy pieces at once. The opponent can only save one — the other is lost.',
  },
  develop: {
    title: 'Development',
    body: 'Bringing your pieces (knights, bishops) off the back rank into the game during the opening.',
  },
  center: {
    title: 'The center',
    body: 'The four squares d4, d5, e4, e5. Controlling them gives your pieces more squares to move to.',
  },
  hanging: {
    title: 'Hanging',
    body: 'A piece that is attacked but not defended — free to capture.',
  },
  tempo: {
    title: 'Tempo',
    body: 'A move that forces the opponent to react, letting you gain time toward your plan.',
  },
};
function Vocab({ term, children }) {
  const [open, setOpen] = useState(false);
  const def = (typeof window !== 'undefined' && window.__ppVocab?.[term]) || VOCAB_DEFS[term];
  return (
    <span
      className="pp-vocab"
      data-term={term}
      tabIndex={0}
      onMouseEnter={() => setOpen(true)}
      onMouseLeave={() => setOpen(false)}
      onFocus={() => setOpen(true)}
      onBlur={() => setOpen(false)}
    >
      {children}
      {open && def && (
        <span className="pp-vocab-tip" role="tooltip">
          <span className="pp-vocab-tip-title">{def.title}</span>
          <span className="pp-vocab-tip-body">{def.body}</span>
        </span>
      )}
    </span>);
}

// HeroCoach — animated coaching moment: move → reflect → coach responds.
// Matches Pawnprint's in-app chat styling (ReflectionGate + InlineCoachingBlock).
function HeroCoach() {
  // stage: 0=before move, 1=move played, 2=reflection prompt visible,
  //        3=user typing, 4=coach thinking, 5=coach response
  const [stage, setStage] = useState(0);
  const [typed, setTyped] = useState('');

  // Teaching position for a pawn fork on d4.
  // Black pieces placed so 1.d4 attacks BOTH:
  //   - Knight on e5 (the Nc6 knight that hopped there)
  //   - Bishop on c5
  // Row 0 = rank 8, row 7 = rank 1. Col 0 = a, col 7 = h.
  //   Black: Rooks a8/h8, Bb bishop c8, Queen d8, King e8, Bf8 developed to c5, Nf6, Ng8 moved out.
  //          Pawns on rank 7 minus e7 (pawn pushed earlier and/or traded). Knight on e5, Bishop on c5.
  //   White: Knight on f3, Bishop on c4, e-pawn on e4, king-side pieces developed.
  //          Move that plays is d2 → d4.
  const before = [
    'r.bqk..r',  // 8: a8 rook, c8 bishop, d8 queen, e8 king, h8 rook
    'pppp.ppp',  // 7: e7 pawn gone
    '.....n..',  // 6: Nf6 only (the Nc6 knight has moved to e5)
    '..b.n...',  // 5: Bishop c5, Knight e5  ← both will be forked
    '..B.P...',  // 4: Bc4, e4 pawn
    '.....N..',  // 3: Nf3
    'PPPP.PPP',  // 2: e2 gone, d2 still there (will push)
    'RNBQK..R']; // 1: Bf1 developed, Ng1 developed

  const after = [
    'r.bqk..r',
    'pppp.ppp',
    '.....n..',
    '..b.n...',
    '..BPP...',  // d4 pawn arrives — attacks c5 bishop AND e5 knight
    '.....N..',
    'PPP..PPP',  // d2 now empty
    'RNBQK..R'];

  // Scripted typing with a realistic typo then backspace correction.
  // Target: "what does d4 do here?"
  const typingScript = useMemo(() => [
    ['w', 95], ['wh', 110], ['wha', 85], ['what', 100], ['what ', 130],
    ['what d', 95], ['what do', 100], ['what doe', 90],
    ['what doe ', 150],    // typo: space early
    ['what doe s', 110],
    ['what doe sd', 140],
    // realize mistake, backspace 3 chars
    ['what doe s', 160],
    ['what doe ', 110],
    ['what doe', 180],
    ['what does', 90], ['what does ', 120],
    ['what does d', 100], ['what does d4', 140],
    ['what does d4 ', 150],
    ['what does d4 d', 90], ['what does d4 do', 110],
    ['what does d4 do ', 140],
    ['what does d4 do h', 90], ['what does d4 do he', 90],
    ['what does d4 do her', 80], ['what does d4 do here', 100],
    ['what does d4 do here?', 400],
  ], []);

  useEffect(() => {
    let cancelled = false;
    const timeouts = [];
    const schedule = (fn, ms) => { const t = setTimeout(() => { if (!cancelled) fn(); }, ms); timeouts.push(t); };

    const runCycle = () => {
      setStage(0); setTyped('');
      schedule(() => setStage(1), 1400);          // move plays
      schedule(() => setStage(2), 2900);          // prompt appears

      // Begin typing at 3800ms
      let t = 3800;
      schedule(() => setStage(3), 3800);
      typingScript.forEach(([text, delayAfter]) => {
        schedule(() => setTyped(text), t);
        t += delayAfter;
      });
      schedule(() => setStage(4), t + 250);
      schedule(() => setStage(5), t + 1800);
      schedule(runCycle, t + 10000);
    };
    runCycle();
    return () => { cancelled = true; timeouts.forEach(clearTimeout); };
  }, [typingScript]);

  const currentRows = stage >= 1 ? after : before;
  // Highlight the move (from d2 to d4), and the forked targets once the move lands.
  const highlights = stage >= 1 ? ['4-3', '6-3'] : ['6-3'];   // d4 + d2
  const targets    = stage >= 1 ? ['3-2', '3-4'] : [];        // c5 (bishop) + e5 (knight)

  return (
    <div className="hero-coach">
      <div className="hc-board-wrap">
        <div className="hc-board-frame">
          <Board rows={currentRows} highlights={highlights} targets={targets} />
        </div>
      </div>

      <div className={`pp-chat-panel ${stage >= 2 ? 'on' : ''}`}>
        {/* Reflection gate: prompt label + (fake) input mirroring user typing */}
        <div className="pp-chat-label">What were you thinking?</div>
        <div className="pp-reflection-row">
          <div className="pp-reflection-input" data-focused={stage === 3}>
            <span className="pp-typed">{typed}</span>
            {stage === 3 && <span className="pp-caret">│</span>}
            {stage < 3 && <span className="pp-placeholder">Tell me what you were thinking…</span>}
          </div>
          <button className={`pp-reflection-submit ${stage >= 4 ? 'sent' : ''}`} disabled>
            {stage >= 4 ? 'Sent' : 'Send'}
          </button>
        </div>

        {/* Coach response block */}
        {stage >= 4 && (
          <div className="pp-coach-entry">
            <div className="pp-coach-entry-head">Coach</div>
            {stage === 4 ? (
              <div className="pp-coach-loading">
                <span className="pp-coach-spinner"></span>
                <span>Thinking…</span>
              </div>
            ) : (
              <div className="pp-coach-response">
                That pawn on <b>d4</b> just attacked <em>two</em> black pieces at once —
                the <b>knight on e5</b> and the <b>bishop on c5</b>.
                Black can only move one of them. Whichever they save, you take the other.
                That's called a <Vocab term="fork">pawn fork</Vocab>, and it's the most common way beginners lose material in the opening.
              </div>
            )}
          </div>
        )}

        {stage === 5 && (
          <div className="pp-coach-actions">
            <button className="pp-coach-action pp-coach-action-primary">Simplify</button>
            <span className="pp-coach-action-dot">·</span>
            <button className="pp-coach-action pp-coach-action-secondary">Ask a question</button>
          </div>
        )}
      </div>
    </div>);
}

Object.assign(window, { Board, Flourish, Mark, Wordmark, Vocab, LoopCycle, HeroCoach, useState, useEffect, useRef, useMemo });
