/* ============================================================
   IMPOSTER — social deduction word game
   ============================================================ */
const { useState: useI, useMemo: useMI } = React;

function GameImposter({ game, players, scoring, addScore, onExit, onHome }){
  const leave=onHome||onExit;
  const packCats = Object.keys(DATA.IMPOSTER);
  const pickCats = ['Random', ...packCats];
  const [cat,setCat]=useI('Random');
  const [phase,setPhase]=useI('setup');   // setup | deal | round | vote | reveal
  const [deal,setDeal]=useI(null);          // {imposter, word, starter, order, category}
  const [votes,setVotes]=useI({});          // voter -> accused
  const [revote,setRevote]=useI(0);

  const resolveCat=()=> cat==='Random' ? rand(packCats) : cat;

  const startDeal=()=>{
    const category=resolveCat();
    const imposter=rand(players);
    const word=rand(DATA.IMPOSTER[category]);
    const order=shuffle(players);
    setDeal({imposter,word,starter:order[0],order,category});
    setVotes({}); setPhase('deal');
  };

  const tally = useMI(()=>{
    const c={}; Object.values(votes).forEach(a=>c[a]=(c[a]||0)+1);
    let max=0,leaders=[]; Object.entries(c).forEach(([p,n])=>{ if(n>max){max=n;leaders=[p];} else if(n===max) leaders.push(p); });
    return {counts:c,max,leaders};
  },[votes]);

  const finishVote=(v)=>{
    if(tally.leaders.length>1){ // tie → revote
      setVotes({}); setRevote(r=>r+1); return;
    }
  };

  const accused = tally.leaders.length===1 ? tally.leaders[0] : null;
  const groupWins = accused===deal?.imposter;

  const applyScore=()=>{
    if(!scoring||!deal) return;
    if(groupWins){ players.forEach(p=>{ if(p!==deal.imposter) addScore(p,1); }); }
    else { addScore(deal.imposter,3); }
  };

  /* ----- SETUP ----- */
  if(phase==='setup'){
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Imposter" color={game.color}/>
        <div className="setup">
          <h2>Imposter</h2>
          <p className="lead">Everyone gets the secret word — except one faker. Give clues, sniff out the imposter.</p>
          <div className="field">
            <label>Category pack</label>
            <div className="wrap" style={{gap:9}}>
              {pickCats.map(c=><button key={c} onClick={()=>setCat(c)} style={{
                fontFamily:'var(--font-display)',fontWeight:700,fontSize:16,padding:'11px 17px',borderRadius:40,cursor:'pointer',
                border:'2.5px solid '+(c===cat?'transparent':'rgba(255,255,255,.18)'),
                background:c===cat?'var(--gold)':'transparent',color:c===cat?'var(--ink)':'#C9BCEC',transition:'all .15s'
              }}>{c}</button>)}
            </div>
          </div>
          <div className="card" style={{padding:'15px 18px',background:'rgba(255,255,255,.05)',color:'var(--cream)',border:'1.5px solid rgba(255,255,255,.12)',boxShadow:'none'}}>
            <div className="row" style={{gap:10}}>
              <span style={{fontSize:22}}>🤫</span>
              <div style={{fontSize:14,color:'#C9BCEC'}}>1 imposter among <b style={{color:'var(--cream)'}}>{players.length}</b> players · word drawn from <b style={{color:'var(--cream)'}}>{cat==='Random'?'any pack':cat}</b></div>
            </div>
          </div>
          <div style={{marginTop:24}}><Btn color="gold" size="lg" onClick={startDeal}>Deal roles →</Btn></div>
        </div>
      </div>
    );
  }

  /* ----- DEAL (private reveal) ----- */
  if(phase==='deal'){
    return (
      <div className="app screen">
        <TopBar title="Imposter · secret roles" color={game.color}/>
        <PrivateReveal players={deal.order} accent={game.color} doneLabel="Let's give clues"
          onDone={()=>setPhase('round')}
          getContent={(name)=>{
            const isImp=name===deal.imposter;
            return (
              <div className="center" style={{gap:16}}>
                <div className="role-card-big" style={{background:isImp?'var(--coral)':'var(--cream)'}}>
                  {isImp ? (
                    <>
                      <div className="kicker" style={{color:'#7a1500'}}>your role</div>
                      <div className="display" style={{fontSize:40,margin:'8px 0',color:'#fff'}}>The Imposter</div>
                      <p style={{color:'#fff',fontWeight:600,fontSize:15}}>You do <b>not</b> know the word. The category is:</p>
                      <div className="secret-word" style={{color:'#fff',marginTop:8}}>{deal.category}</div>
                      <p style={{color:'rgba(255,255,255,.85)',fontSize:13.5,marginTop:12}}>Blend in. Give a vague clue and hope nobody notices.</p>
                    </>
                  ) : (
                    <>
                      <div className="kicker">you know the word</div>
                      <div className="tier-pill" style={{background:'var(--ink)',color:'var(--cream)',marginTop:8}}>{deal.category}</div>
                      <div className="secret-word" style={{marginTop:14}}>{deal.word}</div>
                      <p className="muted" style={{color:'#6E6453',fontSize:13.5,marginTop:14}}>Give a one-word clue that proves you know it — without saying it outright.</p>
                    </>
                  )}
                </div>
              </div>
            );
          }}/>
      </div>
    );
  }

  /* ----- ROUND GUIDE ----- */
  if(phase==='round'){
    return (
      <div className="app screen">
        <TopBar onBack={onExit} title="Imposter · clue round" color={game.color}/>
        <div className="center" style={{flex:1,padding:'20px 26px',gap:8}}>
          <div className="kicker">starts the clue circle</div>
          <div className="stamp sh-gold" style={{fontSize:54}}>{deal.starter}</div>
          <p className="muted mt16" style={{maxWidth:320}}>Going clockwise from {deal.starter}, each player says <b style={{color:'var(--cream)'}}>one word or short phrase</b> hinting at the secret word — without saying it. Then everyone votes.</p>
          <div className="card" style={{marginTop:18,maxWidth:360,width:'100%',padding:'14px 16px'}}>
            <div className="panel-title" style={{marginBottom:9}}>Clue order</div>
            <div className="wrap" style={{gap:7}}>
              {deal.order.map((p,i)=><div key={p} className="chip" style={{fontSize:14}}><span className="mono" style={{color:'#897BB6',fontSize:12}}>{i+1}</span>{p}</div>)}
            </div>
          </div>
          <div style={{width:'100%',maxWidth:360,marginTop:22}}><Btn color="gold" size="lg" onClick={()=>{setVotes({});setPhase('vote');}}>Everyone's given a clue → Vote</Btn></div>
        </div>
      </div>
    );
  }

  /* ----- VOTE (private, one at a time) ----- */
  if(phase==='vote'){
    return (
      <div className="app screen">
        <TopBar title="Imposter · who's faking?" color={game.color}/>
        <SecretVote key={revote} players={players} accent={game.color}
          onComplete={(v)=>{ setVotes(v); setPhase('reveal'); }}/>
        {revote>0 && <div className="tcenter serif-i" style={{fontSize:18,color:'#FFD79A',paddingBottom:14}}>tie! voting again…</div>}
      </div>
    );
  }

  /* ----- REVEAL ----- */
  if(phase==='reveal'){
    // handle tie → revote
    if(tally.leaders.length>1){
      return (
        <div className="app screen">
          <TopBar title="Imposter" color={game.color}/>
          <div className="center" style={{flex:1,padding:30,gap:10}}>
            <div className="stamp sh-gold" style={{fontSize:52}}>It's a tie!</div>
            <p className="muted" style={{maxWidth:300}}>{tally.leaders.join(' & ')} are tied. Vote again to break it.</p>
            <div style={{width:'100%',maxWidth:300,marginTop:20}}><Btn color="gold" onClick={()=>{setVotes({});setRevote(r=>r+1);setPhase('vote');}}>Re-vote →</Btn></div>
          </div>
        </div>
      );
    }
    return <ImposterReveal game={game} deal={deal} accused={accused} groupWins={groupWins} counts={tally.counts}
      scoring={scoring} onScore={applyScore}
      onAgain={startDeal} onExit={onExit} onHome={leave}/>;
  }
  return null;
}

/* one-at-a-time secret vote */
function SecretVote({ players, accent, onComplete }){
  const [idx,setIdx]=useI(0);
  const [shown,setShown]=useI(false);
  const [votes,setVotes]=useI({});
  const name=players[idx];

  if(idx>=players.length){ return <div className="center" style={{flex:1}}><Btn color="gold" onClick={()=>onComplete(votes)} style={{maxWidth:280}}>Reveal the imposter →</Btn></div>; }

  if(!shown){
    return (
      <div className="reveal-screen screen" key={'p'+idx}>
        <div className="kicker">Pass to</div>
        <div className="display wiggle mt16" style={{fontSize:50}}>{name}</div>
        <p className="muted mt16">Your vote is secret 🤫</p>
        <div style={{width:'100%',maxWidth:340,marginTop:26}}><Btn color="gold" size="lg" onClick={()=>setShown(true)}>Tap to vote</Btn></div>
        <div className="mono mt24" style={{fontSize:12,color:'#7E70AE'}}>{idx+1} / {players.length}</div>
      </div>
    );
  }
  return (
    <div className="screen" style={{padding:'14px 22px 24px'}}>
      <p className="tcenter muted" style={{marginBottom:14}}><b style={{color:'var(--cream)'}}>{name}</b>, who's the imposter?</p>
      <div className="bigchoice">
        {players.filter(p=>p!==name).map((p,i)=>(
          <button key={p} className="choice-btn" style={{background:PALETTE[i%PALETTE.length],fontSize:21,padding:'16px'}}
            onClick={()=>{ const v={...votes,[name]:p}; setVotes(v); setShown(false); setIdx(idx+1); }}>
            {p}
          </button>
        ))}
      </div>
    </div>
  );
}

function ImposterReveal({ game, deal, accused, groupWins, counts, scoring, onScore, onAgain, onExit, onHome }){
  const leave=onHome||onExit;
  const [fired,setFired]=useI(false);
  React.useEffect(()=>{ const t=setTimeout(()=>setFired(true),300); onScore(); return ()=>clearTimeout(t); },[]);
  return (
    <div className="app screen" style={{overflow:'hidden'}}>
      <Burst fire={fired} colors={groupWins?['#16C2A3','#FFC22E','#9A6CFF']:['#FF5A3C','#FF5C9D','#FFC22E']}/>
      <TopBar title="Imposter · the truth" color={game.color}/>
      <div className="center" style={{flex:1,padding:'16px 26px 10px',gap:6}}>
        <div className={'stamp '+(groupWins?'sh-teal':'sh-coral')} style={{fontSize:groupWins?56:60}}>{groupWins?'Caught!':'Got away!'}</div>
        <p className="serif-i" style={{fontSize:21,color:'#FFD79A',marginTop:8}}>{groupWins?'The group sniffed out the faker':'The imposter survived the vote'}</p>

        <div className="card" style={{marginTop:18,maxWidth:360,width:'100%',textAlign:'center'}}>
          <div className="panel-title">The imposter was</div>
          <div className="row" style={{justifyContent:'center',gap:10,margin:'8px 0 14px'}}>
            <Avatar name={deal.imposter} size={30}/><b style={{fontSize:26,fontFamily:'var(--font-display)'}}>{deal.imposter}</b>
          </div>
          <div className="panel-title">The word was</div>
          <div className="secret-word" style={{marginTop:4}}>{deal.word}</div>
          <div className="mono" style={{fontSize:11,color:'#897B6A',marginTop:6}}>{deal.category} · accused: {accused} · {counts[accused]||0} votes</div>
        </div>

        {scoring && <div className="mono" style={{fontSize:12,color:'#A99AD6',marginTop:14}}>
          {groupWins? `+1 to each detective 🕵️` : `+3 to ${deal.imposter} 😈`}
        </div>}
      </div>
      <div className="pad" style={{paddingTop:8}}>
        <div className="btn-row">
          <Btn variant="ghost" onClick={leave}>Home</Btn>
          <Btn color="gold" onClick={onAgain}>Play again ↻</Btn>
        </div>
      </div>
    </div>
  );
}
window.GameImposter = GameImposter;
