<script>
    import { onMount, onDestroy } from 'svelte';
    import { push } from 'svelte-spa-router';
    import { gameCompleted, hasSeenControls } from '../stores/colorStore.js';

    const COLORS = [
        '#970505', '#CF8917', '#E3D214', '#39BD1C',
        '#12B6C8', '#170CB7', '#6613BA', '#C71287',
        '#753F16', '#FFD700',
    ];

    let sparks = [];

    onMount(() => {
        sparks = Array.from({ length: 140 }, () => ({
            x:        Math.random() * 100,
            y:        Math.random() * 100,
            size:     Math.random() * 3 + 1,
            color:    COLORS[Math.floor(Math.random() * COLORS.length)],
            delay:    -(Math.random() * 4),
            duration: Math.random() * 2 + 1,
        }));
    });

    let showControls = false;
    const miniKeys = { left: false, right: false, jump: false };

    function startGame() {
        if (!$gameCompleted && !$hasSeenControls) {
            showControls = true;
        } else {
            push('/levelselect');
        }
    }

    function goReady() {
        hasSeenControls.set(true);
        push('/levelselect');
    }

    const onKeyDown = (e) => {
        if (!showControls) return;
        if (e.key === 'ArrowLeft'  || e.key === 'a') { miniKeys.left  = true; e.preventDefault(); }
        if (e.key === 'ArrowRight' || e.key === 'd') { miniKeys.right = true; e.preventDefault(); }
        if ((e.key === 'ArrowUp' || e.key === 'w' || e.key === ' ') && !e.repeat) {
            miniKeys.jump = true;
            e.preventDefault();
        }
    };

    const onKeyUp = (e) => {
        if (e.key === 'ArrowLeft'  || e.key === 'a') miniKeys.left  = false;
        if (e.key === 'ArrowRight' || e.key === 'd') miniKeys.right = false;
    };

    const onBlur = () => {
        miniKeys.left  = false;
        miniKeys.right = false;
        miniKeys.jump  = false;
    };

    window.addEventListener('keydown', onKeyDown);
    window.addEventListener('keyup',   onKeyUp);
    window.addEventListener('blur',    onBlur);

    function initMiniCanvas(node) {
        const CANVAS_W = 680;
        const CANVAS_H = 124;
        const PLAT_H   = 16;

        const sketch = (p) => {
            let playerSprite;
            let playerImg;
            let canJump    = true;
            let peakReached = false;

            p.preload = () => {
                playerImg = p.loadImage('/assets/player.png');
            };

            p.setup = () => {
                const canvas = p.createCanvas(CANVAS_W, CANVAS_H);
                canvas.parent(node);
                p.world.gravity.y = 30;

                // Ground platform
                const plat = new p.Sprite(CANVAS_W / 2, CANVAS_H - PLAT_H / 2, CANVAS_W, PLAT_H);
                plat.collider = 'static';
                const g = p.createGraphics(CANVAS_W, PLAT_H);
                g.clear();
                g.noStroke();
                g.fill('#888888');
                g.rect(0, 0, CANVAS_W, PLAT_H, 4);
                plat.img = g;

                // Player centered above platform
                playerSprite = new p.Sprite(CANVAS_W / 2, CANVAS_H - PLAT_H - 22, 28, 28);
                playerSprite.rotationLock = true;
                playerSprite.bounciness  = 0;
                if (playerImg) playerSprite.img = playerImg;
            };

            p.draw = () => {
                p.background(18);
                p.allSprites.update();

                if (playerSprite) {
                    // Jump state machine — mirrors Player.js logic
                    const vy = playerSprite.vel.y;
                    if (vy > 2) peakReached = true;
                    if (peakReached && vy > -0.5 && vy < 1.5) {
                        canJump     = true;
                        peakReached = false;
                    }

                    // Horizontal movement with friction
                    if (miniKeys.left)  playerSprite.vel.x = -5;
                    if (miniKeys.right) playerSprite.vel.x =  5;
                    if (!miniKeys.left && !miniKeys.right) playerSprite.vel.x *= 0.78;

                    // Jump
                    if (miniKeys.jump && canJump) {
                        playerSprite.vel.y = -11;
                        canJump           = false;
                        miniKeys.jump     = false;
                    }

                    // Clamp to canvas edges
                    if (playerSprite.x < 14)            { playerSprite.x = 14;            playerSprite.vel.x = 0; }
                    if (playerSprite.x > CANVAS_W - 14) { playerSprite.x = CANVAS_W - 14; playerSprite.vel.x = 0; }

                    // Safety respawn
                    if (playerSprite.y > CANVAS_H + 40) {
                        playerSprite.x     = CANVAS_W / 2;
                        playerSprite.y     = CANVAS_H - PLAT_H - 22;
                        playerSprite.vel.x = 0;
                        playerSprite.vel.y = 0;
                    }

                    // Soft white glow under the player
                    p.push();
                    p.noStroke();
                    for (let r = 38; r > 0; r -= 6) {
                        p.fill(255, 255, 255, (r / 38) * 18);
                        p.circle(playerSprite.x, playerSprite.y, r * 2);
                    }
                    p.pop();
                }

                p.allSprites.draw();
            };
        };

        const inst = new p5(sketch);
        return { destroy() { inst.remove(); } };
    }

    onDestroy(() => {
        window.removeEventListener('keydown', onKeyDown);
        window.removeEventListener('keyup',   onKeyUp);
        window.removeEventListener('blur',    onBlur);
    });
</script>

<div class="title-screen">

    {#if $gameCompleted}

        <!-- ── NG+ sparkle layer ── -->
        <div class="sparkfield" aria-hidden="true">
            {#each sparks as s}
                <span
                    class="spark"
                    style="
                        left: {s.x}%;
                        top: {s.y}%;
                        width: {s.size}px;
                        height: {s.size}px;
                        background: {s.color};
                        box-shadow: 0 0 {s.size * 2}px {s.color};
                        animation-duration: {s.duration}s;
                        animation-delay: {s.delay}s;
                    "
                ></span>
            {/each}
        </div>

        <!-- ── NG+ home screen ── -->
        <div class="content">
            <h1 class="rainbow-title">The Full Hue</h1>
            <p class="ng-lead">you've brought all the color back.</p>
            <p class="ng-body">
                go through the world again, now in full color and without sorrows.<br>
                take your time. view the scenery. learn about your hues.
            </p>
            <button on:click={startGame}>go again</button>
        </div>

    {:else if showControls}

        <!-- ── Controls screen ── -->
        <div class="content controls-content">
            <h2>how to play</h2>
            <p class="ctrl-sub">a short guide before your journey begins</p>

            <div class="key-table">
                <div class="key-row">
                    <div class="keys">
                        <span class="key">←</span>
                        <span class="key">→</span>
                        <span class="or">or</span>
                        <span class="key">A</span>
                        <span class="key">D</span>
                    </div>
                    <span class="dot">·</span>
                    <span class="key-desc">move left / right</span>
                </div>
                <div class="key-row">
                    <div class="keys">
                        <span class="key">↑</span>
                        <span class="or">or</span>
                        <span class="key">W</span>
                        <span class="or">or</span>
                        <span class="key wide">SPACE</span>
                    </div>
                    <span class="dot">·</span>
                    <span class="key-desc">jump</span>
                </div>
                <div class="key-row">
                    <div class="keys">
                        <span class="key">E</span>
                    </div>
                    <span class="dot">·</span>
                    <span class="key-desc">open level select</span>
                </div>
            </div>

            <p class="try-label">try it out ↓</p>
            <div class="mini-canvas-wrap" use:initMiniCanvas></div>

            <button on:click={goReady}>i'm ready →</button>
        </div>

    {:else}

        <!-- ── Original home screen ── -->
        <div class="content">
            <h1>The Full Hue</h1>
            <p class="tagline">Bring back your color</p>
            <button on:click={startGame}>begin</button>
        </div>

    {/if}

</div>

<style>
    .title-screen {
        width: 800px;
        height: 450px;
        margin: 0 auto;
        position: relative;
        overflow: hidden;
        background: #111;
    }

    .content {
        position: absolute;
        inset: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 12px;
        color: white;
        padding: 0 80px;
    }

    /* ── shared heading ── */
    h1 {
        font-family: 'Courier New', Courier, monospace;
        font-size: 64px;
        font-weight: 400;
        margin: 0;
        text-shadow: 0 2px 12px rgba(0,0,0,0.7);
    }

    /* ── original tagline ── */
    .tagline {
        font-family: 'Courier New', Courier, monospace;
        font-size: 22px;
        opacity: 0.8;
        margin: 0;
    }

    /* ── NG+ rainbow title ── */
    .rainbow-title {
        background: linear-gradient(
            90deg,
            #FF4136, #FF851B, #FFDC00, #2ECC40,
            #0074D9, #B10DC9, #FF69B4, #FF4136
        );
        background-size: 200% auto;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        animation: shimmer 4s linear infinite;
    }

    @keyframes shimmer {
        from { background-position: 0% center; }
        to   { background-position: 200% center; }
    }

    /* ── NG+ text ── */
    .ng-lead {
        font-family: 'Courier New', Courier, monospace;
        font-size: 18px;
        color: rgba(255, 255, 255, 0.75);
        margin: 4px 0 0;
        text-align: center;
    }

    .ng-body {
        font-family: 'Courier New', Courier, monospace;
        font-size: 14px;
        color: rgba(255, 255, 255, 0.45);
        line-height: 1.75;
        margin: 0;
        text-align: center;
    }

    /* ── shared button ── */
    button {
        margin-top: 20px;
        padding: 12px 40px;
        font-family: 'Courier New', Courier, monospace;
        font-size: 22px;
        background: rgba(255, 255, 255, 0.15);
        color: white;
        border: 1px solid rgba(255, 255, 255, 0.4);
        border-radius: 30px;
        cursor: pointer;
        transition: background 0.2s;
    }

    button:hover { background: rgba(255, 255, 255, 0.3); }

    /* ── NG+ sparkle layer ── */
    .sparkfield {
        position: absolute;
        inset: 0;
        pointer-events: none;
    }

    .spark {
        position: absolute;
        border-radius: 50%;
        animation: sparkle linear infinite;
    }

    @keyframes sparkle {
        0%, 100% { opacity: 1;    transform: scale(1);   }
        50%       { opacity: 0.05; transform: scale(0.4); }
    }

    /* ── controls screen ── */
    .controls-content {
        gap: 9px;
        padding: 0 60px;
    }

    h2 {
        font-family: 'Courier New', Courier, monospace;
        font-size: 28px;
        font-weight: 400;
        margin: 0;
    }

    .ctrl-sub {
        font-family: 'Courier New', Courier, monospace;
        font-size: 13px;
        color: rgba(255, 255, 255, 0.38);
        margin: 0;
    }

    .key-table {
        display: flex;
        flex-direction: column;
        gap: 7px;
        margin: 4px 0 2px;
    }

    .key-row {
        display: flex;
        align-items: center;
        gap: 14px;
    }

    .keys {
        display: flex;
        align-items: center;
        gap: 4px;
        min-width: 218px;
    }

    .key {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 28px;
        height: 24px;
        padding: 0 7px;
        background: rgba(255, 255, 255, 0.09);
        border: 1px solid rgba(255, 255, 255, 0.28);
        border-bottom: 2px solid rgba(255, 255, 255, 0.28);
        border-radius: 5px;
        font-family: 'Courier New', Courier, monospace;
        font-size: 11px;
        color: rgba(255, 255, 255, 0.82);
        box-sizing: border-box;
    }

    .key.wide {
        min-width: 62px;
        letter-spacing: 0.04em;
    }

    .or {
        font-family: 'Courier New', Courier, monospace;
        font-size: 10px;
        color: rgba(255, 255, 255, 0.22);
        padding: 0 1px;
    }

    .dot {
        color: rgba(255, 255, 255, 0.18);
        font-size: 16px;
        line-height: 1;
    }

    .key-desc {
        font-family: 'Courier New', Courier, monospace;
        font-size: 13px;
        color: rgba(255, 255, 255, 0.58);
    }

    .try-label {
        font-family: 'Courier New', Courier, monospace;
        font-size: 11px;
        color: rgba(255, 255, 255, 0.22);
        margin: 0;
        text-align: center;
    }

    .mini-canvas-wrap {
        width: 680px;
        height: 124px;
        border-radius: 8px;
        overflow: hidden;
        border: 1px solid rgba(255, 255, 255, 0.07);
    }

    /* controls-content button gets less top margin */
    .controls-content button {
        margin-top: 6px;
        font-size: 18px;
        padding: 10px 36px;
    }
</style>
