// fates.jsx — Game 3: Roll of the Fates (spin-the-wheel of debauchery)
// 12 sectors of rules/challenges. The Moirai spin your thread.

const FATE_SECTORS = [
  { label: 'WATERFALL',  rule: 'Everyone drinks. You may not stop until the player before you stops. Hubris.', kind: 'group', color: 'wine' },
  { label: 'CATEGORIES', rule: 'Pick a category (Greek gods, exes, bad bosses). Go around. First to stall drinks.', kind: 'mini', color: 'olive' },
  { label: 'LAST MAN',   rule: 'Last person to touch the floor drinks. Pillars are not the floor.', kind: 'group', color: 'wine' },
  { label: 'HAIKU',      rule: 'Speak only in haiku until your next turn. Break form, drink.', kind: 'rule', color: 'gold' },
  { label: 'PHONE',      rule: 'Trade phones with the player on your left for 30 seconds. Snoop responsibly.', kind: 'group', color: 'olive' },
  { label: 'AGE × 0.1',  rule: "Drink for [your age × 0.1] seconds. Time's the executioner.", kind: 'self', color: 'wine' },
  { label: 'CAMERA',     rule: "Show your last camera-roll photo. No vetoes. Aphrodite watches.", kind: 'self', color: 'wine' },
  { label: 'SOBER ONE',  rule: 'If you are the most sober at the table, drink. The gods despise restraint.', kind: 'rule', color: 'wine' },
  { label: 'TRUTH',      rule: 'Player to your right asks a question. You answer, or take 3.', kind: 'mini', color: 'olive' },
  { label: 'PRETTIEST',  rule: 'Vote: who at the table is most attractive right now? They drink. (Compliment, kinda.)', kind: 'group', color: 'wine' },
  { label: 'BOTTOMS',    rule: 'Finish what is in your cup. The Fates have woven your thirst.', kind: 'self', color: 'wine' },
  { label: 'TYCHE',      rule: 'Tyche smiles. Skip. Pass the wheel. Be smug about it.', kind: 'skip', color: 'gold' },
];

function FatesGame() {
  const [phase, setPhase] = React.useState('landing');
  const [players, setPlayers] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const [turn, setTurn] = React.useState(0);
  const [angle, setAngle] = React.useState(0);
  const [spinning, setSpinning] = React.useState(false);
  const [landedIdx, setLandedIdx] = React.useState(null);
  const [sips, setSips] = React.useState({});
  const [round, setRound] = React.useState(0);
  const [confetti, setConfetti] = React.useState(false);

  const SECTOR = 360 / FATE_SECTORS.length;

  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 o = { ...sips }; delete o[n]; setSips(o);
  };

  const spin = () => {
    if (spinning) return;
    setSpinning(true);
    setLandedIdx(null);
    gsSounds.spin();
    const idx = Math.floor(Math.random() * FATE_SECTORS.length);
    const extraTurns = 5 + Math.floor(Math.random() * 3);
    // Center of sector idx is at idx*SECTOR + SECTOR/2 from 12 o'clock.
    // To land at 12 (pointer at top), target rotation = -idx*SECTOR - SECTOR/2.
    const target = 360 * extraTurns - (idx * SECTOR + SECTOR / 2);
    setAngle(target);
    setTimeout(() => {
      setSpinning(false);
      setLandedIdx(idx);
      gsSounds.reveal();
    }, 3800);
  };

  const took = (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);
    setLandedIdx(null);
    setAngle(angle % 360);
    gsSounds.click();
  };

  const endGame = () => {
    setPhase('end'); setConfetti(true); gsSounds.win();
    setTimeout(() => setConfetti(false), 3500);
  };
  const reset = () => {
    setPhase('landing'); setPlayers([]); setSips({}); setTurn(0); setLandedIdx(null); setRound(0); setAngle(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 · III</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: 50, fontWeight: 800, margin: 0, lineHeight: 0.95,
          }}>THE FATES</h1>
          <div className="gs-italic" style={{ fontSize: 22, color: GREEK.wine, marginTop: 6 }}>
            Roll 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 }}>
            Twelve sectors. One spinning thread. <br/>
            <span className="gs-italic">Clotho spins, Lachesis measures, Atropos cuts.</span>
          </p>
          <div style={{ marginTop: 36 }}>
            <GsButton onClick={() => setPhase('setup')}>Approach the Wheel</GsButton>
          </div>
          <div className="gs-mono" style={{ marginTop: 24, fontSize: 10, color: GREEK.inkSoft, letterSpacing: '0.2em' }}>
            12 PROPHECIES · INFINITE SUFFERING
          </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' }}>
            ROLL OF THE FATES · OFFERINGS
          </div>
          <h2 className="gs-cinzel" style={{ fontSize: 26, textAlign: 'center', margin: '8px 0 4px', fontWeight: 700 }}>
            Who Faces the Wheel?
          </h2>
          <p className="gs-italic" style={{ textAlign: 'center', color: GREEK.inkSoft, fontSize: 15, margin: '0 0 14px' }}>
            Inscribe thy name upon the thread.
          </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="mortal's 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: 24, fontSize: 15 }}>
                — the thread is unspun —
              </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={() => setPhase('play')}>
              Spin the Thread{players.length < 2 && ' (need 2+)'}
            </GsButton>
          </div>
        </div>
      </GsFrame>
    );
  }

  // ── PLAY ─────────────────────────────────────────────────
  if (phase === 'play') {
    const active = players[turn];
    const landed = landedIdx !== null ? FATE_SECTORS[landedIdx] : null;
    const totalSips = Object.values(sips).reduce((a, b) => a + b, 0);
    const wheelSize = 240;
    const r = wheelSize / 2;

    const sectorColor = (i) => {
      const sc = FATE_SECTORS[i].color;
      if (sc === 'wine') return i % 2 ? 'oklch(0.42 0.12 25)' : 'oklch(0.34 0.10 25)';
      if (sc === 'olive') return i % 2 ? 'oklch(0.58 0.08 110)' : 'oklch(0.46 0.07 110)';
      return i % 2 ? 'oklch(0.78 0.13 80)' : 'oklch(0.68 0.13 78)';
    };

    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 }}>
              SPIN {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' }}>
              CUT THE THREAD
            </button>
          </div>
          <GsDrinkOMeter value={totalSips} max={players.length * 6} label="Libations" />

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

          {/* Main area: wheel + result */}
          <div style={{ flex: 1, display: 'grid', gridTemplateColumns: `${wheelSize + 20}px 1fr`, gap: 16, alignItems: 'center', minHeight: 0 }}>
            {/* Wheel */}
            <div style={{ position: 'relative', width: wheelSize, height: wheelSize, margin: '0 auto' }}>
              {/* pointer at 12 o'clock */}
              <div style={{
                position: 'absolute', top: -8, left: '50%', transform: 'translateX(-50%)',
                width: 0, height: 0,
                borderLeft: '10px solid transparent',
                borderRight: '10px solid transparent',
                borderTop: `18px solid ${GREEK.wineDeep}`,
                zIndex: 3,
                filter: 'drop-shadow(0 2px 2px rgba(0,0,0,0.3))',
              }} />
              <svg
                width={wheelSize} height={wheelSize}
                viewBox={`0 0 ${wheelSize} ${wheelSize}`}
                style={{
                  transform: `rotate(${angle}deg)`,
                  transition: spinning ? 'transform 3.8s cubic-bezier(0.17, 0.67, 0.16, 1)' : 'none',
                  filter: 'drop-shadow(0 8px 18px rgba(80,40,20,0.35))',
                }}>
                {FATE_SECTORS.map((s, i) => {
                  const a0 = (i * SECTOR - 90) * Math.PI / 180;
                  const a1 = ((i + 1) * SECTOR - 90) * Math.PI / 180;
                  const x0 = r + r * Math.cos(a0), y0 = r + r * Math.sin(a0);
                  const x1 = r + r * Math.cos(a1), y1 = r + r * Math.sin(a1);
                  const large = SECTOR > 180 ? 1 : 0;
                  const d = `M ${r} ${r} L ${x0} ${y0} A ${r} ${r} 0 ${large} 1 ${x1} ${y1} Z`;
                  const mid = (i * SECTOR + SECTOR / 2 - 90) * Math.PI / 180;
                  const tx = r + (r * 0.62) * Math.cos(mid);
                  const ty = r + (r * 0.62) * Math.sin(mid);
                  const rot = i * SECTOR + SECTOR / 2;
                  return (
                    <g key={i}>
                      <path d={d} fill={sectorColor(i)} stroke={GREEK.parchmentDeep} strokeWidth="1" />
                      <text x={tx} y={ty}
                        textAnchor="middle" dominantBaseline="middle"
                        transform={`rotate(${rot}, ${tx}, ${ty})`}
                        fontSize={10}
                        fontFamily="Cinzel, serif"
                        fontWeight="700"
                        letterSpacing="0.05em"
                        fill={s.color === 'gold' ? GREEK.ink : 'oklch(0.97 0.01 80)'}>
                        {s.label}
                      </text>
                    </g>
                  );
                })}
                <circle cx={r} cy={r} r={r - 1} fill="none" stroke={GREEK.goldDeep} strokeWidth="2" />
                <circle cx={r} cy={r} r={20}
                  fill="oklch(0.97 0.005 80)" stroke={GREEK.goldDeep} strokeWidth="2" />
                <text x={r} y={r}
                  textAnchor="middle" dominantBaseline="central"
                  fontSize={20}
                  fontFamily="Cinzel, serif"
                  fontWeight="800"
                  fill={GREEK.wine}>Ω</text>
              </svg>
            </div>

            {/* Right pane: state */}
            <div style={{ minWidth: 0 }}>
              {!landed && !spinning && (
                <div className="gs-fadein">
                  <div className="gs-cinzel" style={{ fontSize: 11, letterSpacing: '0.25em', color: GREEK.inkSoft }}>
                    TURN OF
                  </div>
                  <div className="gs-cinzel" style={{ fontSize: 30, fontWeight: 800, marginBottom: 8 }}>
                    {active}
                  </div>
                  <p className="gs-italic" style={{ color: GREEK.inkSoft, marginBottom: 16, fontSize: 15 }}>
                    The Moirai await. <br/>Spin to reveal thy prophecy.
                  </p>
                  <GsButton onClick={spin} className="gs-pulse" sound={null}>SPIN</GsButton>
                </div>
              )}
              {spinning && (
                <div>
                  <div className="gs-cinzel gs-italic" style={{ fontSize: 16, color: GREEK.inkSoft }}>
                    Clotho spins the thread…
                  </div>
                </div>
              )}
              {landed && !spinning && (
                <div className="gs-flip-in gs-card" style={{ padding: 16, borderLeft: `4px solid ${GREEK.wine}` }}>
                  <div className="gs-mono" style={{ fontSize: 9, color: GREEK.inkSoft, letterSpacing: '0.2em' }}>
                    FATE FOR · {active}
                  </div>
                  <div className="gs-cinzel" style={{ fontSize: 22, fontWeight: 800, color: GREEK.wine, marginTop: 4, marginBottom: 8, letterSpacing: '0.1em' }}>
                    {landed.label}
                  </div>
                  <p className="gs-italic" style={{ fontSize: 16, lineHeight: 1.35, margin: 0 }}>
                    "{landed.rule}"
                  </p>
                  <div style={{ display: 'flex', gap: 6, marginTop: 16, flexWrap: 'wrap' }}>
                    <GsButton kind="wine" sound="drink" onClick={() => took(1)} style={{ padding: '8px 12px', fontSize: 10 }}>
                      🍷 +1 sip
                    </GsButton>
                    <GsButton kind="wine" sound="drink" onClick={() => took(3)} style={{ padding: '8px 12px', fontSize: 10 }}>
                      🍷 +3 sips
                    </GsButton>
                    <GsButton kind="ghost" sound="click" onClick={nextTurn} style={{ padding: '8px 12px', fontSize: 10 }}>
                      Next →
                    </GsButton>
                  </div>
                </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 }}>
          ATROPOS HATH CUT THY THREAD
        </div>
        <h2 className="gs-cinzel" style={{ fontSize: 28, margin: '12px 0 0', fontWeight: 800 }}>
          Wove the Longest Thread
        </h2>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '14px 0 14px' }}>
          <GsAvatar name={champ} size={84} active />
          <div className="gs-cinzel" style={{ fontSize: 30, fontWeight: 800, marginTop: 10 }}>{champ}</div>
          <div className="gs-italic" style={{ fontSize: 16, color: GREEK.wine }}>
            consumed {sips[champ]} libations under Fortune's gaze
          </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 }}>
            THE FATES' 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: 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.wine, fontSize: 13 }}>{sips[p] || 0} 🍷</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
          <GsButton kind="ghost" onClick={() => {
            navigator.clipboard?.writeText(`The Moirai chose ${champ} at greekslaves.beer — ${sips[champ]} sips. Hubris.`);
            gsSounds.ding();
          }} style={{ padding: '10px 18px', fontSize: 11 }}>
            📜 Share fate
          </GsButton>
          <GsButton onClick={reset} style={{ padding: '10px 18px', fontSize: 11 }}>
            Spin again
          </GsButton>
        </div>
      </div>
    </GsFrame>
  );
}

window.FatesGame = FatesGame;
