/* ── Keno ─────────────────────────────────────────────────────────────────── */
function Keno({ balance, apiFetch, onBack, onBalanceChange }) {
  const { useState, useEffect, useRef } = React;

  const KENO_PAYS = [
    [0, 3.5],
    [0, 0, 13],
    [0, 0, 2, 40],
    [0, 0, 1, 6, 100],
    [0, 0, 0, 4, 22, 300],
    [0, 0, 0, 3, 7, 50, 600],
    [0, 0, 0, 2, 5, 20, 150, 3000],
    [0, 0, 0, 0, 3, 12, 75, 750, 7500],
    [0, 0, 0, 0, 2, 6, 30, 225, 3000, 30000],
    [0, 0, 0, 0, 0, 3, 15, 90, 750, 7500, 75000],
  ];

  const [pickSize, setPickSize] = useState(5);
  const [picks, setPicks]       = useState([]);
  const [bet, setBet]           = useState(500);
  const [phase, setPhase]       = useState('pick');   // pick | revealing | done
  const [drawnNums, setDrawnNums] = useState(new Set());
  const [result, setResult]     = useState(null);
  const [busy, setBusy]         = useState(false);
  const [history, setHistory]   = useState([]);
  const [err, setErr]           = useState('');

  const activePicks = useRef([]);

  useEffect(() => {
    setPicks(prev => prev.slice(0, pickSize));
  }, [pickSize]);

  function togglePick(n) {
    if (phase !== 'pick' || busy) return;
    setPicks(prev => {
      if (prev.includes(n)) { window.SoundFX?.chip(); return prev.filter(x => x !== n); }
      if (prev.length >= pickSize) return prev;
      window.SoundFX?.chip();
      return [...prev, n];
    });
  }

  function quickPick() {
    if (phase !== 'pick' || busy) return;
    const pool = Array.from({ length: 80 }, (_, i) => i + 1);
    for (let i = 79; i > 79 - pickSize; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [pool[i], pool[j]] = [pool[j], pool[i]];
    }
    setPicks(pool.slice(80 - pickSize));
    window.SoundFX?.chip();
  }

  async function play() {
    setErr('');
    const amt = parseInt(bet);
    if (!amt || amt <= 0)          { setErr('Enter a valid bet'); return; }
    if (picks.length !== pickSize) { setErr(`Select ${pickSize} number${pickSize !== 1 ? 's' : ''} first`); return; }

    setBusy(true);
    activePicks.current = [...picks];

    let data;
    try {
      data = await apiFetch('/api/game/keno/play', { amount: amt, picks });
    } catch (e) { setBusy(false); setErr(e.message); return; }

    setPhase('revealing');
    setDrawnNums(new Set());
    setResult({ matches: data.matches, mult: data.mult, winAmount: data.winAmount, net: data.net });

    const pickSet = new Set(activePicks.current);
    for (const num of data.drawn) {
      await new Promise(r => setTimeout(r, 110));
      setDrawnNums(prev => new Set([...prev, num]));
      if (pickSet.has(num)) window.SoundFX?.chip();
      else window.SoundFX?.pin?.();
    }

    if (data.winAmount > 0) window.SoundFX?.win();
    onBalanceChange(data.balance);
    setPhase('done');
    setHistory(h => [
      { picks: pickSize, matches: data.matches, mult: data.mult, net: data.net },
      ...h.slice(0, 19),
    ]);
    setBusy(false);
  }

  function reset() {
    setPhase('pick');
    setDrawnNums(new Set());
    setResult(null);
    setErr('');
  }

  const payTable = KENO_PAYS[pickSize - 1];

  return (
    <div className="game-panel" data-game-view="keno">
      <div className="game-panel-header">
        <button className="btn-back"
          onClick={phase !== 'revealing' ? onBack : null}
          style={{ opacity: phase === 'revealing' ? 0.35 : 1, cursor: phase === 'revealing' ? 'default' : 'pointer' }}>
          Lobby
        </button>
        <div>
          <h1 className="game-panel-title">Keno</h1>
          <div className="game-panel-subtitle">·❦· The Numbers Game ·❦·</div>
        </div>
        <div className="game-panel-meta">
          <span>{picks.length}/{pickSize} selected</span>
        </div>
      </div>

      <div className="game-table">
        <FiligreeCorners />

        {/* Pick size + Quick Pick */}
        <div style={{ marginBottom: 14 }}>
          <div className="section-header" style={{ marginBottom: 8 }}>
            <span className="section-title">Pick Size</span>
            <div className="section-line" />
            {phase === 'pick' && (
              <button
                className="btn"
                onClick={quickPick}
                style={{ fontSize: 10, padding: '4px 10px', whiteSpace: 'nowrap' }}
              >
                Quick Pick
              </button>
            )}
          </div>
          <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
            {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(n => (
              <button
                key={n}
                className={`btn${pickSize === n ? ' btn-primary' : ''}`}
                onClick={() => { if (phase === 'pick') { window.SoundFX?.chip(); setPickSize(n); } }}
                style={{ fontSize: 11, padding: '5px 10px', opacity: phase !== 'pick' ? 0.6 : 1 }}
                disabled={phase !== 'pick'}
              >
                {n}
              </button>
            ))}
          </div>
        </div>

        {/* 10 × 8 number grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: 5, marginBottom: 16 }}>
          {Array.from({ length: 80 }, (_, i) => {
            const n = i + 1;
            const isPicked = picks.includes(n);
            const isDrawn  = drawnNums.has(n);
            const isMatch  = isPicked && isDrawn;
            let cls = 'keno-ball';
            if (isMatch)       cls += ' keno-match';
            else if (isPicked) cls += ' keno-picked';
            else if (isDrawn)  cls += ' keno-drawn';
            return (
              <button
                key={n}
                className={cls}
                onClick={() => togglePick(n)}
                disabled={phase !== 'pick' || (!isPicked && picks.length >= pickSize)}
              >
                {n}
              </button>
            );
          })}
        </div>

        {/* Pay table */}
        <div style={{ marginBottom: result ? 12 : 0 }}>
          <div className="section-header" style={{ marginBottom: 6 }}>
            <span className="section-title">Pay Table — Pick {pickSize}</span>
            <div className="section-line" />
          </div>
          <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
            {payTable.map((m, hits) => m > 0 && (
              <div
                key={hits}
                className={`keno-pay-entry${result && result.matches === hits ? ' keno-pay-highlight' : ''}`}
              >
                <span className="keno-pay-match">{hits} hit</span>
                <span className="keno-pay-mult">{m}×</span>
              </div>
            ))}
          </div>
        </div>

        {/* Result banner */}
        {result && phase === 'done' && (
          <div className={`game-status ${result.net >= 0 ? 'win' : 'loss'}`}
            style={{ marginTop: 14, textAlign: 'center' }}>
            {result.matches} match{result.matches !== 1 ? 'es' : ''}
            {result.mult > 0
              ? ` — ${result.mult}× — +${result.winAmount.toLocaleString()} G`
              : ' — No win'}
          </div>
        )}
      </div>

      {/* Controls */}
      {phase === 'pick' && (
        <div className="bet-controls">
          <span className="bet-label">Bet</span>
          <input className="bet-input" type="number" min={1} max={1000}
            value={bet} onChange={e => setBet(e.target.value)} />
          <div className="bet-presets">
            {[100, 250, 500, 1000].map(n => (
              <button key={n} className="btn-preset"
                onClick={() => { window.SoundFX?.chip(); setBet(n); }}>
                {n >= 1000 ? `${n / 1000}k` : n}
              </button>
            ))}
          </div>
          <div className="bet-increments">
            {[10, 25, 100].map(n => (
              <button key={n} className="btn-increment"
                onClick={() => { window.SoundFX?.chip(); setBet(Math.min(1000, (parseInt(bet)||0) + n)); }}>
                +{n}
              </button>
            ))}
          </div>
          <div className="action-buttons">
            <button
              className="btn btn-primary btn-lg"
              onClick={play}
              disabled={busy || picks.length !== pickSize}
              style={{ opacity: picks.length !== pickSize ? 0.5 : 1 }}
            >
              {picks.length < pickSize
                ? `Pick ${pickSize - picks.length} more`
                : 'Draw'}
            </button>
          </div>
        </div>
      )}

      {phase === 'revealing' && (
        <div className="bet-controls" style={{ justifyContent: 'center' }}>
          <span style={{ color: 'var(--muted)', fontStyle: 'italic', fontFamily: 'Cormorant Garamond, serif', fontSize: 14 }}>
            Drawing numbers…
          </span>
        </div>
      )}

      {phase === 'done' && (
        <div className="bet-controls">
          <div className="action-buttons" style={{ width: '100%', justifyContent: 'center', gap: 10 }}>
            <button
              className="btn btn-primary btn-lg"
              onClick={play}
              disabled={busy || picks.length !== pickSize}
            >
              Play Again
            </button>
            <button className="btn btn-lg" onClick={reset}>Change Picks</button>
          </div>
        </div>
      )}

      {err && <p style={{ color: 'var(--garnet)', fontSize: 12, marginTop: 10 }}>{err}</p>}

      {history.length > 0 && (
        <div style={{ marginTop: 20 }}>
          <div className="section-header">
            <span className="section-title">Recent Games</span>
            <div className="section-line" />
          </div>
          <div className="history-feed">
            {history.map((h, i) => (
              <div key={i} className="history-item">
                <span className="history-game">Keno</span>
                <span className="history-bet">Pick {h.picks} · {h.matches} hit · {h.mult}×</span>
                <span className={`history-result ${h.net > 0 ? 'pos' : h.net < 0 ? 'neg' : 'zero'}`}>
                  {h.net > 0 ? '+' : ''}{h.net.toLocaleString()} G
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.Keno = Keno;
