<script>
    import {PUBLIC_API_URL} from "$env/static/public";
    import {toast} from "$lib/toast.svelte.js";
    import {goto} from "$app/navigation";
    import Game from "./Game.svelte";
    import Character from "./Character.svelte";

    let step = $state(1);

    let title = $state("");
    let gameContext = $state("");

    let characterName = $state("");
    let characterDescription = $state("");

    const nextStep = (e) => {
        e.preventDefault();
        step = 2;
    };

    const submit = async (e) => {
        e.preventDefault();

        const gameBody = {
            title: title,
            game_context: gameContext
        };

        const gameRes = await fetch(`${PUBLIC_API_URL}/game`, {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            credentials: "include",
            body: JSON.stringify(gameBody)
        });

        const gameData = await gameRes.json();
        if (!gameRes.ok) {
            toast(gameData.error.message, "error");
            if (gameRes.status === 401) goto("/");
            return;
        }

        const sessionProm = fetch(`${PUBLIC_API_URL}/game/${gameData.id}/session`, {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            credentials: "include"
        });

        const charProm = fetch(`${PUBLIC_API_URL}/game/${gameData.id}/character`, {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            credentials: "include",
            body: JSON.stringify({
                name: characterName,
                description: characterDescription
            })
        });

        const [sessionRes, charRes] = await Promise.all([sessionProm, charProm]);
        const [sessionData, charData] = await Promise.all([sessionRes.json(), charRes.json()]);
        
        if(!sessionRes.ok){
            toast(sessionData.error.message, "error");
            if(sessionRes.status === 401) goto("/");
            return;
        }

        if(!charRes.ok){
            toast(charData.error.message, "error");
            if(charRes.status === 401) goto("/");
            return;
        }

        toast("Adventure created!");
        goto(`/game/${gameData.id}`);
    };
</script>

<div class="page">
    <header>
        {#if step === 1}
            <a href="/game" class="back">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M19 12H5M12 5l-7 7 7 7"/>
                </svg>
                My Games
            </a>
        {:else}
            <button class="back" onclick={() => step = 1}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M19 12H5M12 5l-7 7 7 7"/>
                </svg>
                Back
            </button>
        {/if}
    </header>

    <main>
        <div class="step-indicator">
            <div class="step-node" class:active={step >= 1} class:done={step > 1}>
                {#if step > 1}
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M20 6L9 17l-5-5"/>
                    </svg>
                {:else}
                    1
                {/if}
            </div>
            <div class="step-line" class:active={step > 1}></div>
            <div class="step-node" class:active={step >= 2}>2</div>
        </div>

        {#if step === 1}
            <Game bind:title bind:gameContext onNext={nextStep} />
        {:else}
            <Character bind:name={characterName} bind:description={characterDescription} onSubmit={submit} onBack={() => step = 1} />
        {/if}
    </main>
</div>

<style>
    .page {
        min-height: 100vh;
        display: flex;
        flex-direction: column;
        background: #0b0b10;
    }

    header {
        padding: 1.25rem 2rem;
        border-bottom: 1px solid #1e1e28;
    }

    .back {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-size: 0.85rem;
        font-weight: 500;
        color: #6b6b7a;
        text-decoration: none;
        background: none;
        border: none;
        padding: 0;
        cursor: pointer;
        font-family: inherit;
        transition: color 0.15s;
    }

    .back:hover { color: #a1a1aa; }

    main {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 3rem 1.5rem 6rem;
        gap: 2rem;
    }

    .step-indicator {
        display: flex;
        align-items: center;
    }

    .step-node {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        border: 2px solid #2a2a38;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.8rem;
        font-weight: 600;
        color: #44445a;
        background: #0f0f18;
        transition: border-color 0.3s, color 0.3s, background 0.3s;
        flex-shrink: 0;
    }

    .step-node.active {
        border-color: #c084fc;
        color: #c084fc;
    }

    .step-node.done {
        background: #c084fc;
        border-color: #c084fc;
        color: #0b0b10;
    }

    .step-line {
        width: 80px;
        height: 2px;
        background: #2a2a38;
        transition: background 0.3s;
    }

    .step-line.active {
        background: #c084fc;
    }

    @media (max-width: 700px) {
        main { padding: 2rem 1.25rem 4rem; }
        .step-line { width: 48px; }
    }
</style>
