// symposium.jsx — Game 2: Trial of the Symposium (would-you-rather + voting)
// A spicy WYR is posed. Each player taps A or B. Minority drinks.
// Track streaks per player: agreement with majority builds a "Philosopher's Streak".

const WYR_PROMPTS = [
  ["Sleep with Zeus","Marry Hades"],
  ["Fight one Minotaur","Fight 100 chickens"],
  ["Always speak in haiku","Always wear sandals"],
  ["Your boss reads your DMs","Your boss reads your search history"],
  ["Be naked in front of your in-laws","Be naked in front of your boss"],
  ["Date someone with your ex's name","Date someone with your parent's name"],
  ["Lose all your texts","Lose your camera roll"],
  ["No alcohol for a year","No coffee for a year"],
  ["Wear a toga to work","Wear sandals to work"],
  ["Always whisper","Always shout"],
  ["Mute on a date","Mute on a job interview"],
  ["Fart loudly every kiss","Burp loudly every laugh"],
  ["Tell your crush you love them","Tell your mom your kink"],
  ["Get caught singing on the toilet","Get caught crying at a Disney film"],
  ["Have Hermes deliver every text out loud","Have Aphrodite narrate every flirt"],
  ["Marry your worst coworker","Live with your most annoying coworker"],
  ["Drunk text your ex","Sober text your boss at 2am"],
  ["Find out your partner's body count","Tell them yours"],
  ["Lose your phone for a week","Lose your wallet for a week"],
  ["Bottom of the bottle every Friday","Sober every Saturday"],
];

function SymposiumGame() {
  const [phase, setPhase] = React.useState('landing'); // landing | setup | play | reveal | end
  const [players, setPlayers] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const [round, setRound] = React.useState(0);
  const [maxRounds] = React.useState(7);
  const [prompt, setPrompt] = React.useState(null);
  const [votes, setVotes] = React.useState({}); // name -> 'A' | 'B'
  const [streaks, setStreaks] = React.useState({});
  const [bestStreak, setBestStreak] = React.useState({});
  const [sips, setSips] = React.useState({});
  const [confetti, setConfetti] = React.useState(false);
  const [shake, setShake] = React.useState(false);

  const used = React.useRef(new Set());

  const addPlayer = () => {
    const n = draft.trim();
    if (!n || players.includes(n)) { gsSounds.err(); return; }
    setPlayers([...players, n]);
    setStreaks({ ...streaks, [n]: 0 });
    setBestStreak({ ...bestStreak, [n]: 0 });
    setSips({ ...sips, [n]: 0 });
    setDraft('');
    gsSounds.click();
  };
  const removePlayer = (n) => {
    setPlayers(players.filter((p) => p !== n));
    const o = (m) => { const x = {...m}; delete x[n]; return x; };
    setStreaks(o); setBestStreak(o); setSips(o);
  };

  const nextPrompt = () => {
    let p; let attempts = 0;
    do {
      p = Math.floor(Math.random() * WYR_PROMPTS.length);
      attempts++;
    } while (used.current.has(p) && attempts < 20);
    used.current.add(p);
    setPrompt({ idx: p, a: WYR_PROMPTS[p][0], b: WYR_PROMPTS[p][1] });
    setVotes({});
    setPhase('play');
    gsSounds.click();
  };

  const startGame = () => {
    used.current.clear();
    setRound(0);
    nextPrompt();
  };

  const castVote = (name, choice) => {
    if (votes[name]) return;
    setVotes({ ...votes, [name]: choice });
    gsSounds.click();
  };

  const tally = () => {
    if (Object.keys(votes).length < players.length) {
      gsSounds.err(); setShake(true); setTimeout(() => setShake(false), 300);
      return;
    }
    const a = players.filter((p) => votes[p] === 'A').length;
    const b = players.length - a;
    const majority = a === b ? null : (a > b ? 'A' : 'B');
    const minority = a === b ? null : (a > b ? 'B' : 'A');
    const newStreaks = { ...streaks };
    const newBest = { ...bestStreak };
    const newSips = { ...sips };
    players.forEach((p) => {
      if (!majority) {
        // tie — no streak change
      } else if (votes[p] === majority) {
        newStreaks[p] = (streaks[p] || 0) + 1;
        if (newStreaks[p] > (bestStreak[p] || 0)) newBest[p] = newStreaks[p];
      } else {
        newStreaks[p] = 0;
        newSips[p] = (sips[p] || 0) + 1;
      }
    });
    setStreaks(newStreaks);
    setBestStreak(newBest);
    setSips(newSips);
    setPhase('reveal');
    gsSounds.reveal();
  };

  const advance = () => {
    const r = round + 1;
    if (r >= maxRounds) {
      setPhase('end');
      setConfetti(true);
      gsSounds.win();
      setTimeout(() => setConfetti(false), 3500);
    } else {
      setRound(r);
      nextPrompt();
    }
  };

  const reset = () => {
    setPhase('landing'); setPlayers([]); setStreaks({}); setBestStreak({}); setSips({}); setVotes({}); setRound(0);
    used.current.clear();
  };

  // ── LANDING ──────────────────────────────────────────────
  if (phase === 'landing') {
    return (
      <GsFrame>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '0 20px' }}>
          <div className="gs-mono" style={{ fontSize: 10, letterSpacing: '0.3em', color: GREEK.inkSoft, marginBottom: 8 }}>GAME · II</div>
          <div className="gs-cinzel" style={{ fontSize: 12, color: GREEK.goldDeep, letterSpacing: '0.4em', marginBottom: 20 }}>
            ··· greekslaves.beer ···
          </div>
          <h1 className="gs-cinzel" style={{
            fontSize: 48, fontWeight: 800, margin: 0, lineHeight: 0.95,
            color: GREEK.ink,
          }}>SYMPOSIUM</h1>
          <div className="gs-italic" style={{ fontSize: 22, color: GREEK.wine, marginTop: 6 }}>
            Trial of the
          </div>
          <div style={{ width: 80, height: 1, background: GREEK.goldDeep, margin: '24px 0' }} />
          <p style={{ fontSize: 18, maxWidth: 460, lineHeight: 1.45, color: GREEK.inkSoft, margin: 0 }}>
            Two paths. One must drink. <br/>
            <span style={{ fontStyle: 'italic' }}>The minority always pours.</span>
          </p>
          <div style={{ marginTop: 36 }}>
            <GsButton onClick={() => setPhase('setup')}>Enter the Agora</GsButton>
          </div>
          <div className="gs-mono" style={{ marginTop: 24, fontSize: 10, color: GREEK.inkSoft, letterSpacing: '0.2em' }}>
            BEST OF VII ROUNDS · MAJORITY RULES
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── SETUP ────────────────────────────────────────────────
  if (phase === 'setup') {
    return (
      <GsFrame>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '20px 30px', overflow: 'hidden' }}>
          <div className="gs-cinzel" style={{ fontSize: 10, letterSpacing: '0.3em', color: GREEK.goldDeep, textAlign: 'center' }}>
            SYMPOSIUM · ROSTER OF PHILOSOPHERS
          </div>
          <h2 className="gs-cinzel" style={{ fontSize: 26, textAlign: 'center', margin: '8px 0 4px', fontWeight: 700 }}>
            Who Dares Debate?
          </h2>

          <form onSubmit={(e) => { e.preventDefault(); addPlayer(); }}
            style={{ display: 'flex', gap: 8, margin: '16px 0' }}>
            <input className="gs-input" value={draft} onChange={(e) => setDraft(e.target.value)}
              placeholder="philosopher's name..." maxLength={16}
              autoFocus />
            <GsButton type="submit" kind="wine" style={{ padding: '8px 18px', fontSize: 12 }} disabled={!draft.trim()}>
              Enroll
            </GsButton>
          </form>

          <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
            {players.length === 0 && (
              <div className="gs-italic" style={{ textAlign: 'center', color: GREEK.inkSoft, padding: 30, fontSize: 15 }}>
                — the agora is empty —
              </div>
            )}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
              {players.map((p, i) => (
                <div key={p} className="gs-fadein" style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                  background: 'oklch(0.97 0.005 80 / 0.6)',
                  padding: 12,
                  border: `1px solid ${GREEK.parchmentDeep}`,
                  borderRadius: 2, position: 'relative',
                }}>
                  <GsAvatar name={p} size={48} />
                  <div style={{ fontWeight: 600, fontSize: 15, textAlign: 'center', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%' }}>{p}</div>
                  <button onClick={() => removePlayer(p)}
                    style={{ position: 'absolute', top: 4, right: 4, background: 'none', border: 'none', color: GREEK.wine, cursor: 'pointer', fontSize: 16 }}>×</button>
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 14, borderTop: `1px solid ${GREEK.parchmentDeep}` }}>
            <button onClick={() => setPhase('landing')}
              style={{ background: 'none', border: 'none', cursor: 'pointer', color: GREEK.inkSoft, fontFamily: 'Cinzel', fontSize: 11, letterSpacing: '0.15em' }}>
              ← BACK
            </button>
            <GsButton disabled={players.length < 3} onClick={startGame}>
              Begin Trial{players.length < 3 && ' (need 3+)'}
            </GsButton>
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── PLAY ─────────────────────────────────────────────────
  if (phase === 'play' || phase === 'reveal') {
    const aVotes = players.filter((p) => votes[p] === 'A');
    const bVotes = players.filter((p) => votes[p] === 'B');
    const allVoted = aVotes.length + bVotes.length === players.length;
    const majority = phase === 'reveal'
      ? (aVotes.length === bVotes.length ? null : (aVotes.length > bVotes.length ? 'A' : 'B'))
      : null;
    const tie = phase === 'reveal' && aVotes.length === bVotes.length;

    return (
      <GsFrame>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '14px 26px', minHeight: 0 }}>
          {/* HUD */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <div className="gs-cinzel" style={{ fontSize: 11, letterSpacing: '0.2em', color: GREEK.inkSoft }}>
              ROUND {String(round + 1).padStart(2, '0')} / {String(maxRounds).padStart(2, '0')}
            </div>
            <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
              {Array.from({ length: maxRounds }).map((_, i) => (
                <div key={i} style={{
                  width: 18, height: 4,
                  background: i < round ? GREEK.goldDeep : i === round ? GREEK.gold : oklch_bg(0.85, 0.02, 75),
                  borderRadius: 1,
                }} />
              ))}
            </div>
          </div>

          {/* The two options */}
          <div className={shake ? 'gs-shake' : ''} style={{
            flex: '0 0 auto',
            display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 0,
            margin: '10px 0 14px',
            minHeight: 200,
          }}>
            <button
              disabled={phase === 'reveal'}
              onClick={() => {
                // for "play test" allow voting as the first player without a name
                if (players.length === 1) castVote(players[0], 'A');
              }}
              style={{
                background: phase === 'reveal' && majority === 'A' ? 'linear-gradient(180deg, oklch(0.92 0.04 110), oklch(0.85 0.06 110))' :
                            phase === 'reveal' && majority === 'B' ? 'oklch(0.94 0.01 75 / 0.5)' :
                            'oklch(0.96 0.01 80)',
                border: `2px solid ${phase === 'reveal' && majority === 'A' ? GREEK.olive : GREEK.parchmentDeep}`,
                padding: '20px 16px', cursor: phase === 'play' ? 'default' : 'default',
                textAlign: 'center', position: 'relative',
                transition: 'background 0.3s, border-color 0.3s',
              }}>
              <div className="gs-cinzel" style={{ fontSize: 12, color: GREEK.goldDeep, letterSpacing: '0.3em', marginBottom: 8 }}>
                PATH · A
              </div>
              <div className="gs-italic" style={{ fontSize: 22, fontWeight: 500, lineHeight: 1.25, textWrap: 'pretty' }}>
                {prompt?.a}
              </div>
              {phase === 'reveal' && (
                <div className="gs-cinzel gs-fadein" style={{
                  marginTop: 10, fontSize: 28, fontWeight: 800,
                  color: majority === 'A' ? GREEK.oliveDeep : GREEK.wine,
                }}>
                  {aVotes.length}
                </div>
              )}
            </button>

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 8px', flexDirection: 'column' }}>
              <div className="gs-cinzel" style={{ fontSize: 18, fontWeight: 800, color: GREEK.wine, letterSpacing: '0.1em' }}>
                OR
              </div>
              <div style={{ width: 1, height: 60, background: GREEK.parchmentDeep, margin: '6px 0' }} />
            </div>

            <button
              disabled={phase === 'reveal'}
              style={{
                background: phase === 'reveal' && majority === 'B' ? 'linear-gradient(180deg, oklch(0.92 0.04 110), oklch(0.85 0.06 110))' :
                            phase === 'reveal' && majority === 'A' ? 'oklch(0.94 0.01 75 / 0.5)' :
                            'oklch(0.96 0.01 80)',
                border: `2px solid ${phase === 'reveal' && majority === 'B' ? GREEK.olive : GREEK.parchmentDeep}`,
                padding: '20px 16px', cursor: 'default',
                textAlign: 'center', position: 'relative',
                transition: 'background 0.3s, border-color 0.3s',
              }}>
              <div className="gs-cinzel" style={{ fontSize: 12, color: GREEK.goldDeep, letterSpacing: '0.3em', marginBottom: 8 }}>
                PATH · B
              </div>
              <div className="gs-italic" style={{ fontSize: 22, fontWeight: 500, lineHeight: 1.25, textWrap: 'pretty' }}>
                {prompt?.b}
              </div>
              {phase === 'reveal' && (
                <div className="gs-cinzel gs-fadein" style={{
                  marginTop: 10, fontSize: 28, fontWeight: 800,
                  color: majority === 'B' ? GREEK.oliveDeep : GREEK.wine,
                }}>
                  {bVotes.length}
                </div>
              )}
            </button>
          </div>

          {/* Players cast their vote */}
          <div style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
            <div className="gs-cinzel" style={{ fontSize: 10, letterSpacing: '0.25em', color: GREEK.inkSoft, marginBottom: 8, textAlign: 'center' }}>
              {phase === 'play'
                ? `CAST THY VOTE · ${aVotes.length + bVotes.length} / ${players.length}`
                : tie ? 'A TIE — THE GODS DRINK ALONE'
                : `MINORITY DRINKS · ${(majority === 'A' ? bVotes : aVotes).length} MORTALS`}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(110px, 1fr))', gap: 8 }}>
              {players.map((p) => {
                const v = votes[p];
                const isLoser = phase === 'reveal' && majority && v !== majority;
                const isWinner = phase === 'reveal' && majority && v === majority;
                return (
                  <div key={p} style={{
                    background: isLoser ? 'oklch(0.92 0.08 25 / 0.4)' :
                                isWinner ? 'oklch(0.92 0.04 110 / 0.4)' :
                                'oklch(0.97 0.005 80 / 0.6)',
                    border: `1px solid ${isLoser ? GREEK.wine : isWinner ? GREEK.olive : GREEK.parchmentDeep}`,
                    padding: '8px',
                    transition: 'all 0.3s',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                  }}>
                    <GsAvatar name={p} size={32} active={v && phase === 'play'} />
                    <div style={{ fontSize: 12, fontWeight: 600, textAlign: 'center', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%' }}>{p}</div>
                    {phase === 'play' && (
                      <div style={{ display: 'flex', gap: 4 }}>
                        <button onClick={() => castVote(p, 'A')}
                          disabled={!!v}
                          style={{
                            width: 26, height: 22, fontSize: 11, fontFamily: 'Cinzel', fontWeight: 700,
                            border: `1px solid ${v === 'A' ? GREEK.olive : GREEK.parchmentDeep}`,
                            background: v === 'A' ? GREEK.olive : 'transparent',
                            color: v === 'A' ? GREEK.marble : GREEK.ink,
                            cursor: v ? 'default' : 'pointer',
                          }}>A</button>
                        <button onClick={() => castVote(p, 'B')}
                          disabled={!!v}
                          style={{
                            width: 26, height: 22, fontSize: 11, fontFamily: 'Cinzel', fontWeight: 700,
                            border: `1px solid ${v === 'B' ? GREEK.olive : GREEK.parchmentDeep}`,
                            background: v === 'B' ? GREEK.olive : 'transparent',
                            color: v === 'B' ? GREEK.marble : GREEK.ink,
                            cursor: v ? 'default' : 'pointer',
                          }}>B</button>
                      </div>
                    )}
                    {phase === 'reveal' && (
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
                        <div className="gs-cinzel" style={{ fontSize: 14, fontWeight: 800, color: isLoser ? GREEK.wine : GREEK.oliveDeep }}>{v}</div>
                        {streaks[p] >= 3 && isWinner && (
                          <div className="gs-mono" style={{ fontSize: 8, color: GREEK.goldDeep, letterSpacing: '0.1em' }}>
                            🔥 {streaks[p]} STREAK
                          </div>
                        )}
                        {isLoser && (
                          <div className="gs-mono" style={{ fontSize: 8, color: GREEK.wine }}>+ 1 SIP</div>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Footer */}
          <div style={{ display: 'flex', gap: 8, marginTop: 12, justifyContent: 'space-between', alignItems: 'center', paddingTop: 10, borderTop: `1px solid ${GREEK.parchmentDeep}` }}>
            <button onClick={() => { setPhase('end'); gsSounds.win(); }}
              style={{ background: 'none', border: 'none', cursor: 'pointer', color: GREEK.inkSoft, fontFamily: 'Cinzel', fontSize: 10, letterSpacing: '0.2em' }}>
              FORFEIT
            </button>
            {phase === 'play' && (
              <GsButton kind="wine" onClick={tally} sound="reveal">
                {allVoted ? 'Reveal Verdict' : `Reveal (${aVotes.length+bVotes.length}/${players.length})`}
              </GsButton>
            )}
            {phase === 'reveal' && (
              <GsButton onClick={advance}>
                {round + 1 >= maxRounds ? 'Crown the Champion' : 'Next Trial →'}
              </GsButton>
            )}
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── END ──────────────────────────────────────────────────
  const ranked = [...players].sort((a, b) => (bestStreak[b] || 0) - (bestStreak[a] || 0) || (sips[a] || 0) - (sips[b] || 0));
  const champ = ranked[0];
  const champStreak = bestStreak[champ] || 0;
  const title = champStreak >= 5 ? 'HERO OF SPARTA'
              : champStreak >= 3 ? 'PHILOSOPHER-KING'
              : champStreak >= 2 ? 'CITIZEN OF NOTE'
              : 'OF THE PEOPLE';
  return (
    <GsFrame>
      <GsConfetti active={confetti} count={80} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '20px 30px', textAlign: 'center', overflow: 'auto' }}>
        <div className="gs-cinzel" style={{ fontSize: 10, letterSpacing: '0.3em', color: GREEK.goldDeep }}>
          ⊕ THE TRIAL CONCLUDES ⊕
        </div>
        <h2 className="gs-cinzel" style={{ fontSize: 28, margin: '12px 0 0', fontWeight: 800 }}>
          The People's Philosopher
        </h2>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '14px 0 14px' }}>
          <GsAvatar name={champ} size={80} active />
          <div className="gs-cinzel" style={{ fontSize: 28, fontWeight: 800, marginTop: 10 }}>{champ}</div>
          <div className="gs-cinzel" style={{ fontSize: 11, letterSpacing: '0.3em', color: GREEK.goldDeep, marginTop: 4 }}>
            — {title} —
          </div>
          <div className="gs-italic" style={{ fontSize: 15, color: GREEK.wine, marginTop: 4 }}>
            best streak: {champStreak}
          </div>
        </div>
        <div style={{ background: 'oklch(0.97 0.005 80 / 0.6)', border: `1px solid ${GREEK.parchmentDeep}`, padding: 14, marginBottom: 12 }}>
          <div className="gs-cinzel" style={{ fontSize: 10, letterSpacing: '0.25em', color: GREEK.inkSoft, marginBottom: 8, display: 'flex', justifyContent: 'space-between' }}>
            <span>NAME</span><span>🔥 BEST</span><span>🍷 SIPS</span>
          </div>
          {ranked.map((p, i) => (
            <div key={p} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0', borderTop: i ? `1px solid ${GREEK.parchmentDeep}` : 'none' }}>
              <div className="gs-cinzel" style={{ width: 22, fontSize: 12, color: GREEK.goldDeep, fontWeight: 700 }}>
                {['I','II','III','IV','V','VI','VII','VIII'][i] || (i+1)}
              </div>
              <GsAvatar name={p} size={26} />
              <div style={{ flex: 1, textAlign: 'left', fontWeight: 600, fontSize: 14 }}>{p}</div>
              <div className="gs-mono" style={{ color: GREEK.goldDeep, fontSize: 13, width: 30, textAlign: 'right' }}>{bestStreak[p] || 0}</div>
              <div className="gs-mono" style={{ color: GREEK.wine, fontSize: 13, width: 30, textAlign: 'right' }}>{sips[p] || 0}</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <GsButton kind="ghost" onClick={() => {
            navigator.clipboard?.writeText(`${champ} was crowned ${title} at greekslaves.beer — ${champStreak} streak. Plato could never.`);
            gsSounds.ding();
          }} style={{ padding: '10px 18px', fontSize: 11 }}>
            📜 Share verdict
          </GsButton>
          <GsButton onClick={reset} style={{ padding: '10px 18px', fontSize: 11 }}>
            New Trial
          </GsButton>
        </div>
      </div>
    </GsFrame>
  );
}

window.SymposiumGame = SymposiumGame;
