<script>
    import { apiRequest } from '../../lib/api';
    export let state;
    let error = '';
    $: proposals = JSON.parse(state.game.objective_votes || '[]');
    const labels = { personal_1: 'Gat', personal_2: 'Name', personal_3: 'Die/Retire' };
    async function vote(proposal_id, approve) {
        error = '';
        try {
            await apiRequest(`/game/${state.game.id}/player/${state.player.id}/objective/vote`, 'POST', { proposal_id, approve });
        } catch (e) { error = e.message; }
    }
</script>

{#if error}<div class="alert alert-danger">{error}</div>{/if}
{#each proposals as proposal (proposal.id)}
    <div class="card glass-panel">
        <h3>Objective Vote: {state.players.find(p => p.id === proposal.target_id)?.name} — {labels[proposal.type]}</h3>
        <p class="info-text">Majority decides. The Captain breaks ties; a tie without a Captain does not award the objective. Votes close when decided or the scene ends.</p>
        <p>{Object.values(proposal.ballots).filter(Boolean).length} Yes · {Object.values(proposal.ballots).filter(v => !v).length} No · {state.players.filter(p => !p.needs_reroll && !(p.id in proposal.ballots)).length} waiting</p>
        {#if !state.player.needs_reroll}
            <div class="challenge-actions">
                <button class="btn btn-primary" aria-pressed={proposal.ballots[state.player.id] === true} disabled={proposal.ballots[state.player.id] === true} on:click={() => vote(proposal.id, true)}>Yes{proposal.ballots[state.player.id] === true ? ' ✓' : ''}</button>
                <button class="btn btn-secondary" aria-pressed={proposal.ballots[state.player.id] === false} disabled={proposal.ballots[state.player.id] === false} on:click={() => vote(proposal.id, false)}>No{proposal.ballots[state.player.id] === false ? ' ✓' : ''}</button>
            </div>
        {/if}
    </div>
{/each}
