/* ============================================================
   BRANCHING VOTES — story-fork moments the group owns.
   • VoteMainView      — dilemma + option cards + live tally
   • VotePlayerOverlay — tap an option (changeable until close)
   ============================================================ */
const { useState: useS_vt } = React;

function voteTally(v){
  const t = {}; v.options.forEach(o=>t[o.id]=0);
  Object.entries(v.ballots).forEach(([pid,oid])=>{ const w=(v.weights&&v.weights[pid])||1; if(t[oid]!=null) t[oid]+=w; });
  return t;
}

function VoteMainView({ vote }){
  const game = useGame();
  const v = vote;
  useGameEvents((ev)=>{ if(ev.type==='vote-cast'){ try{ audio.play('beat'); }catch(_){} } else if(ev.type==='vote-close'){ try{ audio.play('coin'); }catch(_){} } });
  const closed = v.status==='closed';
  const tally = voteTally(v);
  const totalCast = Object.keys(v.ballots).length;
  const totalWeight = Object.values(tally).reduce((a,b)=>a+b,0) || 1;
  const maxV = Math.max(0, ...Object.values(tally));
  const result = v.result;

  return (
    <div className={`vote-stage ${closed?'is-closed':''}`}>
      <Embers count={16}/>
      <div className="vote-titlebar">
        <div className="vote-eyebrow">{closed ? 'The party has spoken' : (v.secret ? 'A secret vote' : 'An open vote')}</div>
        <div className="vote-prompt display">{v.prompt}</div>
      </div>

      <div className={`vote-options n${v.options.length}`}>
        {v.options.map(o=>{
          const count = tally[o.id]||0;
          const pct = closed ? Math.round((count/totalWeight)*100) : 0;
          const isWin = closed && result===o.id;
          const voters = (!v.secret && !closed) || closed
            ? game.players.filter(p=>v.ballots[p.id]===o.id) : [];
          return (
            <div key={o.id} className={`vote-card ${isWin?'win':''} ${closed?'revealed':''}`}>
              <div className="vote-card-label">{o.label}</div>
              {closed ? (
                <>
                  <div className="vote-bar-track"><div className="vote-bar" style={{ width:pct+'%' }}></div></div>
                  <div className="vote-card-foot"><span className="vote-count">{count} {count===1?'vote':'votes'}</span><span className="vote-pct">{pct}%</span></div>
                </>
              ) : (
                <div className="vote-card-foot">
                  {v.secret
                    ? <span className="vote-count muted">{Object.values(v.ballots).filter(x=>x===o.id).length} in</span>
                    : <span className="vote-count">{Object.values(v.ballots).filter(x=>x===o.id).length} in</span>}
                </div>
              )}
              {voters.length>0 && (
                <div className="vote-voters">{voters.map(p=><span key={p.id} className="vote-chip">{p.name.split(' ')[0]}</span>)}</div>
              )}
              {isWin && <div className="vote-win-flag">CHOSEN</div>}
            </div>
          );
        })}
      </div>

      <div className="vote-foot">
        {!closed
          ? <span className="muted">{totalCast}/{game.players.length} voted · {v.secret?'tallies hidden until the vote closes':'change your vote any time'}</span>
          : (result ? <span className="gold">The path is set</span> : <span className="vote-tie">A tie — the Keeper must decide</span>)}
      </div>
    </div>
  );
}
window.VoteMainView = VoteMainView;

function VotePlayerOverlay({ player }){
  const game = useGame();
  const v = game.vote;
  if(!v.open) return null;
  const closed = v.status==='closed';
  const mine = v.ballots[player.id];
  const pick = (oid)=>{ if(closed) return; Game.castVote(player.id, oid); haptic(HAPTIC.card); try{audio.play('beat');}catch(_){} };
  const chosen = v.options.find(o=>o.id===v.result);

  return (
    <div className={`vote-overlay ${closed?'is-closed':''}`}>
      <Embers count={10}/>
      <div className="vote-ov-inner animate-fade-rise">
        <div className="vote-ov-eyebrow">{closed?'The vote is closed':(v.secret?'🗳 Secret vote':'🗳 Open vote')}</div>
        <h2 className="vote-ov-prompt display">{v.prompt}</h2>
        <div className="vote-ov-cards">
          {v.options.map(o=>{
            const sel = mine===o.id;
            const isWin = closed && v.result===o.id;
            return (
              <button key={o.id} className={`vote-ov-card liquid-glass glass-btn ${sel?'selected':''} ${isWin?'win':''}`}
                      disabled={closed} onClick={()=>pick(o.id)}>
                <span className="vote-ov-card-label">{o.label}</span>
                {sel && !closed && <span className="vote-ov-tick">✓ your vote</span>}
                {isWin && <span className="vote-ov-tick win">chosen</span>}
              </button>
            );
          })}
        </div>
        <div className="vote-ov-state">
          {closed
            ? (chosen ? `The party chose: ${chosen.label}` : 'A tie — the Keeper will decide.')
            : (mine ? 'Vote locked — tap another to change it' : 'Tap your choice. You can change it until the vote closes.')}
        </div>
      </div>
    </div>
  );
}
window.VotePlayerOverlay = VotePlayerOverlay;
