<script> 
    import {push} from 'svelte-spa-router';
    import {unlockedColors} from '../stores/colorStore.js';
    import {LEVELS} from '../game/levelData.js';

    function playLevel(id) {
        push(`/game?level=${id}`);
    }

    // level 1 is always unlocked, other based on prev level completion
    function isUnlocked(level){
        if (level.id === 1) return true;
        const prevLevel = LEVELS.find(l => l.id === level.id -1);
        return $unlockedColors.includes(prevLevel.color);
    }
</script>

<div class="screen">
    <h1>Choose a level</h1>

    <div class="level-grid">
        {#each LEVELS as level}
        <button
        class="level-card"
        class:locked={!isUnlocked(level)}
        style="--c: {level.color}"
        on:click={() => isUnlocked(level) && playLevel(level.id)}
        >
        <div class="swatch"></div>
        <span class="name">{isUnlocked(level) ? level.name: '?'}</span>
        </button>
        {/each}
    </div>

    <button class="back" on:click={() => push('/')}>back</button>
</div>

<style>
    .screen{
        width: 800px;
        height: 450px; 
        margin: 0 auto;
        background: #111;
        color: white; 
        display: flex;
        flex-direction: column;
        align-items: center; 
        justify-content: center;
        gap: 24px;
    }
    h1 {
        font-family: 'Courier New', Courier, monospace;
        font-size: 34px;
        font-weight: 400;
    }
    .level-grid {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 12px;
        max-width: 560px;
    }
    .level-card {
        width: 100px;
        height: 118px;
        background: #222;
        border: 1px solid #444;
        border-radius: 12px;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 8px;
        color: white;
        transition: transform 0.15s, border-color 0.15s;
    }
    .level-card:hover:not(.locked) {
        transform: translateY(-4px);
        border-color: var(--c);
    }
    .level-card.locked {
        opacity: 0.4;
        cursor: not-allowed;
    }
    .swatch {
        width: 44px;
        height: 44px;
        border-radius: 50%;
        background: var(--c);
    }
    .level-card.locked .swatch {
        background: #555;
    }
    .name {
        font-family: 'Courier New', Courier, monospace;
        font-size: 13px;
        text-align: center;
        padding: 0 4px;
    }
    .back{
        background: none;
        border: 1px solid #555;
        color: #aaa;
        padding: 8px 24px;
        border-radius: 20px;
        cursor: pointer;
        font-family:'Courier New', Courier, monospace;
        font-size: 16px;
    }
</style>