/* ── Blackjack ──────────────────────────────────────────────────────────── */
const BJ_RED = new Set(['♥','♦']);

const PIP_LAYOUTS = {
  'A':  [{x:50, y:50}],
  '2':  [{x:50, y:20}, {x:50, y:80, f:1}],
  '3':  [{x:50, y:17}, {x:50, y:50}, {x:50, y:83, f:1}],
  '4':  [{x:27, y:22}, {x:73, y:22}, {x:27, y:78, f:1}, {x:73, y:78, f:1}],
  '5':  [{x:27, y:22}, {x:73, y:22}, {x:50, y:50}, {x:27, y:78, f:1}, {x:73, y:78, f:1}],
  '6':  [{x:27, y:17}, {x:73, y:17}, {x:27, y:50}, {x:73, y:50}, {x:27, y:83, f:1}, {x:73, y:83, f:1}],
  '7':  [{x:27, y:13}, {x:73, y:13}, {x:50, y:33}, {x:27, y:55}, {x:73, y:55}, {x:27, y:83, f:1}, {x:73, y:83, f:1}],
  '8':  [{x:27, y:13}, {x:73, y:13}, {x:50, y:32}, {x:27, y:50}, {x:73, y:50}, {x:50, y:68, f:1}, {x:27, y:83, f:1}, {x:73, y:83, f:1}],
  '9':  [{x:27, y:13}, {x:73, y:13}, {x:27, y:36}, {x:73, y:36}, {x:50, y:50}, {x:27, y:64, f:1}, {x:73, y:64, f:1}, {x:27, y:87, f:1}, {x:73, y:87, f:1}],
  '10': [{x:27, y:11}, {x:73, y:11}, {x:50, y:27}, {x:27, y:43}, {x:73, y:43}, {x:27, y:57, f:1}, {x:73, y:57, f:1}, {x:50, y:73, f:1}, {x:27, y:89, f:1}, {x:73, y:89, f:1}],
};

function KingSVG() {
  // ArcheAge Paladin — great helm with T-visor, broad pauldrons, holy cross on chest, greatsword pommel above
  return (
    <svg width="62" height="58" viewBox="0 0 52 50" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      {/* Greatsword pommel + crossguard above helm */}
      <rect x="24.5" y="0" width="3" height="7" rx="1" opacity="0.75" />
      <rect x="19" y="4" width="14" height="3" rx="1.5" opacity="0.75" />
      <circle cx="26" cy="1" r="2.5" opacity="0.75" />
      {/* Left pauldron */}
      <ellipse cx="7" cy="30" rx="9" ry="6" />
      {/* Right pauldron */}
      <ellipse cx="45" cy="30" rx="9" ry="6" />
      {/* Pauldron ridges */}
      <ellipse cx="7" cy="28" rx="7" ry="3" opacity="0.4" fill="white" />
      <ellipse cx="45" cy="28" rx="7" ry="3" opacity="0.4" fill="white" />
      {/* Great helm dome */}
      <path d="M15 26 Q15 6 26 4 Q37 6 37 26 Z" />
      {/* Helm rim / gorget */}
      <rect x="13" y="26" width="26" height="5" rx="2.5" />
      {/* T-visor — vertical slot */}
      <rect x="24" y="11" width="4" height="19" fill="white" opacity="0.28" />
      {/* T-visor — horizontal slot */}
      <rect x="18" y="19" width="16" height="5" fill="white" opacity="0.28" />
      {/* Helm crest ridge */}
      <rect x="24.5" y="5" width="3" height="21" rx="1.5" opacity="0.18" fill="white" />
      {/* Chest plate */}
      <path d="M14 31 L14 50 Q26 54 38 50 L38 31 Q26 35 14 31 Z" />
      {/* Holy cross emblem */}
      <line x1="26" y1="33" x2="26" y2="49" stroke="white" strokeWidth="2.5" opacity="0.32" />
      <line x1="19" y1="39" x2="33" y2="39" stroke="white" strokeWidth="2.5" opacity="0.32" />
      {/* Chest plate centre line */}
      <line x1="26" y1="31" x2="26" y2="50" stroke="white" strokeWidth="1" opacity="0.13" />
    </svg>
  );
}

function QueenSVG() {
  // ArcheAge Sorceress — tall gem crown, flowing hair, arcane staff with orb, robes
  return (
    <svg width="62" height="58" viewBox="0 0 52 50" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      {/* Staff shaft — right side */}
      <rect x="44" y="5" width="3" height="45" rx="1.5" opacity="0.42" />
      {/* Arcane orb on staff */}
      <circle cx="45.5" cy="7" r="7" opacity="0.48" />
      <circle cx="45.5" cy="7" r="4.5" fill="white" opacity="0.38" />
      <circle cx="45.5" cy="7" r="2" fill="white" opacity="0.55" />
      {/* Staff rune marks */}
      <line x1="43" y1="20" x2="48" y2="20" stroke="white" strokeWidth="1" opacity="0.35" />
      <line x1="43" y1="28" x2="48" y2="28" stroke="white" strokeWidth="1" opacity="0.35" />
      {/* Flowing hair — left */}
      <path d="M11 24 Q2 34 5 47 L9 49 Q6 37 13 28 Z" opacity="0.65" />
      {/* Tall ornate crown */}
      <path d="M13 22 L17 10 L21 17 L26 5 L31 17 L35 10 L39 22 Z" />
      <rect x="11" y="22" width="30" height="4.5" rx="2" />
      {/* Crown gems */}
      <circle cx="26" cy="11" r="3" fill="white" opacity="0.52" />
      <circle cx="18" cy="16" r="2" fill="white" opacity="0.42" />
      <circle cx="34" cy="16" r="2" fill="white" opacity="0.42" />
      {/* Crown gem inner sparkle */}
      <circle cx="26" cy="11" r="1.5" fill="white" opacity="0.7" />
      {/* Face oval */}
      <ellipse cx="25" cy="33" rx="10" ry="10.5" fill="none" stroke="currentColor" strokeWidth="2" />
      {/* Eyes — dramatic arched */}
      <ellipse cx="21" cy="31" rx="2.2" ry="1.5" />
      <ellipse cx="29" cy="31" rx="2.2" ry="1.5" />
      <path d="M18.5 29 Q21 27 23.5 29" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" opacity="0.6" />
      <path d="M26.5 29 Q29 27 31.5 29" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" opacity="0.6" />
      {/* Lips */}
      <path d="M21.5 36.5 Q23 34.5 25 36 Q27 34.5 28.5 36.5 Q27 39 25 39.5 Q23 39 21.5 36.5 Z" opacity="0.8" />
      {/* Robe collar + décolletage */}
      <path d="M15 44 L19 41 L25 46 L31 41 L37 44 L37 50 L15 50 Z" />
      {/* Rune sigil on chest */}
      <path d="M23 44 L25 41 L27 44 L25 47 Z" fill="white" opacity="0.45" />
    </svg>
  );
}

function JackSVG() {
  // ArcheAge Shadowblade — hooded cowl, bandana mask, glowing eyes, twin daggers crossed
  return (
    <svg width="62" height="58" viewBox="0 0 52 50" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      {/* Twin daggers crossed — behind figure */}
      {/* Dagger 1: top-right to bottom-left */}
      <line x1="36" y1="11" x2="8" y2="45" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" opacity="0.52" />
      <polygon points="36,11 39,7 40,12" opacity="0.52" />
      {/* Dagger 2: top-left to bottom-right */}
      <line x1="16" y1="11" x2="44" y2="45" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" opacity="0.52" />
      <polygon points="16,11 13,7 12,12" opacity="0.52" />
      {/* Dagger crossguards */}
      <line x1="30" y1="22" x2="38" y2="18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity="0.52" />
      <line x1="14" y1="18" x2="22" y2="22" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity="0.52" />
      {/* Hood outer shape */}
      <path d="M10 24 Q10 2 26 1 Q42 2 42 24 L40 31 Q33 28 26 29 Q19 28 12 31 Z" />
      {/* Hood inner shadow — depth */}
      <path d="M14 23 Q14 7 26 5 Q38 7 38 23 L37 28 Q32 25 26 26 Q20 25 15 28 Z" opacity="0.45" />
      {/* Face scarf / bandana */}
      <rect x="15" y="27" width="22" height="8" rx="4" />
      {/* Glowing eyes */}
      <ellipse cx="21.5" cy="21.5" rx="3.2" ry="2.2" fill="white" opacity="0.8" />
      <ellipse cx="30.5" cy="21.5" rx="3.2" ry="2.2" fill="white" opacity="0.8" />
      {/* Slit pupils */}
      <ellipse cx="21.5" cy="21.5" rx="1.2" ry="1.8" opacity="0.45" />
      <ellipse cx="30.5" cy="21.5" rx="1.2" ry="1.8" opacity="0.45" />
      {/* Leather chest / pauldron hint */}
      <path d="M12 35 L12 50 L40 50 L40 35 Q26 40 12 35 Z" opacity="0.85" />
      {/* Shoulder pauldrons — small leather */}
      <ellipse cx="10" cy="33" rx="6" ry="4" opacity="0.7" />
      <ellipse cx="42" cy="33" rx="6" ry="4" opacity="0.7" />
      {/* Belt buckle */}
      <rect x="22" y="43" width="8" height="5" rx="1.5" fill="white" opacity="0.22" />
    </svg>
  );
}

const FACE_SVG = { 'J': JackSVG, 'Q': QueenSVG, 'K': KingSVG };

function CardCenter({ rank, suit }) {
  const pips = PIP_LAYOUTS[rank];
  if (pips) {
    return (
      <div className="card-pips">
        {pips.map((p, i) => (
          <span
            key={i}
            className={`card-pip${rank === 'A' ? ' ace' : ''}${p.f ? ' flipped' : ''}`}
            style={{ left: `${p.x}%`, top: `${p.y}%` }}
          >{suit}</span>
        ))}
      </div>
    );
  }
  const FaceSVG = FACE_SVG[rank];
  return (
    <div className="card-face">
      {FaceSVG && <FaceSVG />}
      <div className="card-face-suit">{suit}</div>
    </div>
  );
}

function bjValue(hand) {
  let v = 0, aces = 0;
  for (const c of hand) {
    if (c.hidden) continue;
    if (c.rank === 'A') { v += 11; aces++; }
    else if (['J','Q','K'].includes(c.rank)) v += 10;
    else v += parseInt(c.rank);
  }
  while (v > 21 && aces > 0) { v -= 10; aces--; }
  return v;
}

function bjLabel(hand) {
  const v = bjValue(hand);
  if (v > 21) return { text: `${v} — Bust`, cls: 'bust' };
  if (v === 21 && hand.filter(c => !c.hidden).length === 2) return { text: 'Blackjack!', cls: 'blackjack' };
  return { text: String(v), cls: '' };
}

const bjDelay = ms => new Promise(r => setTimeout(r, ms));

function Card({ card, revealed }) {
  if (card.hidden) return <div className="playing-card face-down" />;
  const isRed = BJ_RED.has(card.suit);
  return (
    <div className={`playing-card ${isRed ? 'red' : 'black'}${revealed ? ' card-reveal' : ''}`}>
      <div className="card-corner">
        <div className="card-rank">{card.rank}</div>
        <div className="card-suit">{card.suit}</div>
      </div>
      <CardCenter rank={card.rank} suit={card.suit} />
      <div className="card-corner bottom">
        <div className="card-rank">{card.rank}</div>
        <div className="card-suit">{card.suit}</div>
      </div>
    </div>
  );
}

function Blackjack({ balance, apiFetch, onBack, onBalanceChange }) {
  const { useState, useCallback } = React;

  const [dealer, setDealer]         = useState([]);
  const [player, setPlayer]         = useState([]);
  const [betAmount, setBetAmount]   = useState(100);
  const [phase, setPhase]           = useState('idle');
  const [status, setStatus]         = useState({ text: '', cls: '' });
  const [handId, setHandId]         = useState(null);
  const [origBet, setOrigBet]       = useState(0);
  const [revealingHole, setRevealingHole] = useState(false);
  const [history, setHistory]       = useState([]);
  const [err, setErr]               = useState('');

  function playResult(result) {
    if (result.cls === 'bj')   window.SoundFX?.blackjack();
    else if (result.cls === 'win')  window.SoundFX?.win();
    else if (result.cls === 'loss') window.SoundFX?.bust();
  }

  // Animate the dealer's full resolved hand: flip hole card, then reveal any extra cards
  async function animateDealer(fullDealer) {
    setPhase('dealer');
    setRevealingHole(true);
    setDealer([fullDealer[0], fullDealer[1]]);
    window.SoundFX?.card();

    for (let i = 2; i < fullDealer.length; i++) {
      await bjDelay(650);
      setDealer(fullDealer.slice(0, i + 1));
      window.SoundFX?.card();
    }
    await bjDelay(300);
  }

  async function deal() {
    setErr('');
    const amt = parseInt(betAmount);
    if (!amt || amt <= 0) { setErr('Enter a valid bet'); return; }
    if (amt > balance)    { setErr('Insufficient balance'); return; }

    window.SoundFX?.chip();

    let data;
    try {
      data = await apiFetch('/api/game/blackjack/deal', { amount: amt });
    } catch (e) { setErr(e.message); return; }

    setHandId(data.handId);
    setOrigBet(amt);
    setStatus({ text: '', cls: '' });
    setRevealingHole(false);

    // Animate deal: player c1 → dealer c1 → player c2 → dealer hole
    setPhase('dealing');
    setPlayer([]);
    setDealer([]);

    await bjDelay(200);
    setPlayer([data.player[0]]);
    window.SoundFX?.card();
    await bjDelay(450);
    setDealer([data.dealer[0]]);
    window.SoundFX?.card();
    await bjDelay(450);
    setPlayer(data.player);
    window.SoundFX?.card();
    await bjDelay(450);
    setDealer(data.dealer);
    window.SoundFX?.card();
    await bjDelay(300);

    if (data.phase === 'done') {
      // Natural blackjack — animate dealer resolution
      await animateDealer(data.dealerFinal);
      playResult(data.result);
      setStatus({ text: data.result.msg, cls: data.result.cls });
      setPhase('done');
      setHistory(h => [{ bet: amt, net: data.result.net }, ...h.slice(0, 19)]);
      onBalanceChange(data.balance);
    } else {
      setPhase('playing');
      onBalanceChange(data.balance);
    }
  }

  async function hit() {
    window.SoundFX?.chip();
    let data;
    try {
      data = await apiFetch('/api/game/blackjack/hit', { handId });
    } catch (e) { setErr(e.message); return; }

    setPlayer(data.player);
    window.SoundFX?.card();

    if (data.phase === 'done') {
      await bjDelay(400);
      if (bjValue(data.player) <= 21) await animateDealer(data.dealer);
      else setPhase('dealer');
      playResult(data.result);
      setStatus({ text: data.result.msg, cls: data.result.cls });
      setPhase('done');
      setHistory(h => [{ bet: origBet, net: data.result.net }, ...h.slice(0, 19)]);
      onBalanceChange(data.balance);
    }
  }

  async function stand() {
    window.SoundFX?.chip();
    let data;
    try {
      data = await apiFetch('/api/game/blackjack/stand', { handId });
    } catch (e) { setErr(e.message); return; }

    await animateDealer(data.dealer);
    playResult(data.result);
    setStatus({ text: data.result.msg, cls: data.result.cls });
    setPhase('done');
    setHistory(h => [{ bet: origBet, net: data.result.net }, ...h.slice(0, 19)]);
    onBalanceChange(data.balance);
  }

  async function doDouble() {
    window.SoundFX?.chip();
    let data;
    try {
      data = await apiFetch('/api/game/blackjack/double', { handId });
    } catch (e) { setErr(e.message); return; }

    setPlayer(data.player);
    window.SoundFX?.card();
    await bjDelay(500);
    if (bjValue(data.player) <= 21) await animateDealer(data.dealer);
    playResult(data.result);
    setStatus({ text: data.result.msg, cls: data.result.cls });
    setPhase('done');
    setHistory(h => [{ bet: origBet * 2, net: data.result.net }, ...h.slice(0, 19)]);
    onBalanceChange(data.balance);
  }

  const pLabel = player.length ? bjLabel(player) : null;
  const dLabel = dealer.some(c => !c.hidden) ? bjLabel(dealer.filter(c => !c.hidden)) : null;
  const busy   = phase === 'dealing' || phase === 'dealer';

  return (
    <div className="game-panel" data-game-view="blackjack">
      <div className="game-panel-header">
        <button className="btn-back" onClick={onBack}>Lobby</button>
        <div>
          <h1 className="game-panel-title">Blackjack</h1>
          <div className="game-panel-subtitle">·❦· Twenty-One or Perish ·❦·</div>
        </div>
        <div className="game-panel-meta"><span>3 : 2 Payout</span></div>
      </div>

      <div className="game-table">
        <FiligreeCorners />
        <div className="hand-label">
          Dealer{dLabel && !dealer.some(c => c.hidden) ? ` — ${dLabel.text}` : ''}
        </div>
        <div className="hand-area">
          {dealer.length ? dealer.map((c, i) => (
            <Card
              key={`d-${i}-${c.hidden}`}
              card={c}
              revealed={revealingHole && i === 1 && !c.hidden}
            />
          )) : (
            <span style={{ color: 'var(--muted)', fontFamily: 'Cormorant Garamond, serif', fontSize: 18 }}>
              Awaiting deal…
            </span>
          )}
        </div>

        <div className="table-divider" />

        {status.text && (
          <div className={`game-status ${status.cls}`} style={{ marginBottom: 16 }}>{status.text}</div>
        )}

        <div className="hand-area">
          {player.length ? player.map((c, i) => (
            <Card key={`p-${i}`} card={c} />
          )) : (
            <span style={{ color: 'var(--muted)', fontFamily: 'Cormorant Garamond, serif', fontSize: 18 }}>
              Place your bet below
            </span>
          )}
        </div>
        <div className="hand-label" style={{ marginTop: 0, marginBottom: 0 }}>
          {pLabel
            ? <span className={`hand-value${pLabel.cls ? ' ' + pLabel.cls : ''}`}>{pLabel.text}</span>
            : 'Your Hand'}
        </div>
      </div>

      <div className="bet-controls">
        <span className="bet-label">Bet</span>
        <input
          className="bet-input"
          type="number"
          min={1}
          max={1000}
          value={betAmount}
          onChange={e => setBetAmount(e.target.value)}
          disabled={phase !== 'idle' && phase !== 'done'}
        />
        <div className="bet-presets">
          {[100, 250, 500, 1000].map(n => (
            <button
              key={n}
              className="btn-preset"
              onClick={() => setBetAmount(n)}
              disabled={busy || phase === 'playing'}
            >
              {n >= 1000 ? `${n/1000}k` : n}
            </button>
          ))}
        </div>
        <div className="bet-increments">
          {[10, 25, 100].map(n => (
            <button key={n} className="btn-increment" disabled={busy || phase === 'playing'}
              onClick={() => { window.SoundFX?.chip(); setBetAmount(Math.min(1000, (parseInt(betAmount)||0) + n)); }}>
              +{n}
            </button>
          ))}
        </div>
        <div className="action-buttons">
          {(phase === 'idle' || phase === 'done') && (
            <button className="btn btn-primary btn-lg" onClick={deal}>Deal</button>
          )}
          {phase === 'dealing' && (
            <button className="btn btn-lg" disabled>Dealing…</button>
          )}
          {phase === 'playing' && (<>
            <button className="btn btn-lg" onClick={hit}>Hit</button>
            <button className="btn btn-lg" onClick={stand}>Stand</button>
            {player.length === 2 && balance >= origBet && (
              <button className="btn btn-lg" onClick={doDouble}>Double</button>
            )}
          </>)}
          {phase === 'dealer' && (
            <button className="btn btn-lg" disabled>Dealer's Turn…</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 Hands</span>
            <div className="section-line" />
          </div>
          <div className="history-feed">
            {history.map((h, i) => (
              <div key={i} className="history-item">
                <span className="history-game">Blackjack</span>
                <span className="history-bet">Bet {h.bet.toLocaleString()}</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>
  );
}
