// drink.jsx — Game 4: ΕΙΣ ΥΓΕΙΑΝ / Eis Hygian ("to thy health")
// Quick-fire, no-setup, tap-through challenges.
// Random prompts inject random player names. Big tappable card.

const DRINK_PROMPTS = [
  // {A}-only prompts
  "{A} drinks 2",
  "{A} drinks 3",
  "{A} finishes whatever is in their cup. Bottoms up.",
  "{A}: pick anyone to drink for you. They cannot refuse.",
  "{A}: do your best Aphrodite walk to the kitchen and back",
  "{A}: speak only in Zeus's voice until the next card. Slip up — drink.",
  "{A}: confess the most unhinged thing you Googled this week",
  "{A}: show the most recent photo in your camera roll. No vetoes.",
  "{A}: read the last text in your group chat OUT LOUD",
  "{A}: name 5 Olympians in 10 seconds or drink 3",
  "{A}: play your last-played song. Everyone drinks if it's embarrassing.",
  "{A}: bottoms up. The gods thirst.",
  "{A}: do 5 push-ups OR drink 3. Hera shrugs either way.",
  "{A}: invent a Greek god. Drink the number of letters in their name.",
  "{A}: kiss your own phone screen. Take it to the grave. Drink.",
  "{A}: send 'I miss you' to your ex. Or drink 4. Choose thy poison.",
  "{A}: take a sip for every coworker you've fantasized about (silently, no number)",
  "{A}: hold the next sip in your mouth until the next card",
  "{A}: drink for every hour you slept under 6 last night",
  "{A}: who at this table would survive the longest in Hades? They drink.",
  "{A}: tell {B} a secret. {B} drinks if it's good.",

  // {A} + {B} prompts
  "{A} and {B} drink together. Olympian teamwork.",
  "{A} and {B}: swap drinks. Trust the Moirai.",
  "{A} and {B}: best 2-of-3 thumb war. Loser drinks 3.",
  "{A} and {B}: kiss on the cheek or both drink twice",
  "{A}: do your worst impression of {B}. If we laugh, {B} drinks.",
  "{A}: tell {B} one thing you've always wanted to say. Then drink.",
  "{A} starts a waterfall. {B} may be the first to stop.",
  "{A} and {B}: trade phones for 30 seconds. Snoop with grace.",
  "{A} compliments {B}. {B} drinks if blushing.",
  "{A} and {B}: stare each other down. First to laugh drinks.",

  // Group prompts
  "Everyone drinks. The gods commanded it.",
  "Last person to touch their nose drinks",
  "Last person to touch the floor drinks",
  "Last to clap drinks twice",
  "Anyone wearing socks drinks",
  "Anyone with a tattoo drinks twice",
  "Anyone who has cried this month drinks",
  "Anyone single drinks (sorry / congrats)",
  "Anyone who has kissed a coworker drinks. We will not ask which.",
  "Anyone who has been to therapy: cheers — drink with pride",
  "Most attractive at the table drinks (vote silently — point)",
  "Person whose phone has buzzed most tonight drinks",
  "Tallest player drinks for their height",
  "Youngest drinks for their innocence",
  "Oldest drinks for their wisdom",
  "Group cheers — everyone takes one sip",
  "Pour one sip into your neighbor's cup. Hospitality.",
  "Whoever spoke last drinks. Yes — you.",
  "Last to put their drink down — drinks twice. GO.",

  // Mini-game prompts
  "CATEGORIES — Greek gods. {A} starts. First to stall drinks 3.",
  "CATEGORIES — Worst bosses you've had. {A} starts.",
  "CATEGORIES — Exes' names. {A} starts.",
  "CATEGORIES — Things in a toga. {A} starts.",
  "RHYME TIME — {A} says a word. Going clockwise, each rhymes. Stall = drink.",
  "TRUTH — {A}: pick {B}. {B} asks the question. {A} answers or drinks 3.",
  "VOTE — Who at this table would last longest at Sparta? They drink.",
  "VOTE — Whose ex was the worst? They drink. (You voted, you drink too.)",
];

function DrinkGame() {
  const [phase, setPhase] = React.useState('landing'); // landing | setup | play | end
  const [players, setPlayers] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const [card, setCard] = React.useState(null);   // { text, key }
  const [count, setCount] = React.useState(0);
  const [tapped, setTapped] = React.useState(false);
  const usedRef = React.useRef([]);

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

  const pickPrompt = () => {
    // Avoid repeats within last N
    const recent = new Set(usedRef.current.slice(-Math.min(15, DRINK_PROMPTS.length - 1)));
    let idx;
    do { idx = Math.floor(Math.random() * DRINK_PROMPTS.length); } while (recent.has(idx));
    usedRef.current.push(idx);
    let text = DRINK_PROMPTS[idx];
    // Pick distinct A and B names
    const shuffled = [...players].sort(() => Math.random() - 0.5);
    const A = shuffled[0] || 'You';
    const B = shuffled[1] || shuffled[0] || 'Someone';
    text = text.replace(/\{A\}/g, A).replace(/\{B\}/g, B);
    return text;
  };

  const start = () => {
    usedRef.current = [];
    setCount(0);
    setCard({ text: pickPrompt(), key: 1 });
    setTapped(false);
    setPhase('play');
    gsSounds.reveal();
  };

  const next = () => {
    setTapped(true);
    gsSounds.drink();
    setTimeout(() => {
      setCount((c) => c + 1);
      setCard((c) => ({ text: pickPrompt(), key: c.key + 1 }));
      setTapped(false);
    }, 220);
  };

  const reset = () => { setPhase('landing'); setPlayers([]); setCount(0); setCard(null); usedRef.current = []; };

  // ── 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 · IV</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: 64, fontWeight: 800, margin: 0, lineHeight: 0.9,
            color: GREEK.wine,
            textShadow: '0 1px 0 oklch(1 0 0 / 0.5), 0 4px 24px oklch(0.30 0.10 25 / 0.25)',
            letterSpacing: '0.08em',
          }}>ΕΙΣ ΥΓΕΙΑΝ</h1>
          <div className="gs-italic" style={{ fontSize: 18, color: GREEK.wine, marginTop: 6 }}>
            Eis Hygian · <span style={{ color: GREEK.inkSoft }}>“to thy health”</span>
          </div>
          <div className="gs-italic" style={{ fontSize: 17, color: GREEK.ink, marginTop: 14, maxWidth: 380 }}>
            No rules. No setup. Just tap and obey the gods.
          </div>
          <div style={{ width: 80, height: 1, background: GREEK.goldDeep, margin: '28px 0' }} />
          <div style={{ display: 'flex', gap: 12 }}>
            <GsButton onClick={() => setPhase('setup')}>Begin the Bacchanal</GsButton>
          </div>
          <div className="gs-mono" style={{ marginTop: 24, fontSize: 10, color: GREEK.inkSoft, letterSpacing: '0.2em' }}>
            ENDLESS · 2+ MORTALS · BRING THINE OWN CHALICE
          </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' }}>
            ΕΙΣ ΥΓΕΙΑΝ · WHO DRINKS?
          </div>
          <h2 className="gs-cinzel" style={{ fontSize: 28, textAlign: 'center', margin: '8px 0 4px', fontWeight: 700 }}>
            Quick. Add Names.
          </h2>
          <p className="gs-italic" style={{ textAlign: 'center', color: GREEK.inkSoft, fontSize: 15, margin: '0 0 18px' }}>
            Dionysus does not wait.
          </p>

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

          <div style={{ flex: 1, overflowY: 'auto', minHeight: 0, display: 'flex', flexWrap: 'wrap', gap: 8, alignContent: 'flex-start' }}>
            {players.length === 0 && (
              <div className="gs-italic" style={{ width: '100%', textAlign: 'center', color: GREEK.inkSoft, padding: 30, fontSize: 15 }}>
                — no mortals yet —
              </div>
            )}
            {players.map((p) => (
              <div key={p} className="gs-fadein" style={{
                display: 'flex', alignItems: 'center', gap: 8,
                background: 'oklch(0.97 0.005 80 / 0.7)',
                padding: '6px 6px 6px 10px',
                border: `1px solid ${GREEK.parchmentDeep}`,
                borderRadius: 999,
              }}>
                <GsAvatar name={p} size={28} />
                <span style={{ fontWeight: 600, fontSize: 14 }}>{p}</span>
                <button onClick={() => removePlayer(p)}
                  style={{ background: 'none', border: 'none', color: GREEK.wine, cursor: 'pointer', fontSize: 14, padding: '0 4px' }}>×</button>
              </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 < 2} onClick={start}>
              ΕΙΣ ΥΓΕΙΑΝ!{players.length < 2 && ' (need 2+)'}
            </GsButton>
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── PLAY ───────────────────────────────────────────────
  if (phase === 'play') {
    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 }}>
              CARD {String(count + 1).padStart(3, '0')}
            </div>
            <button onClick={() => { setPhase('end'); gsSounds.win(); }}
              style={{ background: 'none', border: 'none', cursor: 'pointer', color: GREEK.wine, fontFamily: 'Cinzel', fontSize: 10, letterSpacing: '0.2em' }}>
              END BACCHANAL
            </button>
          </div>

          {/* Player chips */}
          <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
            {players.map((p) => (
              <div key={p} style={{ display: 'flex', alignItems: 'center', gap: 5, background: 'oklch(0.97 0.005 80 / 0.5)', padding: '3px 8px 3px 4px', borderRadius: 999 }}>
                <GsAvatar name={p} size={20} />
                <span style={{ fontSize: 12, fontWeight: 500 }}>{p}</span>
              </div>
            ))}
          </div>

          {/* The card — big tappable */}
          <div
            onClick={next}
            style={{
              flex: 1,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer',
              padding: 20,
              userSelect: 'none',
              position: 'relative',
              minHeight: 0,
            }}>
            <div key={card.key}
              className={`${tapped ? '' : 'gs-flip-in'} gs-card`}
              style={{
                width: '100%', maxWidth: 560,
                padding: '36px 32px',
                borderTop: `4px solid ${GREEK.wine}`,
                position: 'relative',
                opacity: tapped ? 0.5 : 1,
                transform: tapped ? 'scale(0.96)' : 'scale(1)',
                transition: 'opacity 0.2s, transform 0.2s',
              }}>
              <div className="gs-cinzel" style={{ fontSize: 11, letterSpacing: '0.3em', color: GREEK.goldDeep, textAlign: 'center', marginBottom: 14 }}>
                — DIONYSUS DECLARES —
              </div>
              <p className="gs-italic" style={{ fontSize: 26, lineHeight: 1.3, textAlign: 'center', margin: 0, fontWeight: 500, color: GREEK.ink, textWrap: 'pretty' }}>
                {card.text}
              </p>
            </div>
            <div className="gs-cinzel" style={{
              marginTop: 22,
              fontSize: 13, letterSpacing: '0.35em', color: GREEK.inkSoft, fontWeight: 600,
              animation: 'gs-pulse-glow 2s infinite ease-in-out',
            }}>
              ▼ TAP FOR NEXT ▼
            </div>
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── END ────────────────────────────────────────────────
  return (
    <GsFrame>
      <GsConfetti active count={80} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '40px 30px', textAlign: 'center', alignItems: 'center', justifyContent: 'center' }}>
        <div className="gs-cinzel" style={{ fontSize: 10, letterSpacing: '0.3em', color: GREEK.goldDeep }}>
          THE BACCHANAL CONCLUDES
        </div>
        <h2 className="gs-cinzel" style={{ fontSize: 36, margin: '14px 0 6px', fontWeight: 800 }}>
          You Survived
        </h2>
        <div className="gs-italic" style={{ fontSize: 17, color: GREEK.inkSoft, marginBottom: 26 }}>
          (or did you?)
        </div>
        <div style={{ background: 'oklch(0.97 0.005 80 / 0.6)', border: `1px solid ${GREEK.parchmentDeep}`, padding: '20px 36px', marginBottom: 26 }}>
          <div className="gs-mono" style={{ fontSize: 10, color: GREEK.inkSoft, letterSpacing: '0.25em' }}>CARDS DRAWN</div>
          <div className="gs-cinzel" style={{ fontSize: 64, fontWeight: 800, color: GREEK.wine, lineHeight: 1 }}>
            {count}
          </div>
          <div className="gs-mono" style={{ fontSize: 11, color: GREEK.inkSoft, letterSpacing: '0.2em', marginTop: 4 }}>
            BY {players.length} MORTAL{players.length !== 1 && 'S'}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <GsButton kind="ghost" onClick={() => {
            navigator.clipboard?.writeText(`We endured ${count} prophecies at greekslaves.beer. Dionysus is proud.`);
            gsSounds.ding();
          }} style={{ padding: '10px 18px', fontSize: 11 }}>
            📜 Share the carnage
          </GsButton>
          <GsButton onClick={reset} style={{ padding: '10px 18px', fontSize: 11 }}>
            Again
          </GsButton>
        </div>
      </div>
    </GsFrame>
  );
}

window.DrinkGame = DrinkGame;
