// Main game component — the table, state machine, AI runner
const { useState: useS, useEffect: useE, useRef: useR, useMemo: useM, useCallback: useC } = React;

const LS_KEY = 'rome_game_state_v1';

function makeInitialGameState(config) {
  const { buildDeck, shuffle } = window.RomeEngine;
  let deck = shuffle(buildDeck());
  const playerHand = deck.splice(0, 13);
  const aiHand = deck.splice(0, 13);
  const discard = [deck.pop()];
  // If first discard is a joker, shuffle it back (classic rule)
  while (discard[0].joker) {
    deck.push(discard.pop());
    deck = shuffle(deck);
    discard.push(deck.pop());
  }
  return {
    config,
    deck,
    discard,
    player: { hand: window.RomeEngine.sortHand(playerHand), melds: [], hasOpenedMeld: false, openingPoints: 0 },
    ai:     { hand: aiHand, melds: [], hasOpenedMeld: false, openingPoints: 0, picked: [] },
    melds: [], // { id, type, cards, owner }
    turn: 'player',
    phase: 'draw', // draw -> play -> discard
    startedAt: Date.now(),
    winner: null
  };
}

// Utility: generate id
let _mid = 0; const meldId = () => `m${_mid++}`;

function useToasts() {
  const [toasts, setToasts] = useS([]);
  const push = useC((t) => {
    const id = Math.random().toString(36).slice(2);
    setToasts(ts => [...ts, { ...t, id }]);
    setTimeout(() => setToasts(ts => ts.filter(x => x.id !== id)), 5000);
  }, []);
  return [toasts, push];
}

function Confetti() {
  const pieces = useM(() => Array.from({ length: 60 }, (_, i) => ({
    left: Math.random() * 100,
    delay: Math.random() * 0.8,
    duration: 2 + Math.random() * 2,
    color: ['#ff3ea5','#3ef4ff','#9d5cff','#c8ff3e','#ffb43e'][i % 5],
    rot: Math.random() * 360
  })), []);
  return (
    <div className="confetti">
      {pieces.map((p, i) => (
        <span key={i} style={{
          left: p.left + '%',
          background: p.color,
          animationDelay: p.delay + 's',
          animationDuration: p.duration + 's',
          transform: `rotate(${p.rot}deg)`
        }} />
      ))}
    </div>
  );
}

function VictoryModal({ winner, personality, onAgain, onMenu }) {
  const p = window.RomeAI.PERSONALITIES[personality];
  const title = winner === 'player' ? 'Vēnī. Vīdī. Won.' : `${p.name} takes it.`;
  const sub = winner === 'player' ? 'Glory is yours. For now.' : 'Your punishment is having to keep playing.';
  const quote = winner === 'player'
    ? window.RomeAI.randLine(personality, 'lose')
    : window.RomeAI.randLine(personality, 'win');
  return (
    <div className="modal-wrap">
      <div className="modal victory">
        <Confetti />
        <div className="v-title">{title}</div>
        <div className="v-sub">{sub}</div>
        <div className="v-quote">"{quote}"<br/><span style={{fontSize:11,color:'var(--ink-lo)',fontStyle:'normal'}}>— {p.name}</span></div>
        <div style={{display:'flex',gap:10,justifyContent:'center',marginTop:16}}>
          <button className="btn" onClick={onMenu}>← Menu</button>
          <button className="cta" style={{padding:'14px 22px',fontSize:14}} onClick={onAgain}>Rematch</button>
        </div>
      </div>
    </div>
  );
}

function HelpModal({ onClose, config }) {
  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <h2>How to Rommé</h2>
        <div className="sub">Deal 13 cards each. Empty your hand first.</div>
        <ul className="help-list">
          <li>Each turn: <code>DRAW</code> one card (deck or discard), <code>MELD</code> if you want, then <code>DISCARD</code> one card.</li>
          <li><strong>Set</strong> = 3 or 4 cards of the same rank, different suits.</li>
          <li><strong>Run</strong> = 3+ consecutive cards of the same suit (A-low or A-high, no wrap).</li>
          <li>Jokers (★) can replace any card in a meld.</li>
          {config.variant === 'classic' && <li><strong>Classic rule:</strong> your first meld of the game must total <code>40+</code> points. Aces = 11, face cards = 10.</li>}
          {config.layoffAllowed && <li>You may extend an existing meld on the table (yours or theirs) with one or more cards.</li>}
          <li>Win by emptying your hand. Last card must be discarded or melded cleanly.</li>
        </ul>
        <div style={{display:'flex',justifyContent:'flex-end',marginTop:16}}>
          <button className="cta" style={{padding:'10px 20px',fontSize:13}} onClick={onClose}>Got it</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { makeInitialGameState, meldId, useToasts, Confetti, VictoryModal, HelpModal, LS_KEY });
