<script lang="ts">
    import { gameSession } from "$lib/stores/gameSession.svelte";
    import * as m from "$lib/paraglide/messages";
    import { KvGameLogo } from "$lib/components/kuldvillak/ui";

    // Derived state
    let session = $derived(gameSession.state);
    let currentRound = $derived(gameSession.currentRound);
    let questionData = $derived(gameSession.currentQuestionData);

    // Get round variant for logo display
    let roundVariant = $derived.by(() => {
        const roundIndex = session?.currentRoundIndex ?? 0;
        if (roundIndex === 0) return "villak" as const;
        if (roundIndex === 1) return "topeltvillak" as const;
        return "hobevillak" as const;
    });

    // Animation state for question expand
    let animationPhase = $state<"waiting" | "expanding" | "shown" | "none">(
        "none",
    );
    let finalAnimPhase = $state<"waiting" | "expanding" | "shown" | "none">(
        "none",
    );
    let ddQuestionAnimPhase = $state<
        "waiting" | "expanding" | "shown" | "none"
    >("none");
    let ddRevealAnimPhase = $state<"waiting" | "spinning" | "shown" | "none">(
        "none",
    );
    let isDailyDoubleQuestion = $state(false);
    let prevPhase = $state<string | null>(null);

    // Intro category animation state (used for both regular and final round)
    // Timing: 500ms dissolve ease-out, 1500ms shown, 500ms push left
    let introAnimPhase = $state<
        "villak" | "fade-in" | "shown" | "push-out" | "none"
    >("none");
    let prevIntroCatIndex = $state(-1);
    let finalCategoryAnimStarted = $state(false);

    // Game board reveal animation state
    let boardRevealPhase = $state<"hidden" | "revealing" | "revealed">(
        "hidden",
    );
    let revealedPrices = $state<Set<string>>(new Set());
    let prevBoardPhase = $state<string | null>(null);

    // Calculate starting position for the expanding overlay using actual DOM element
    let questionGridEl = $state<HTMLElement | null>(null);
    let startPosition = $derived(() => {
        if (!session?.currentQuestion || !currentRound || !questionGridEl) {
            return { left: 50, top: 50, width: 16, height: 20 };
        }
        const { categoryIndex, questionIndex } = session.currentQuestion;
        const card = questionGridEl.querySelector(
            `[data-cat="${categoryIndex}"][data-q="${questionIndex}"]`,
        ) as HTMLElement | null;

        if (!card) {
            return { left: 50, top: 50, width: 16, height: 20 };
        }

        const cardRect = card.getBoundingClientRect();
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;

        // Calculate center position relative to viewport
        const left =
            ((cardRect.left + cardRect.width / 2) / viewportWidth) * 100;
        const top =
            ((cardRect.top + cardRect.height / 2) / viewportHeight) * 100;
        const width = (cardRect.width / viewportWidth) * 100;
        const height = (cardRect.height / viewportHeight) * 100;

        return { left, top, width, height };
    });

    // Watch for phase changes to trigger animation
    $effect(() => {
        const currentPhase = session?.phase;

        if (currentPhase === "question" && prevPhase !== "question") {
            // Check if coming from daily-double phase
            if (prevPhase === "daily-double") {
                isDailyDoubleQuestion = true;
                ddQuestionAnimPhase = "waiting";
                setTimeout(() => {
                    ddQuestionAnimPhase = "expanding";
                }, 1000);
                setTimeout(() => {
                    ddQuestionAnimPhase = "shown";
                }, 2000);
            } else {
                isDailyDoubleQuestion = false;
                animationPhase = "waiting";
                setTimeout(() => {
                    animationPhase = "expanding";
                }, 1000);
                setTimeout(() => {
                    animationPhase = "shown";
                }, 2000);
            }
        } else if (currentPhase !== "question") {
            animationPhase = "none";
            ddQuestionAnimPhase = "none";
            if (currentPhase !== "daily-double") {
                isDailyDoubleQuestion = false;
            }
        }

        // Final question animation - wait 1s on Kuldvillak, then expand from center
        if (
            currentPhase === "final-question" &&
            prevPhase !== "final-question"
        ) {
            finalAnimPhase = "waiting";
            setTimeout(() => {
                finalAnimPhase = "expanding";
            }, 1000); // Wait 1 second before expanding
            setTimeout(() => {
                finalAnimPhase = "shown";
            }, 2000); // 1s wait + 1s expand
        } else if (currentPhase !== "final-question") {
            finalAnimPhase = "none";
        }

        // Daily Double reveal animation - wait 1s, then spin in from center
        if (currentPhase === "daily-double" && prevPhase !== "daily-double") {
            ddRevealAnimPhase = "waiting";
            setTimeout(() => {
                ddRevealAnimPhase = "spinning";
            }, 1000); // Wait 1 second before spinning
            setTimeout(() => {
                ddRevealAnimPhase = "shown";
            }, 2000); // 1s wait + 1s spin
        } else if (currentPhase !== "daily-double") {
            ddRevealAnimPhase = "none";
        }

        prevPhase = currentPhase ?? null;
    });

    // Watch for intro category changes to trigger animation sequence
    // Timing: 3s initial delay (first category only), then 500ms on villak, 500ms dissolve ease-out, 1500ms shown, 500ms push left linear
    $effect(() => {
        const catIndex = session?.introCategoryIndex ?? -1;
        const isFirstCategory = catIndex === 0 && prevIntroCatIndex === -1;

        if (
            session?.phase === "intro-categories" &&
            catIndex >= 0 &&
            catIndex !== prevIntroCatIndex
        ) {
            // Initial 3 second delay for first category only
            const initialDelay = isFirstCategory ? 3000 : 0;

            // Start animation sequence for new category
            setTimeout(() => {
                introAnimPhase = "villak"; // Stay on Villak for 500ms
            }, initialDelay);
            setTimeout(() => {
                introAnimPhase = "fade-in"; // 500ms dissolve
            }, initialDelay + 500); // Start fade after 500ms on villak
            setTimeout(() => {
                introAnimPhase = "shown";
            }, initialDelay + 1000); // 500ms villak + 500ms fade
            setTimeout(() => {
                introAnimPhase = "push-out"; // 500ms push left
            }, initialDelay + 2500); // 500ms villak + 500ms fade + 1500ms shown
            setTimeout(() => {
                introAnimPhase = "none";
                gameSession.nextIntroCategory();
            }, initialDelay + 3000); // Total: 500ms + 500ms + 1500ms + 500ms = 3000ms
        } else if (
            session?.phase !== "intro-categories" &&
            session?.phase !== "final-category"
        ) {
            introAnimPhase = "none";
        }

        prevIntroCatIndex = catIndex;
    });

    // Watch for board phase to trigger staggered price reveal (only once per round)
    $effect(() => {
        const currentPhase = session?.phase;
        const alreadyRevealed = session?.boardRevealed ?? false;

        if (
            currentPhase === "board" &&
            prevBoardPhase !== "board" &&
            !alreadyRevealed
        ) {
            // First time entering board - do the reveal animation
            boardRevealPhase = "revealing";
            revealedPrices = new Set();

            // Custom reveal order: [ci, qi, order] - order determines when cell appears
            // Grid: 6 columns (C1-C6) × 5 rows (R1-R5)
            const revealOrder: [number, number, number][] = [
                // Row 1 (qi=0): 01  02  15  11  13  08
                [0, 0, 1],
                [1, 0, 2],
                [2, 0, 15],
                [3, 0, 11],
                [4, 0, 13],
                [5, 0, 8],
                // Row 2 (qi=1): 25  04  28  24  05  07
                [0, 1, 25],
                [1, 1, 4],
                [2, 1, 28],
                [3, 1, 24],
                [4, 1, 5],
                [5, 1, 7],
                // Row 3 (qi=2): 20  16  09  10  18  26
                [0, 2, 20],
                [1, 2, 16],
                [2, 2, 9],
                [3, 2, 10],
                [4, 2, 18],
                [5, 2, 26],
                // Row 4 (qi=3): 12  27  06  23  21  30
                [0, 3, 12],
                [1, 3, 27],
                [2, 3, 6],
                [3, 3, 23],
                [4, 3, 21],
                [5, 3, 30],
                // Row 5 (qi=4): 19  22  03  14  17  29
                [0, 4, 19],
                [1, 4, 22],
                [2, 4, 3],
                [3, 4, 14],
                [4, 4, 17],
                [5, 4, 29],
            ];

            // Sort by order and schedule reveals
            const sorted = [...revealOrder].sort((a, b) => a[2] - b[2]);
            sorted.forEach(([ci, qi, _order], idx) => {
                const key = `${ci}-${qi}`;
                setTimeout(() => {
                    revealedPrices = new Set([...revealedPrices, key]);
                }, idx * 50); // 50ms between each cell
            });

            setTimeout(
                () => {
                    boardRevealPhase = "revealed";
                    gameSession.markBoardRevealed(); // Mark as revealed so it won't animate again
                },
                sorted.length * 50 + 100,
            );
        } else if (currentPhase === "board" && alreadyRevealed) {
            // Already revealed - show all prices immediately
            boardRevealPhase = "revealed";
        }

        prevBoardPhase = currentPhase ?? null;
    });

    // Watch for final category phase to trigger the same animation
    $effect(() => {
        if (session?.phase === "final-category" && !finalCategoryAnimStarted) {
            finalCategoryAnimStarted = true;
            // Same timing as regular category intro
            introAnimPhase = "villak";
            setTimeout(() => {
                introAnimPhase = "fade-in";
            }, 500);
            setTimeout(() => {
                introAnimPhase = "shown";
            }, 1000);
            setTimeout(() => {
                introAnimPhase = "push-out";
            }, 2500);
            setTimeout(() => {
                introAnimPhase = "none";
                gameSession.finishFinalCategoryReveal();
            }, 3000);
        } else if (session?.phase !== "final-category") {
            finalCategoryAnimStarted = false;
        }
    });

    // Helper to check if a price cell should be visible
    function isPriceRevealed(ci: number, qi: number): boolean {
        if (boardRevealPhase === "revealed") return true;
        return revealedPrices.has(`${ci}-${qi}`);
    }
</script>

{#if session}
    <div
        class="h-screen w-screen bg-kv-black flex flex-col overflow-hidden relative"
    >
        {#if session.phase === "intro"}
            <!-- Home Screen with grid background - show Villak if categories introduced -->
            <div
                class="flex-1 flex items-center justify-center intro-grid-bg"
                class:animated={!session.categoriesIntroduced}
            >
                {#if session.categoriesIntroduced}
                    <KvGameLogo
                        variant={roundVariant}
                        class="w-[60vw] max-w-[885px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                    />
                {:else}
                    <KvGameLogo
                        variant="kuldvillak"
                        class="w-[80vw] max-w-[1536px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                    />
                {/if}
            </div>
        {:else if session.phase === "intro-categories"}
            <!-- Category Introduction Animation -->
            {@const currentCat =
                currentRound?.categories[session.introCategoryIndex]}
            <div class="flex-1 relative overflow-hidden">
                <!-- VILLAK background - always visible as base layer -->
                <div
                    class="absolute inset-0 flex items-center justify-center intro-grid-bg"
                >
                    <KvGameLogo
                        variant={roundVariant}
                        class="w-[60vw] max-w-[885px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                    />
                </div>

                <!-- Category reveal - fades in on TOP of Villak, then pushed out -->
                {#if currentCat}
                    <div
                        class="absolute inset-0 bg-kv-black p-8 intro-category {introAnimPhase}"
                    >
                        <div
                            class="w-full h-full flex items-center justify-center bg-kv-blue overflow-hidden p-2"
                        >
                            <div
                                class="font-kv-body text-kv-white text-[clamp(48px,12vw,192px)] uppercase text-center leading-normal kv-shadow-text"
                            >
                                {currentCat.name}
                            </div>
                        </div>
                    </div>
                {/if}

                <!-- Villak pusher - slides in from right to push category out -->
                <div
                    class="absolute inset-0 flex items-center justify-center intro-grid-bg intro-pusher {introAnimPhase}"
                >
                    <KvGameLogo
                        variant={roundVariant}
                        class="w-[60vw] max-w-[885px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                    />
                </div>
            </div>
        {:else if session.phase === "board" || session.phase === "question"}
            <!-- Game Board - Full screen responsive grid -->
            <div class="flex-1 flex flex-col p-4 lg:p-8 gap-4 h-full min-h-0">
                <!-- Category Headers - show round name until board is revealed -->
                <div
                    class="grid gap-2 lg:gap-4 shrink-0"
                    style="grid-template-columns: repeat({currentRound
                        ?.categories.length ?? 6}, 1fr);"
                >
                    {#each currentRound?.categories ?? [] as cat}
                        {@const logoVariant =
                            session.currentRoundIndex === 0
                                ? "villak"
                                : "topeltvillak"}
                        <div
                            class="bg-kv-blue font-kv-body text-kv-white text-center uppercase px-2 py-4 lg:px-4 lg:py-6 text-[clamp(12px,2.5vw,48px)] leading-tight flex items-center justify-center kv-shadow-text overflow-hidden relative category-header"
                        >
                            <div
                                class="category-content {session.boardRevealed
                                    ? 'show-name'
                                    : 'show-logo'}"
                            >
                                <div class="category-logo">
                                    <KvGameLogo
                                        variant={logoVariant}
                                        class="h-full w-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                                    />
                                </div>
                                <div class="category-name">
                                    {cat.name || "???"}
                                </div>
                            </div>
                        </div>
                    {/each}
                </div>

                <!-- Question Grid - fills remaining space -->
                <div
                    bind:this={questionGridEl}
                    class="flex-1 grid gap-2 lg:gap-4 min-h-0"
                    style="grid-template-columns: repeat({currentRound
                        ?.categories.length ??
                        6}, 1fr); grid-template-rows: repeat({currentRound
                        ?.categories[0]?.questions.length ?? 5}, 1fr);"
                >
                    {#each currentRound?.categories ?? [] as cat, ci}
                        {#each cat.questions as q, qi}
                            <div
                                class="bg-kv-blue flex items-center justify-center question-card overflow-hidden"
                                style="grid-column: {ci + 1}; grid-row: {qi +
                                    1};"
                                data-cat={ci}
                                data-q={qi}
                            >
                                <span
                                    class="font-kv-price text-kv-yellow text-[clamp(24px,6vw,128px)] kv-shadow-price price-reveal
                                        {q.isRevealed ? 'opacity-0' : ''}
                                        {isPriceRevealed(ci, qi)
                                        ? 'revealed'
                                        : ''}"
                                >
                                    {q.points}<span class="text-[0.75em]"
                                        >€</span
                                    >
                                </span>
                            </div>
                        {/each}
                    {/each}
                </div>
            </div>

            <!-- Question Overlay - Full screen over board (normal questions) -->
            {#if session.phase === "question" && questionData && animationPhase !== "none" && !isDailyDoubleQuestion}
                {@const pos = startPosition()}
                <div
                    class="absolute bg-kv-black flex flex-col expand-overlay {animationPhase}"
                    style="--start-left: {pos.left}%; --start-top: {pos.top}%; --start-width: {pos.width}%; --start-height: {pos.height}%;"
                >
                    <!-- Players row - top -->
                    <div
                        class="grid gap-2 lg:gap-4 shrink-0"
                        style="grid-template-columns: repeat({session.teams
                            .length}, 1fr);"
                    >
                        {#each session.teams as team}
                            {@const isAnswering =
                                session.activeTeamId === team.id}
                            <div
                                class="bg-kv-blue px-2 py-4 lg:px-4 lg:py-6 flex flex-col items-center justify-between overflow-hidden font-kv-body text-kv-white uppercase text-center border-8 border-transparent {isAnswering
                                    ? 'team-answering'
                                    : ''}"
                            >
                                <span
                                    class="text-[clamp(24px,2.5vw,36px)] kv-shadow-text {team.score <
                                    0
                                        ? 'text-kv-red'
                                        : ''}">{team.score}€</span
                                >
                                <span
                                    class="text-[clamp(24px,2.5vw,36px)] kv-shadow-text"
                                    >{team.name}</span
                                >
                            </div>
                        {/each}
                    </div>

                    <!-- Question area - fills remaining space -->
                    <div
                        class="flex-1 flex items-center justify-center p-4 overflow-hidden bg-kv-blue"
                    >
                        {#if questionData.question.imageUrl}
                            <!-- Image question - show only image -->
                            <div
                                class="w-full h-full flex items-center justify-center"
                            >
                                <img
                                    src={questionData.question.imageUrl}
                                    alt="Question"
                                    class="w-full h-full object-contain"
                                />
                            </div>
                        {:else}
                            <!-- Text question -->
                            <div
                                class="font-kv-question text-center text-[clamp(48px,6vw,96px)] leading-[1] uppercase"
                                style="transform: scaleX(0.9225);"
                            >
                                {#if session.showAnswer}
                                    <div class="text-kv-yellow kv-shadow-text">
                                        {questionData.question.answer}
                                    </div>
                                {:else}
                                    <div class="text-kv-white kv-shadow-text">
                                        {questionData.question.question}
                                    </div>
                                {/if}
                            </div>
                        {/if}
                    </div>
                </div>
            {/if}
            <!-- Daily Double Question Overlay - Hõbevillak background with center expand -->
            {#if session.phase === "question" && questionData && isDailyDoubleQuestion}
                <!-- Hõbevillak background -->
                <div
                    class="absolute inset-0 flex flex-col items-center justify-center intro-grid-bg"
                >
                    <KvGameLogo
                        variant="hobevillak"
                        class="w-[60vw] max-w-[885px] h-auto drop-shadow-[0_0_20px_rgba(192,192,192,0.8)]"
                    />
                </div>
                <!-- Question overlay expanding from center -->
                {#if ddQuestionAnimPhase !== "none"}
                    <div
                        class="absolute bg-kv-black flex flex-col expand-overlay-center {ddQuestionAnimPhase}"
                    >
                        <!-- Players row - top -->
                        <div
                            class="grid gap-2 lg:gap-4 shrink-0"
                            style="grid-template-columns: repeat({session.teams
                                .length}, 1fr);"
                        >
                            {#each session.teams as team}
                                {@const isAnswering =
                                    session.activeTeamId === team.id}
                                <div
                                    class="bg-kv-blue px-2 py-4 lg:px-4 lg:py-6 flex flex-col items-center justify-between overflow-hidden font-kv-body text-kv-white uppercase text-center border-8 {isAnswering
                                        ? 'border-kv-yellow'
                                        : 'border-transparent'}"
                                >
                                    <span
                                        class="text-[clamp(24px,2.5vw,36px)] kv-shadow-text {team.score <
                                        0
                                            ? 'text-kv-red'
                                            : ''}">{team.score}€</span
                                    >
                                    <span
                                        class="text-[clamp(24px,2.5vw,36px)] kv-shadow-text"
                                        >{team.name}</span
                                    >
                                </div>
                            {/each}
                        </div>

                        <!-- Question area - fills remaining space -->
                        <div
                            class="flex-1 flex items-center justify-center p-4 overflow-hidden bg-kv-blue"
                        >
                            {#if questionData.question.imageUrl}
                                <!-- Image question - show only image -->
                                <div
                                    class="w-full h-full flex items-center justify-center"
                                >
                                    <img
                                        src={questionData.question.imageUrl}
                                        alt="Question"
                                        class="w-full h-full object-contain"
                                    />
                                </div>
                            {:else}
                                <!-- Text question -->
                                <div
                                    class="font-kv-question text-center text-[clamp(48px,6vw,96px)] leading-[1] uppercase"
                                    style="transform: scaleX(0.9225);"
                                >
                                    {#if session.showAnswer}
                                        <div
                                            class="text-kv-yellow kv-shadow-text"
                                        >
                                            {questionData.question.answer}
                                        </div>
                                    {:else}
                                        <div
                                            class="text-kv-white kv-shadow-text"
                                        >
                                            {questionData.question.question}
                                        </div>
                                    {/if}
                                </div>
                            {/if}
                        </div>
                    </div>
                {/if}
            {/if}
        {:else if session.phase === "daily-double"}
            <!-- Daily Double (Hõbevillak) - Game board background with spinning overlay -->
            <!-- Game Board Background (same as board phase) -->
            <div class="flex-1 flex flex-col p-4 lg:p-8 gap-4 h-full min-h-0">
                <!-- Category Headers -->
                <div
                    class="grid gap-2 lg:gap-4 shrink-0"
                    style="grid-template-columns: repeat({currentRound
                        ?.categories.length ?? 6}, 1fr);"
                >
                    {#each currentRound?.categories ?? [] as cat}
                        <div
                            class="bg-kv-blue font-kv-body text-kv-white text-center uppercase px-2 py-4 lg:px-4 lg:py-6 text-[clamp(12px,2.5vw,48px)] leading-tight flex items-center justify-center kv-shadow-text overflow-hidden"
                        >
                            {cat.name || "???"}
                        </div>
                    {/each}
                </div>

                <!-- Question Grid -->
                <div
                    class="flex-1 grid gap-2 lg:gap-4 min-h-0"
                    style="grid-template-columns: repeat({currentRound
                        ?.categories.length ??
                        6}, 1fr); grid-template-rows: repeat({currentRound
                        ?.categories[0]?.questions.length ?? 5}, 1fr);"
                >
                    {#each currentRound?.categories ?? [] as cat, ci}
                        {#each cat.questions as q, qi}
                            <div
                                class="bg-kv-blue flex items-center justify-center question-card overflow-hidden"
                                style="grid-column: {ci + 1}; grid-row: {qi +
                                    1};"
                            >
                                <span
                                    class="font-kv-price text-kv-yellow text-[clamp(24px,6vw,128px)] kv-shadow-price
                                        {q.isRevealed ? 'opacity-0' : ''}"
                                >
                                    {q.points}<span class="text-[0.75em]"
                                        >€</span
                                    >
                                </span>
                            </div>
                        {/each}
                    {/each}
                </div>
            </div>

            <!-- Hõbevillak overlay spinning in from center -->
            {#if ddRevealAnimPhase !== "none"}
                <div
                    class="absolute inset-0 flex flex-col items-center justify-center intro-grid-bg dd-spin-overlay {ddRevealAnimPhase}"
                >
                    <KvGameLogo
                        variant="hobevillak"
                        class="w-[60vw] max-w-[885px] h-auto drop-shadow-[0_0_20px_rgba(192,192,192,0.8)]"
                    />
                    {#if session.dailyDoubleWager}
                        <div
                            class="font-kv-body text-kv-white text-[clamp(32px,4vw,64px)] uppercase kv-shadow-text mt-8"
                        >
                            {m.kv_play_wager()}: {session.dailyDoubleWager}€
                        </div>
                    {/if}
                </div>
            {/if}
        {:else if session.phase === "final-intro"}
            <!-- Final Round Intro - KULDVILLAK screen -->
            <div class="flex-1 flex items-center justify-center intro-grid-bg">
                <KvGameLogo
                    variant="kuldvillak"
                    class="w-[80vw] max-w-[1536px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                />
            </div>
        {:else if session.phase === "final-category"}
            <!-- Final Round Category - Animated reveal -->
            <div class="flex-1 relative overflow-hidden">
                <!-- KULDVILLAK background - always visible as base layer -->
                <div
                    class="absolute inset-0 flex items-center justify-center intro-grid-bg"
                >
                    <KvGameLogo
                        variant="kuldvillak"
                        class="w-[80vw] max-w-[1536px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                    />
                </div>

                <!-- Final category reveal - fades in on TOP of KULDVILLAK, then pushed out -->
                <div
                    class="absolute inset-0 bg-kv-black p-8 intro-category {introAnimPhase}"
                >
                    <div
                        class="w-full h-full flex items-center justify-center bg-kv-blue overflow-hidden p-2"
                    >
                        <div
                            class="font-kv-body text-kv-white text-[clamp(48px,12vw,192px)] uppercase text-center leading-normal kv-shadow-text"
                        >
                            {session.finalRound?.category || "???"}
                        </div>
                    </div>
                </div>

                <!-- KULDVILLAK pusher - slides in from right to push category out -->
                <div
                    class="absolute inset-0 flex items-center justify-center intro-grid-bg intro-pusher {introAnimPhase}"
                >
                    <KvGameLogo
                        variant="kuldvillak"
                        class="w-[80vw] max-w-[1536px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                    />
                </div>
            </div>
        {:else if session.phase === "final-question"}
            <!-- Final Round Question - Kuldvillak background with question overlay -->
            <div class="flex-1 flex items-center justify-center intro-grid-bg">
                <KvGameLogo
                    variant="kuldvillak"
                    class="w-[80vw] max-w-[1536px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                />
            </div>
            <!-- Question overlay on top -->
            {#if finalAnimPhase !== "none"}
                <div
                    class="absolute bg-kv-black flex flex-col expand-overlay-center {finalAnimPhase}"
                >
                    <!-- Players row - top -->
                    <div
                        class="grid gap-2 lg:gap-4 shrink-0"
                        style="grid-template-columns: repeat({session.teams
                            .length}, 1fr);"
                    >
                        {#each session.teams as team}
                            {@const isActive = session.activeTeamId === team.id}
                            <div
                                class="bg-kv-blue px-2 py-4 lg:px-4 lg:py-6 flex flex-col items-center justify-between overflow-hidden font-kv-body text-kv-white uppercase text-center border-8 {isActive
                                    ? 'border-kv-yellow'
                                    : 'border-transparent'}"
                            >
                                <span
                                    class="text-[clamp(24px,2.5vw,36px)] kv-shadow-text {team.score <
                                    0
                                        ? 'text-kv-red'
                                        : ''}">{team.score}€</span
                                >
                                <span
                                    class="text-[clamp(24px,2.5vw,36px)] kv-shadow-text"
                                    >{team.name}</span
                                >
                            </div>
                        {/each}
                    </div>

                    <!-- Question area - fills remaining space -->
                    <div
                        class="flex-1 flex items-center justify-center p-4 overflow-hidden bg-kv-blue"
                    >
                        <div
                            class="font-kv-question text-center text-[clamp(48px,6vw,96px)] leading-[1] uppercase"
                            style="transform: scaleX(0.9225);"
                        >
                            {#if session.showAnswer}
                                <div class="text-kv-yellow kv-shadow-text">
                                    {session.finalRound?.answer}
                                </div>
                            {:else}
                                <div class="text-kv-white kv-shadow-text">
                                    {session.finalRound?.question}
                                </div>
                            {/if}
                        </div>
                    </div>
                </div>
            {/if}
        {:else if session.phase === "final-scores"}
            <!-- Final Scores Display - Flexible grid layout -->
            {@const sorted = gameSession.sortedTeams}
            {@const count = sorted.length}
            {@const topRowCount = count <= 3 ? count : 3}
            {@const bottomRowCount = count > 3 ? count - 3 : 0}
            {@const topRow = sorted.slice(0, topRowCount)}
            {@const bottomRow = sorted.slice(topRowCount)}
            <div class="flex-1 flex flex-col bg-kv-black p-8 gap-4">
                <!-- Top row -->
                <div
                    class="flex-1 grid gap-4"
                    style="grid-template-columns: repeat({topRowCount}, 1fr);"
                >
                    {#each topRow as team, i}
                        <div
                            class="bg-kv-blue flex flex-col items-center justify-center gap-4 p-4"
                        >
                            <span
                                class="font-kv-body text-[clamp(36px,6vw,72px)] uppercase kv-shadow-text {team.score <
                                0
                                    ? 'text-kv-red'
                                    : 'text-kv-white'}"
                            >
                                {team.score}€
                            </span>
                            <span
                                class="font-kv-body text-[clamp(24px,4vw,48px)] text-kv-white uppercase kv-shadow-text"
                            >
                                {team.name}
                            </span>
                            <span
                                class="font-kv-body text-[clamp(24px,4vw,48px)] text-kv-white uppercase kv-shadow-text"
                            >
                                #{i + 1}
                            </span>
                        </div>
                    {/each}
                </div>
                <!-- Bottom row (if more than 3 players) -->
                {#if bottomRowCount > 0}
                    <div
                        class="flex-1 grid gap-4"
                        style="grid-template-columns: repeat({bottomRowCount}, 1fr);"
                    >
                        {#each bottomRow as team, i}
                            <div
                                class="bg-kv-blue flex flex-col items-center justify-center gap-4 p-4"
                            >
                                <span
                                    class="font-kv-body text-[clamp(36px,6vw,72px)] uppercase kv-shadow-text {team.score <
                                    0
                                        ? 'text-kv-red'
                                        : 'text-kv-white'}"
                                >
                                    {team.score}€
                                </span>
                                <span
                                    class="font-kv-body text-[clamp(24px,4vw,48px)] text-kv-white uppercase kv-shadow-text"
                                >
                                    {team.name}
                                </span>
                                <span
                                    class="font-kv-body text-[clamp(24px,4vw,48px)] text-kv-white uppercase kv-shadow-text"
                                >
                                    #{i + topRowCount + 1}
                                </span>
                            </div>
                        {/each}
                    </div>
                {/if}
            </div>
        {:else if session.phase === "finished"}
            <!-- Game Over - Back to Kuldvillak screen -->
            <div
                class="flex-1 flex items-center justify-center intro-grid-bg animated"
            >
                <KvGameLogo
                    variant="kuldvillak"
                    class="w-[80vw] max-w-[1536px] h-auto drop-shadow-[6px_6px_4px_rgba(0,0,0,0.5)]"
                />
            </div>
        {/if}
    </div>
{/if}

<style>
    /* Intro grid background - flat scrolling pattern */
    .intro-grid-bg {
        background-color: var(--kv-blue);
        background-image: linear-gradient(#001a45 2px, transparent 2px),
            linear-gradient(90deg, #001a45 2px, transparent 2px);
        background-size: 60px 60px;
    }

    .intro-grid-bg.animated {
        animation: grid-scroll 2s linear infinite;
    }

    @keyframes grid-scroll {
        from {
            background-position: 0 0;
        }
        to {
            background-position: -60px 0;
        }
    }

    /* Intro category animation - 500ms dissolve ease-out */
    .intro-category {
        opacity: 0;
        z-index: 5;
    }
    .intro-category.villak {
        opacity: 0;
    }
    .intro-category.fade-in {
        animation: fade-in 500ms ease-out forwards;
    }
    .intro-category.shown {
        opacity: 1;
    }
    .intro-category.push-out {
        opacity: 1;
        animation: slide-out-left 500ms linear forwards;
    }

    /* Intro pusher - Villak that slides in from right - 500ms linear */
    .intro-pusher {
        transform: translateX(100%);
        z-index: 10;
    }
    .intro-pusher.villak,
    .intro-pusher.fade-in,
    .intro-pusher.shown {
        transform: translateX(100%);
    }
    .intro-pusher.push-out {
        animation: slide-in-from-right 500ms linear forwards;
    }

    @keyframes fade-in {
        from {
            opacity: 0;
        }
        to {
            opacity: 1;
        }
    }

    @keyframes slide-in-from-right {
        from {
            transform: translateX(100%);
        }
        to {
            transform: translateX(0);
        }
    }

    @keyframes slide-out-left {
        from {
            transform: translateX(0);
        }
        to {
            transform: translateX(-100%);
        }
    }

    /* Price reveal animation - instant staggered appearance */
    .price-reveal {
        opacity: 0;
    }
    .price-reveal.revealed {
        opacity: 1;
    }
    .price-reveal.opacity-0 {
        opacity: 0 !important;
    }

    /* Question overlay animation - expand from card position */
    .expand-overlay {
        left: var(--start-left);
        top: var(--start-top);
        width: var(--start-width);
        height: var(--start-height);
        transform: translate(-50%, -50%);
        transform-origin: center center;
        overflow: hidden;
        container-type: size;
        opacity: 0;
        visibility: hidden;
    }
    .expand-overlay.expanding {
        opacity: 1;
        visibility: visible;
        transition:
            left 1s linear,
            top 1s linear,
            width 1s linear,
            height 1s linear,
            transform 1s linear;
    }
    .expand-overlay.expanding,
    .expand-overlay.shown {
        left: 50%;
        top: 50%;
        width: 100%;
        height: 100%;
        transform: translate(-50%, -50%);
        opacity: 1;
        visibility: visible;
    }
    /* Scale all elements proportionally to container */
    .expand-overlay {
        padding: clamp(4px, 3cqh, 32px);
        gap: clamp(4px, 1.5cqh, 16px);
    }
    .expand-overlay .font-kv-question {
        font-size: clamp(12px, 8cqh, 96px);
    }
    .expand-overlay .font-kv-body {
        font-size: clamp(8px, 4cqh, 36px);
    }
    .expand-overlay .grid {
        gap: clamp(2px, 1.5cqh, 16px);
    }
    .expand-overlay .grid span {
        font-size: clamp(8px, 3.5cqh, 36px);
    }
    .expand-overlay .border-8 {
        border-width: clamp(2px, 0.8cqh, 8px);
    }
    .expand-overlay .bg-kv-blue {
        padding: clamp(4px, 1.5cqh, 16px);
    }
    .expand-overlay .px-2 {
        padding-left: clamp(2px, 0.8cqw, 8px);
        padding-right: clamp(2px, 0.8cqw, 8px);
    }
    .expand-overlay .py-4 {
        padding-top: clamp(4px, 1.5cqh, 16px);
        padding-bottom: clamp(4px, 1.5cqh, 16px);
    }

    /* Final question overlay animation - expand from center */
    .expand-overlay-center {
        left: 50%;
        top: 50%;
        width: 10%;
        height: 10%;
        transform: translate(-50%, -50%);
        transform-origin: center center;
        overflow: hidden;
        container-type: size;
        opacity: 0;
        visibility: hidden;
    }
    .expand-overlay-center.waiting {
        opacity: 0;
        visibility: hidden;
    }
    .expand-overlay-center.expanding {
        opacity: 1;
        visibility: visible;
        transition:
            width 1s linear,
            height 1s linear;
        width: 100%;
        height: 100%;
    }
    .expand-overlay-center.shown {
        left: 50%;
        top: 50%;
        width: 100%;
        height: 100%;
        transform: translate(-50%, -50%);
        opacity: 1;
        visibility: visible;
    }
    /* Scale elements for center expand */
    .expand-overlay-center {
        padding: clamp(4px, 3cqh, 32px);
        gap: clamp(4px, 1.5cqh, 16px);
    }
    .expand-overlay-center .font-kv-question {
        font-size: clamp(12px, 8cqh, 96px);
    }
    .expand-overlay-center .font-kv-body {
        font-size: clamp(8px, 4cqh, 36px);
    }
    .expand-overlay-center .grid {
        gap: clamp(2px, 1.5cqh, 16px);
    }
    .expand-overlay-center .grid span {
        font-size: clamp(8px, 3.5cqh, 36px);
    }
    .expand-overlay-center .border-8 {
        border-width: clamp(2px, 0.8cqh, 8px);
    }
    .expand-overlay-center .bg-kv-blue {
        padding: clamp(4px, 1.5cqh, 16px);
    }
    .expand-overlay-center .px-2 {
        padding-left: clamp(2px, 0.8cqw, 8px);
        padding-right: clamp(2px, 0.8cqw, 8px);
    }
    .expand-overlay-center .py-4 {
        padding-top: clamp(4px, 1.5cqh, 16px);
        padding-bottom: clamp(4px, 1.5cqh, 16px);
    }

    /* Daily Double spin overlay - starts flipped and spins while expanding */
    .dd-spin-overlay {
        transform: scale(0.1) rotateY(180deg);
        transform-origin: center center;
        opacity: 0;
        visibility: hidden;
    }
    .dd-spin-overlay.waiting {
        opacity: 0;
        visibility: hidden;
        transform: scale(0.1) rotateY(180deg);
    }
    .dd-spin-overlay.spinning {
        opacity: 1;
        visibility: visible;
        animation: dd-spin-in 1s linear forwards;
    }
    .dd-spin-overlay.shown {
        opacity: 1;
        visibility: visible;
        transform: scale(1) rotateY(0deg);
    }
    @keyframes dd-spin-in {
        0% {
            transform: scale(0.1) rotateY(180deg);
            opacity: 0;
        }
        20% {
            opacity: 1;
        }
        100% {
            transform: scale(1) rotateY(0deg);
            opacity: 1;
        }
    }

    /* Team answering - flash 3 times then stay white */
    .team-answering {
        animation:
            border-flash 150ms ease-in-out 6,
            border-stay 0ms 900ms forwards;
    }
    @keyframes border-flash {
        0%,
        100% {
            border-color: transparent;
        }
        50% {
            border-color: white;
        }
    }
    @keyframes border-stay {
        to {
            border-color: white;
        }
    }

    /* Category header transition - smooth crossfade between logo and name */
    .category-header {
        min-height: 3em;
    }
    .category-content {
        position: relative;
        display: grid;
        place-items: center;
    }
    .category-logo,
    .category-name {
        grid-area: 1 / 1;
        display: flex;
        align-items: center;
        justify-content: center;
        transition:
            opacity 400ms ease-in-out,
            transform 400ms ease-in-out;
    }
    .category-logo {
        height: 1.2em;
    }
    .category-content.show-logo .category-logo {
        opacity: 1;
        transform: scale(1);
    }
    .category-content.show-logo .category-name {
        opacity: 0;
        transform: scale(0.9);
    }
    .category-content.show-name .category-logo {
        opacity: 0;
        transform: scale(1.1);
    }
    .category-content.show-name .category-name {
        opacity: 1;
        transform: scale(1);
    }
</style>
