<script>
    import { slide } from 'svelte/transition';
    import { apiRequest } from '../../lib/api';
    import { crewLabel } from '../../lib/cards';
    import { tooltip } from '../../lib/tooltip';
    import CharacterSheet from './CharacterSheet.svelte';

    export let state;

    let openTargetId = null;
    let showObjectives = false;
    let objError = '';

    $: isDeep = state.player.role === 'deep';

    // Track which Pi-Rats have faced a Deep Challenge this scene so the Deep can
    // see who still needs one before ending the scene.
    $: challengedIds = new Set(
        (state.challenges || [])
            .filter(c => c.challenge_type === 'deep')
            .map(c => c.target_player_id)
    );
    function hasBeenChallenged(p) {
        return p.role === 'pirat' && challengedIds.has(p.id);
    }

    // The Deep ticks Crew Objectives off here (moved from the old Deep panel).
    async function toggleCrew(type) {
        objError = '';
        try {
            await apiRequest(`/game/${state.game.id}/player/${state.player.id}/objective/toggle`, 'POST', { type });
        } catch (e) {
            objError = e.message;
        }
    }

    // Pi-Rats first, the Deep last; otherwise keep join order.
    $: crew = [...state.players].sort((a, b) => (a.role === 'deep' ? 1 : 0) - (b.role === 'deep' ? 1 : 0));
    $: captainId = state.game.captain_player_id;
    $: openTarget = openTargetId ? state.players.find(p => p.id === openTargetId) : null;
    $: crewDone = [state.game.completed_crew_1, state.game.completed_crew_2, state.game.completed_crew_3].filter(Boolean).length;

    function handSize(p) {
        try { return JSON.parse(p.hand_cards || '[]').length; } catch { return 0; }
    }
    function roleIcon(p) {
        if (p.role === 'deep') return '🌊';
        if (p.is_ghost) return '👻';
        if (p.is_dead) return '💀';
        return '🐀';
    }
</script>

<div class="crew-column">
    <div class="crew-bubbles">
        {#each crew as p (p.id)}
            <button
                class="crew-bubble"
                class:is-you={p.id === state.player.id}
                class:is-deep={p.role === 'deep'}
                class:is-dead={p.is_dead}
                class:is-ghost={p.is_ghost}
                title="View {p.name}'s character sheet"
                on:click={() => openTargetId = p.id}
            >
                {#if isDeep && p.role === 'pirat'}
                    <span
                        class="challenge-check"
                        class:done={hasBeenChallenged(p)}
                        use:tooltip={hasBeenChallenged(p)
                            ? `${p.name} has faced a Challenge this scene.`
                            : `${p.name} hasn't faced a Challenge yet — the scene can't end until they do (or the Obstacle List is cleared).`}
                    >{hasBeenChallenged(p) ? '✓' : '○'}</span>
                {/if}
                <span class="bubble-icon">{roleIcon(p)}</span>
                <span class="bubble-name">{crewLabel(p, captainId)}</span>
                <span class="bubble-meta">
                    {#if p.role === 'deep'}Deep{:else}Rank {p.rank}{/if} · 🃏 {handSize(p)}
                </span>
            </button>
        {/each}

        <!-- Crew Objectives sits at the end of the roster and slides open in place -->
        <button
            class="crew-objectives-toggle"
            aria-expanded={showObjectives}
            on:click={() => showObjectives = !showObjectives}
        >
            <span class="co-label">{showObjectives ? '▾' : '▸'} Crew Objectives</span>
            <span class="co-count">{crewDone}/3</span>
        </button>
        {#if showObjectives}
            <div class="crew-objectives-detail" transition:slide>
                {#if objError}<div class="alert alert-danger">{objError}</div>{/if}
                <label class="checkbox-label">
                    <input type="checkbox" checked={state.game.completed_crew_1} disabled={!isDeep} on:change={() => toggleCrew('crew_1')}>
                    <span>Steal a Ship</span>
                </label>
                <label class="checkbox-label">
                    <input type="checkbox" checked={state.game.completed_crew_2} disabled={!isDeep} on:change={() => toggleCrew('crew_2')}>
                    <span>Choose a Captain</span>
                </label>
                <label class="checkbox-label">
                    <input type="checkbox" checked={state.game.completed_crew_3} disabled={!isDeep} on:change={() => toggleCrew('crew_3')}>
                    <span>Commit Piracy</span>
                </label>
                {#if isDeep}<p class="info-text" style="font-size: 0.75rem; margin: 0.25rem 0 0;">As the Deep, tick these off as the crew earns them.</p>{/if}
            </div>
        {/if}
    </div>
</div>

{#if openTarget}
    <CharacterSheet {state} target={openTarget} on:close={() => openTargetId = null} />
{/if}
