<script>
    import { onMount, onDestroy } from 'svelte';
    import { apiRequest } from '../lib/api';
    
    import LobbyPhase from '../components/LobbyPhase.svelte';
    import CharacterCreationPhase from '../components/CharacterCreationPhase.svelte';
    import SceneSetupPhase from '../components/SceneSetupPhase.svelte';
    import ScenePhase from '../components/ScenePhase.svelte';
    import UpkeepPhase from '../components/UpkeepPhase.svelte';

    export let params = {};
    let gameId = params.id;
    let playerId = params.pid;

    let state = null;
    let error = '';
    let intervalId;

    async function fetchState() {
        try {
            const data = await apiRequest(`/game/${gameId}/player/${playerId}/state`);
            state = data;
            error = '';
        } catch (err) {
            error = err.message;
        }
    }

    onMount(() => {
        fetchState();
        // Poll every 2 seconds
        intervalId = setInterval(fetchState, 2000);
    });

    onDestroy(() => {
        if (intervalId) clearInterval(intervalId);
    });
</script>

{#if error}
    <div class="alert alert-danger" style="margin: 20px;">
        Error connecting to game: {error}
    </div>
{/if}

{#if state}
    <div class="dashboard-container {state.player.is_ghost ? 'ghost-world' : ''}">
        {#if state.game.phase === 'lobby'}
            <LobbyPhase {state} />
        {:else if state.game.phase === 'character_creation' || state.game.phase === 'swap_techniques'}
            <CharacterCreationPhase {state} />
        {:else if state.game.phase === 'scene_setup'}
            <SceneSetupPhase {state} />
        {:else if state.game.phase === 'scene'}
            <ScenePhase {state} />
        {:else if state.game.phase === 'between_scenes' || state.game.phase === 'deep_upkeep'}
            <UpkeepPhase {state} />
        {:else}
            <div class="card p-4">Unknown phase: {state.game.phase}</div>
        {/if}
    </div>
{:else if !error}
    <div class="loading-container">
        <p>Loading game state...</p>
    </div>
{/if}

<style>
    .loading-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        color: white;
        font-size: 1.5rem;
    }
</style>
