/* ============================================================
   HOT TAKE — does the reader secretly agree?
   ============================================================ */
const { useState: useH, useMemo: useMH, useRef: useRH } = React;

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

function GameHotTake({ game, players, scoring, scores, addScore, onExit, onHome }){
  const leave=onHome||onExit;
  const [tiers,setTiers]=useH({Mild:true,Spicy:true,Chaotic:false});
  const [rounds,setRounds]=useH(1);
  const [phase,setPhase]=useH('setup');     // setup | card | stance | vote | reveal | done
  const deckRef=useRH(null);
  const [order,setOrder]=useH([]);
  const [turn,setTurn]=useH(0);
  const [card,setCard]=useH(null);
  const [stance,setStance]=useH(null);       // 'A' | 'D'
  const [guesses,setGuesses]=useH({});

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

  const begin=()=>{
    const pool=activeTiers.flatMap(t=>DATA.HOTTAKE[t].map(text=>({text,tier:t})));
    deckRef.current=makeDeck(pool);
    const ord=[]; for(let r=0;r<rounds;r++) shuffle(players).forEach(p=>ord.push(p));
    setOrder(ord); setTurn(0); drawFor(0);
  };
  const drawFor=()=>{ setCard(deckRef.current.draw()); setStance(null); setGuesses({}); setPhase('card'); };

  const active=order[turn];
  const others=players.filter(p=>p!==active);

  const revealWith=(v)=>{
    setGuesses(v);
    if(scoring){
      let wrong=0;
      others.forEach(p=>{ const g=v[p]; if(g && g===stance) addScore(p,1); else wrong++; });
      addScore(active, wrong);
    }
    setPhase('reveal');
  };
  const next=()=>{ if(turn+1>=order.length){ setPhase('done'); } else { setTurn(turn+1); drawFor(turn+1); } };

  /* ---- SETUP ---- */
  if(phase==='setup'){
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Hot Take" color={game.color}/>
        <div className="setup">
          <h2>Hot Take</h2>
          <p className="lead">One player reads a spicy opinion and secretly picks a side. Everyone else guesses: do they <i>really</i> agree?</p>
          <div className="field">
            <label>Spice level</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}}>{TIER_META[t].emoji}</span>
                  <div className="lbl"><b>{t}</b><small>{DATA.HOTTAKE[t].length} cards</small></div>
                  <Switch on={tiers[t]} onChange={v=>setTiers({...tiers,[t]:v})}/>
                </div>
              ))}
            </div>
          </div>
          <div className="field">
            <label>Rounds per player</label>
            <Stepper value={rounds} min={1} max={3} onChange={setRounds}/>
          </div>
          <div style={{marginTop:8}}><Btn color="teal" size="lg" disabled={activeTiers.length===0} onClick={begin}>{activeTiers.length===0?'Pick a spice level':'Start →'}</Btn></div>
        </div>
      </div>
    );
  }

  /* ---- CARD ---- */
  if(phase==='card'){
    const tm=TIER_META[card.tier];
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Hot Take" color={game.color} right={<span className="mono" style={{fontSize:11,color:'#9082BE'}}>{turn+1}/{order.length}</span>}/>
        <div className="center" style={{flex:1,padding:'14px 26px',gap:14}}>
          <div className="kicker">reads aloud</div>
          <div className="display" style={{fontSize:34}}>{active}</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">"{card.text}"</div>
          </div>
          <p className="muted" style={{maxWidth:300,fontSize:14}}>Read it with a straight face. Then secretly pick your real stance.</p>
        </div>
        <div className="pad" style={{paddingTop:6}}><Btn color="teal" size="lg" onClick={()=>setPhase('stance')}>{active} decides secretly →</Btn></div>
      </div>
    );
  }

  /* ---- STANCE (private to active) ---- */
  if(phase==='stance'){
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Hot Take · your secret" color={game.color}/>
        <SecretBallot
          players={[active]}
          accent={game.color}
          btnColor="teal"
          autoComplete
          onComplete={(v)=>{ setStance(v[active]); setPhase('vote'); }}
          renderVote={(name,onPick)=>(
            <div className="center" style={{gap:16,width:'100%',maxWidth:360}}>
              <p className="serif-i" style={{fontSize:20,color:'#FFD79A',maxWidth:320}}>"{card.text}"</p>
              <p className="muted">What's your <b style={{color:'var(--cream)'}}>true</b> stance?</p>
              <div className="bigchoice" style={{width:'100%'}}>
                <button className="choice-btn" style={{background:'var(--teal)',color:'#06281f'}} onClick={()=>onPick('A')}>👍 I agree</button>
                <button className="choice-btn" style={{background:'var(--coral)',color:'#fff'}} onClick={()=>onPick('D')}>👎 I disagree</button>
              </div>
            </div>
          )}
        />
      </div>
    );
  }

  /* ---- VOTE (secret pass-around) ---- */
  if(phase==='vote'){
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Hot Take · guess the stance" color={game.color}/>
        <SecretBallot
          players={others}
          accent={game.color}
          btnColor="teal"
          completeLabel="Reveal the truth →"
          onComplete={revealWith}
          renderVote={(name,onPick)=>(
            <div className="center" style={{gap:14,width:'100%',maxWidth:360}}>
              <p className="muted" style={{fontSize:14}}>Does <b style={{color:'var(--cream)'}}>{active}</b> secretly agree with this?</p>
              <p className="serif-i" style={{fontSize:18,color:'#FFD79A',maxWidth:300}}>"{card.text}"</p>
              <div className="bigchoice" style={{width:'100%'}}>
                <button className="choice-btn" style={{background:'var(--teal)',color:'#06281f',fontSize:20}} onClick={()=>onPick('A')}>👍 They agree</button>
                <button className="choice-btn" style={{background:'var(--coral)',color:'#fff',fontSize:20}} onClick={()=>onPick('D')}>👎 They disagree</button>
              </div>
            </div>
          )}
        />
      </div>
    );
  }

  /* ---- REVEAL ---- */
  if(phase==='reveal'){
    const agree=stance==='A';
    const wrong=others.filter(p=>guesses[p]!==stance);
    return (
      <div className="app screen" style={{overflow:'hidden'}}>
        <Burst fire={true} colors={['#16C2A3','#FF5C9D','#FFC22E']}/>
        <TopBar title="Hot Take · revealed" color={game.color}/>
        <div className="center" style={{flex:1,padding:'18px 26px',gap:8}}>
          <div className="kicker">{active} actually…</div>
          <div className={'stamp '+(agree?'sh-teal':'sh-coral')} style={{fontSize:54}}>{agree?'AGREES':'DISAGREES'}</div>
          <p className="serif-i" style={{fontSize:20,color:'#FFD79A',marginTop:6,maxWidth:320}}>"{card.text}"</p>
          <div className="card" style={{marginTop:16,maxWidth:360,width:'100%'}}>
            <div className="panel-title" style={{marginBottom:8}}>Who got fooled</div>
            {wrong.length===0
              ? <p style={{color:'var(--ink)',fontWeight:600}}>Nobody! {active} is an open book. 📖</p>
              : <div className="wrap" style={{gap:7}}>{wrong.map(p=><div key={p} className="chip" style={{fontSize:14}}><Avatar name={p} size={20}/>{p}</div>)}</div>}
            {scoring && <div className="mono" style={{fontSize:11,color:'#897B6A',marginTop:12}}>+{wrong.length} to {active} · +1 each to {others.length-wrong.length} correct guesser{others.length-wrong.length===1?'':'s'}</div>}
          </div>
        </div>
        <div className="pad" style={{paddingTop:6}}>
          <Btn color="teal" size="lg" onClick={next}>{turn+1>=order.length?'See results →':`Next: ${order[turn+1]} →`}</Btn>
        </div>
      </div>
    );
  }

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

window.GameHotTake = GameHotTake;
