/* ============================================================
   WOULD YOU RATHER — everyone picks A or B
   ============================================================ */
const { useState: useW, useRef: useRW } = React;

const WYR_TIER_META = {
  Mild:   {color:'#16C2A3', emoji:'🌱'},
  Spicy:  {color:'#FF8A3C', emoji:'🌶️'},
  Chaotic:{color:'#FF5C9D', emoji:'🤯'},
};

function GameWouldYouRather({ game, players, scoring, scores, addScore, onExit, onHome }){
  const leave=onHome||onExit;
  const [tiers,setTiers]=useW({Mild:true,Spicy:true,Chaotic:false});
  const [rounds,setRounds]=useW(1);
  const [phase,setPhase]=useW('setup');
  const deckRef=useRW(null);
  const [turn,setTurn]=useW(0);
  const [totalRounds,setTotalRounds]=useW(0);
  const [card,setCard]=useW(null);
  const [votes,setVotes]=useW({});

  const activeTiers=Object.keys(tiers).filter(t=>tiers[t]);

  const begin=()=>{
    const pool=activeTiers.flatMap(t=>DATA.WOULD_YOU_RATHER[t].map(pair=>({...pair,tier:t})));
    deckRef.current=makeDeck(pool);
    setTotalRounds(rounds);
    setTurn(0);
    drawNext();
  };

  const drawNext=()=>{
    setCard(deckRef.current.draw());
    setVotes({});
    setPhase('card');
  };

  const countA=players.filter(p=>votes[p]==='A').length;
  const countB=players.length-countA;
  const minority=countA<=countB?'A':'B';
  const split=Math.abs(countA-countB)<=1;

  const revealWith=(v)=>{
    setVotes(v);
    const cA=players.filter(p=>v[p]==='A').length;
    const cB=players.length-cA;
    const min=cA<=cB?'A':'B';
    const isSplit=Math.abs(cA-cB)<=1;
    if(scoring){
      players.forEach(p=>{
        if(v[p]===min && !isSplit) addScore(p,1);
      });
    }
    setPhase('reveal');
  };

  const next=()=>{
    if(turn+1>=totalRounds){ setPhase('done'); }
    else { setTurn(turn+1); drawNext(); }
  };

  /* ---- SETUP ---- */
  if(phase==='setup'){
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Would You Rather" color={game.color}/>
        <div className="setup">
          <h2>Would You Rather</h2>
          <p className="lead">Two impossible choices. Everyone picks secretly — then see who'd survive the same world.</p>
          <div className="field">
            <label>Intensity</label>
            <div className="col" style={{gap:9}}>
              {Object.keys(tiers).map(t=>(
                <div key={t} className="toggle-row" style={{padding:'12px 15px'}}>
                  <span style={{fontSize:22}}>{WYR_TIER_META[t].emoji}</span>
                  <div className="lbl"><b>{t}</b><small>{DATA.WOULD_YOU_RATHER[t].length} pairs</small></div>
                  <Switch on={tiers[t]} onChange={v=>setTiers({...tiers,[t]:v})}/>
                </div>
              ))}
            </div>
          </div>
          <div className="field">
            <label>Rounds</label>
            <Stepper value={rounds} min={1} max={20} onChange={setRounds}/>
          </div>
          <div style={{marginTop:8}}>
            <Btn color="gold" size="lg" disabled={activeTiers.length===0} onClick={begin}>
              {activeTiers.length===0?'Pick an intensity':'Start →'}
            </Btn>
          </div>
        </div>
      </div>
    );
  }

  /* ---- CARD ---- */
  if(phase==='card'){
    const tm=WYR_TIER_META[card.tier];
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Would You Rather" color={game.color}
          right={<span className="mono" style={{fontSize:11,color:'#9082BE'}}>{turn+1}/{totalRounds}</span>}/>
        <div className="center" style={{flex:1,padding:'14px 26px',gap:14}}>
          <div className="kicker">read aloud together</div>
          <div className="bigcard" style={{borderColor:tm.color}}>
            <div className="tier-pill" style={{background:tm.color,color:'#fff',alignSelf:'center',marginBottom:14}}>{tm.emoji} {card.tier}</div>
            <div className="q" style={{fontSize:22,marginBottom:18}}>Would you rather…</div>
            <div className="wyr-options">
              <div className="wyr-opt"><span className="wyr-letter">A</span>{card.a}</div>
              <div className="wyr-or">or</div>
              <div className="wyr-opt"><span className="wyr-letter">B</span>{card.b}</div>
            </div>
          </div>
          <p className="muted" style={{maxWidth:300,fontSize:14}}>Discuss if you want — then everyone votes secretly.</p>
        </div>
        <div className="pad" style={{paddingTop:6}}>
          <Btn color="gold" size="lg" onClick={()=>setPhase('vote')}>Everyone vote secretly →</Btn>
        </div>
      </div>
    );
  }

  /* ---- VOTE (secret pass-around) ---- */
  if(phase==='vote'){
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Would You Rather · your pick" color={game.color}/>
        <SecretBallot
          players={players}
          accent={game.color}
          btnColor="gold"
          completeLabel="Reveal the split →"
          onComplete={revealWith}
          renderVote={(name,onPick)=>(
            <div className="center" style={{gap:14,width:'100%',maxWidth:360}}>
              <p className="muted" style={{fontSize:14}}>Pick your side — nobody else will see.</p>
              <div className="card" style={{padding:'14px 16px',width:'100%',textAlign:'left'}}>
                <p style={{fontSize:13,fontWeight:600,marginBottom:8}}><span style={{color:'var(--teal)'}}>A</span> {card.a}</p>
                <p style={{fontSize:13,fontWeight:600}}><span style={{color:'var(--coral)'}}>B</span> {card.b}</p>
              </div>
              <div className="bigchoice" style={{width:'100%'}}>
                <button className="choice-btn" style={{background:'var(--teal)',color:'#06281f',fontSize:22}} onClick={()=>onPick('A')}>A</button>
                <button className="choice-btn" style={{background:'var(--coral)',color:'#fff',fontSize:22}} onClick={()=>onPick('B')}>B</button>
              </div>
            </div>
          )}
        />
      </div>
    );
  }

  /* ---- REVEAL ---- */
  if(phase==='reveal'){
    const teamA=players.filter(p=>votes[p]==='A');
    const teamB=players.filter(p=>votes[p]==='B');
    return (
      <div className="app screen" style={{overflow:'hidden'}}>
        <Burst fire={split} colors={['#FF8A3C','#16C2A3','#FFC22E']}/>
        <TopBar title="Would You Rather · results" color={game.color}/>
        <div className="center" style={{flex:1,padding:'18px 26px',gap:10}}>
          <div className="kicker">{split?'dead split!':'the room has spoken'}</div>
          <div className="wyr-split-bar">
            <div className="wyr-split-a" style={{width:(countA/players.length*100)+'%'}}><b>{countA}</b></div>
            <div className="wyr-split-b" style={{width:(countB/players.length*100)+'%'}}><b>{countB}</b></div>
          </div>
          <div className="row" style={{width:'100%',maxWidth:360,gap:12}}>
            <div className="card" style={{flex:1,padding:'12px 14px'}}>
              <div className="panel-title" style={{marginBottom:8,color:'var(--teal)'}}>Team A</div>
              <p style={{fontSize:13,color:'var(--ink)',fontWeight:600,marginBottom:8}}>{card.a}</p>
              <div className="wrap" style={{gap:6}}>{teamA.map(p=><div key={p} className="chip" style={{fontSize:13}}><Avatar name={p} size={18}/>{p}</div>)}</div>
            </div>
            <div className="card" style={{flex:1,padding:'12px 14px'}}>
              <div className="panel-title" style={{marginBottom:8,color:'var(--coral)'}}>Team B</div>
              <p style={{fontSize:13,color:'var(--ink)',fontWeight:600,marginBottom:8}}>{card.b}</p>
              <div className="wrap" style={{gap:6}}>{teamB.map(p=><div key={p} className="chip" style={{fontSize:13}}><Avatar name={p} size={18}/>{p}</div>)}</div>
            </div>
          </div>
          {!split && <p className="muted" style={{fontSize:13}}>Minority ({minority}): {players.filter(p=>votes[p]===minority).map(p=>p).join(', ')}</p>}
        </div>
        <div className="pad" style={{paddingTop:6}}>
          <Btn color="gold" size="lg" onClick={next}>{turn+1>=totalRounds?'See results →':'Next round →'}</Btn>
        </div>
      </div>
    );
  }

  /* ---- DONE ---- */
  return (
    <div className="app screen">
      <TopBar onBack={onExit} title="Would You Rather" color={game.color}/>
      <div className="center" style={{flex:1,padding:'20px 24px',gap:14}}>
        <div className="stamp sh-gold" style={{fontSize:50}}>That's a wrap!</div>
        {scoring
          ? <div style={{width:'100%',maxWidth:360}}><ScoreBoard scores={scores} players={players} accent="var(--gold)"/></div>
          : <p className="serif-i" style={{fontSize:21,color:'#FFD79A'}}>no wrong answers… only uncomfortable ones</p>}
        <div className="btn-row" style={{width:'100%',maxWidth:360,marginTop:6}}>
          <Btn variant="ghost" onClick={leave}>Home</Btn>
          <Btn color="gold" onClick={()=>setPhase('setup')}>Play again ↻</Btn>
        </div>
      </div>
    </div>
  );
}

window.GameWouldYouRather = GameWouldYouRather;
