// oracle.jsx — Game 1: Oracle of Dionysus (card-draw prompt game)
// Players take turns drawing prophecies. Three suits: TRUTH, DARE, DRINK.
// Spicy/adult tone, workplace-coworker-flavored.

const ORACLE_PROMPTS = {
  truth: [
    "Which Olympian would you slide into the DMs of, and why?",
    "Confess a workplace crush — or take three sips",
    "Last text in your phone you would absolutely die if your mother read",
    "Worst date in one sentence",
    "Who in this room have you fantasized about? (no names — show fingers)",
    "Most expensive lie you've ever told",
    "How many of your exes still have your nudes?",
    "What's the pettiest reason you've cried at work?",
    "Have you ever fake-laughed for the entire length of a meeting?",
    "Confess the dumbest thing you've Googled this week",
    "Stolen anything from a previous job? Spill or sip",
    "The most unhinged thing in your search history right now",
  ],
  dare: [
    "Speak only in the voice of Zeus until your next turn",
    "Send 'I've been thinking about you' to the 3rd contact in your phone",
    "Slow dance with the player on your left for 30 seconds",
    "Recite an impromptu ode to the player across from you",
    "Show the last 3 photos in your camera roll — uncensored",
    "Eat a grape off another player's shoulder. Olympian style.",
    "Do your best Aphrodite walk to the kitchen and back",
    "Read the latest text from your group chat OUT LOUD",
    "Trade one item of clothing with the player to your right",
    "Re-enact your worst hangover for the gods to witness",
    "Call your mother and tell her you love her. Right now.",
    "Demonstrate how you flirt. Try it on Dionysus (the bottle).",
  ],
  drink: [
    "Sip if you've cried at work this year",
    "Drink if you've ever ghosted someone you actually liked",
    "Everyone with a visible tattoo drinks",
    "Pour out and pass — Dionysus thirsts. Bottom 2 finish.",
    "If you've kissed a coworker, drain half. We're not judging. We are.",
    "Last person to touch the floor: drink",
    "Youngest player drinks for their innocence",
    "Drink if you've never read the book you said you read",
    "Anyone who's been to therapy: cheers and drink",
    "If you've sent a risky text this week, take two",
    "Drink if you can name 5 Greek gods (you have 10 seconds)",
    "Group sip — the gods are watching",
  ],
};

const ORACLE_SUITS = {
  truth: { label: 'TRUTH', color: GREEK.wine, glyph: 'Ω' },
  dare: { label: 'DARE', color: GREEK.oliveDeep, glyph: 'Δ' },
  drink: { label: 'DRINK', color: GREEK.goldDeep, glyph: 'Θ' },
};

function OracleGame() {
  const [phase, setPhase] = React.useState('landing'); // landing | setup | play | end
  const [players, setPlayers] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const [turn, setTurn] = React.useState(0);
  const [card, setCard] = React.useState(null);
  const [sips, setSips] = React.useState({}); // name -> sips taken
  const [round, setRound] = React.useState(0);
  const [confetti, setConfetti] = React.useState(false);
  const [revealing, setRevealing] = React.useState(false);

  const cardRef = React.useRef(0);

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

  const drawCard = () => {
    if (revealing) return;
    setRevealing(true);
    const suits = ['truth', 'dare', 'drink'];
    const suit = suits[Math.floor(Math.random() * 3)];
    const list = ORACLE_PROMPTS[suit];
    const text = list[Math.floor(Math.random() * list.length)];
    setCard({ suit, text, key: ++cardRef.current });
    gsSounds.reveal();
    setTimeout(() => setRevealing(false), 500);
  };

  const tookSip = (n = 1) => {
    const who = players[turn];
    setSips({ ...sips, [who]: (sips[who] || 0) + n });
    gsSounds.drink();
  };
  const nextTurn = () => {
    setTurn((turn + 1) % players.length);
    setRound(round + 1);
    setCard(null);
    gsSounds.click();
  };
  const endGame = () => {
    setPhase('end');
    setConfetti(true);
    gsSounds.win();
    setTimeout(() => setConfetti(false), 3500);
  };
  const reset = () => {
    setPhase('landing'); setPlayers([]); setSips({}); setTurn(0); setCard(null); setRound(0);
  };

  // ── 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 · I</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: 56, fontWeight: 800, margin: 0, lineHeight: 0.95,
            color: GREEK.ink, textShadow: '0 1px 0 oklch(1 0 0 / 0.6)',
          }}>ORACLE</h1>
          <div className="gs-cormorant gs-italic" style={{ fontSize: 22, color: GREEK.wine, marginTop: 4, fontStyle: 'italic' }}>
            of Dionysus
          </div>
          <div style={{ width: 80, height: 1, background: GREEK.goldDeep, margin: '24px 0' }} />
          <p style={{ fontSize: 19, maxWidth: 460, lineHeight: 1.45, color: GREEK.inkSoft, margin: 0 }}>
            Draw a prophecy. Obey, or pour. <br/>
            <span style={{ fontStyle: 'italic' }}>The wine-god decides thy fate.</span>
          </p>
          <div style={{ marginTop: 36 }}>
            <GsButton onClick={() => setPhase('setup')}>Consult the Oracle</GsButton>
          </div>
          <div className="gs-mono" style={{ marginTop: 24, fontSize: 10, color: GREEK.inkSoft, letterSpacing: '0.2em' }}>
            4+ MORTALS · 21+ ONLY · DRINK RESPONSIBLY
          </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' }}>
            ORACLE OF DIONYSUS · STEP I
          </div>
          <h2 className="gs-cinzel" style={{ fontSize: 26, textAlign: 'center', margin: '8px 0 4px', fontWeight: 700 }}>
            Name Thy Mortals
          </h2>
          <p className="gs-italic" style={{ textAlign: 'center', color: GREEK.inkSoft, fontSize: 15, margin: '0 0 18px' }}>
            Who hath gathered at this symposium?
          </p>

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

          <div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
            {players.length === 0 && (
              <div className="gs-italic" style={{ textAlign: 'center', color: GREEK.inkSoft, padding: 24, fontSize: 15 }}>
                — the marble is yet uncarved —
              </div>
            )}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 10 }}>
              {players.map((p, i) => (
                <div key={p} className="gs-fadein" style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  background: 'oklch(0.97 0.005 80 / 0.6)',
                  padding: '8px 10px',
                  border: `1px solid ${GREEK.parchmentDeep}`,
                  borderRadius: 2,
                }}>
                  <GsAvatar name={p} size={34} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 16, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p}</div>
                    <div className="gs-mono" style={{ fontSize: 9, color: GREEK.inkSoft, letterSpacing: '0.15em' }}>MORTAL · {String(i+1).padStart(2,'0')}</div>
                  </div>
                  <button onClick={() => removePlayer(p)}
                    style={{ background: 'none', border: 'none', color: GREEK.wine, cursor: 'pointer', fontSize: 18, padding: 4 }}>×</button>
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 16, 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 < 2} onClick={() => setPhase('play')}>
              Begin the Rite{players.length < 2 && ' (need 2+)'}
            </GsButton>
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── PLAY ─────────────────────────────────────────────────
  if (phase === 'play') {
    const active = players[turn];
    const totalSips = Object.values(sips).reduce((a, b) => a + b, 0);
    const suitInfo = card ? ORACLE_SUITS[card.suit] : null;

    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: 10 }}>
            <div className="gs-cinzel" style={{ fontSize: 11, letterSpacing: '0.2em', color: GREEK.inkSoft }}>
              ROUND {String(round + 1).padStart(2, '0')}
            </div>
            <button onClick={endGame}
              style={{ background: 'none', border: 'none', cursor: 'pointer', color: GREEK.wine, fontFamily: 'Cinzel', fontSize: 10, letterSpacing: '0.2em' }}>
              END THE SYMPOSIUM
            </button>
          </div>
          <GsDrinkOMeter value={totalSips} max={players.length * 8} label="Libations" />

          {/* Player chips */}
          <div style={{ display: 'flex', gap: 6, marginTop: 12, marginBottom: 10, overflowX: 'auto', paddingBottom: 4 }}>
            {players.map((p, i) => (
              <div key={p} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, minWidth: 50 }}>
                <GsAvatar name={p} size={36} active={i === turn} />
                <div style={{ fontSize: 11, fontWeight: i === turn ? 700 : 500, color: i === turn ? GREEK.ink : GREEK.inkSoft }}>
                  {p.length > 8 ? p.slice(0, 8) + '…' : p}
                </div>
                <div className="gs-mono" style={{ fontSize: 9, color: GREEK.wine }}>
                  {sips[p] || 0}🍷
                </div>
              </div>
            ))}
          </div>

          {/* Card area */}
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: 0, position: 'relative' }}>
            {!card && (
              <div style={{ textAlign: 'center' }}>
                <div className="gs-cinzel" style={{ fontSize: 13, letterSpacing: '0.25em', color: GREEK.inkSoft, marginBottom: 6 }}>
                  IT IS THE TURN OF
                </div>
                <div className="gs-cinzel" style={{ fontSize: 36, fontWeight: 800, color: GREEK.ink, marginBottom: 18 }}>
                  {active}
                </div>
                <GsButton onClick={drawCard} sound={null}>Draw a Prophecy</GsButton>
              </div>
            )}
            {card && (
              <div key={card.key} className="gs-flip-in gs-card" style={{
                width: 'min(440px, 100%)',
                padding: '24px 28px',
                position: 'relative',
                borderTop: `4px solid ${suitInfo.color}`,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                  <div>
                    <div className="gs-mono" style={{ fontSize: 9, color: GREEK.inkSoft, letterSpacing: '0.2em' }}>FOR</div>
                    <div className="gs-cinzel" style={{ fontSize: 20, fontWeight: 700 }}>{active}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="gs-cinzel" style={{
                      fontSize: 16, fontWeight: 700,
                      color: suitInfo.color,
                      letterSpacing: '0.2em',
                    }}>{suitInfo.label}</div>
                    <div style={{ fontSize: 32, fontFamily: 'Cinzel', fontWeight: 800, color: suitInfo.color, lineHeight: 1 }}>{suitInfo.glyph}</div>
                  </div>
                </div>
                <div style={{ height: 1, background: GREEK.parchmentDeep, margin: '4px 0 16px' }} />
                <p className="gs-italic" style={{ fontSize: 20, lineHeight: 1.4, margin: 0, color: GREEK.ink, fontWeight: 500 }}>
                  "{card.text}"
                </p>
                <div style={{ display: 'flex', gap: 8, marginTop: 22, justifyContent: 'space-between' }}>
                  <GsButton kind="wine" sound="drink"
                    onClick={() => { tookSip(2); }}
                    style={{ padding: '10px 14px', fontSize: 11 }}>
                    🍷 I drink instead
                  </GsButton>
                  <GsButton kind="ghost" sound="click"
                    onClick={() => { tookSip(1); nextTurn(); }}
                    style={{ padding: '10px 14px', fontSize: 11 }}>
                    Done · Next
                  </GsButton>
                </div>
              </div>
            )}
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── END ──────────────────────────────────────────────────
  const ranked = [...players].sort((a, b) => (sips[b] || 0) - (sips[a] || 0));
  const champ = ranked[0];
  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 ORACLE HAS SPOKEN
        </div>
        <h2 className="gs-cinzel" style={{ fontSize: 30, margin: '12px 0 6px', fontWeight: 800 }}>
          Most Devoted to Dionysus
        </h2>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '14px 0 18px' }}>
          <GsAvatar name={champ} size={84} active />
          <div className="gs-cinzel" style={{ fontSize: 32, fontWeight: 800, marginTop: 12 }}>{champ}</div>
          <div className="gs-italic" style={{ fontSize: 16, color: GREEK.wine }}>
            with {sips[champ]} libations consumed
          </div>
        </div>
        <div style={{ background: 'oklch(0.97 0.005 80 / 0.6)', border: `1px solid ${GREEK.parchmentDeep}`, padding: 14, marginBottom: 14 }}>
          <div className="gs-cinzel" style={{ fontSize: 10, letterSpacing: '0.25em', color: GREEK.inkSoft, marginBottom: 8 }}>
            FINAL LEDGER
          </div>
          {ranked.map((p, i) => (
            <div key={p} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 0', borderTop: i ? `1px solid ${GREEK.parchmentDeep}` : 'none' }}>
              <div className="gs-cinzel" style={{ width: 24, fontSize: 14, color: GREEK.goldDeep, fontWeight: 700 }}>
                {['I','II','III','IV','V','VI','VII','VIII'][i] || (i+1)}
              </div>
              <GsAvatar name={p} size={28} />
              <div style={{ flex: 1, textAlign: 'left', fontWeight: 600 }}>{p}</div>
              <div className="gs-mono" style={{ color: GREEK.wine, fontSize: 14 }}>{sips[p] || 0} 🍷</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <GsButton kind="ghost" onClick={() => {
            navigator.clipboard?.writeText(`${champ} drank like a god at greekslaves.beer 🍷 (${sips[champ]} sips)`);
            gsSounds.ding();
          }} style={{ padding: '10px 18px', fontSize: 11 }}>
            📜 Share the tale
          </GsButton>
          <GsButton onClick={reset} style={{ padding: '10px 18px', fontSize: 11 }}>
            Another round
          </GsButton>
        </div>
      </div>
    </GsFrame>
  );
}

window.OracleGame = OracleGame;
