<script lang="ts">
    import { gameSession } from "$lib/stores/gameSession.svelte";
    import { goto } from "$app/navigation";
    import { onMount } from "svelte";
    import * as m from "$lib/paraglide/messages";
    import {
        KvButton,
        KvNumberInput,
        KvEditCard,
    } from "$lib/components/kuldvillak/ui";
    import { Settings, ConfirmDialog } from "$lib/components";

    // Only moderator controls the timer
    onMount(() => {
        gameSession.enableTimerControl();

        // Add spacebar event listener for timer control
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.code === "Space") {
                e.preventDefault(); // Prevent scrolling
                if (
                    ["question", "final-question"].includes(
                        session?.phase || "",
                    ) &&
                    !session?.showAnswer
                ) {
                    if (session?.timerRunning) {
                        gameSession.stopTimer();
                    } else {
                        gameSession.startTimer();
                    }
                }
            }
        };

        window.addEventListener("keydown", handleKeyDown);

        return () => {
            window.removeEventListener("keydown", handleKeyDown);
        };
    });

    // Settings modal state
    let settingsOpen = $state(false);

    // End game confirmation dialog
    let showEndGameConfirm = $state(false);

    // Loading overlay when finishing game
    let isFinishing = $state(false);

    async function finishGame() {
        isFinishing = true;
        gameSession.clearSession();
        await goto("/kuldvillak/edit");
    }

    function openProjector() {
        gameSession.openProjector();
    }

    function openSettings() {
        settingsOpen = true;
    }

    // Local state
    let wagerInput = $state(5);
    let scoreAdjustment = $state(10);
    let introDelayComplete = $state(false);
    let introCountdown = $state(3);
    let prevIntroPhase = $state<string | null>(null);

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

    // Track intro-categories initial delay (3 seconds before first category shows)
    $effect(() => {
        const phase = session?.phase;
        if (
            phase === "intro-categories" &&
            prevIntroPhase !== "intro-categories"
        ) {
            // Just entered intro-categories, start 3s countdown
            introDelayComplete = false;
            introCountdown = 3;
            const interval = setInterval(() => {
                introCountdown--;
                if (introCountdown <= 0) {
                    clearInterval(interval);
                    introDelayComplete = true;
                }
            }, 1000);
            return () => clearInterval(interval);
        } else if (phase !== "intro-categories") {
            introDelayComplete = false;
            introCountdown = 3;
        }
        prevIntroPhase = phase ?? null;
    });
    let currentRound = $derived(gameSession.currentRound);
    let questionData = $derived(gameSession.currentQuestionData);

    function selectQuestion(catIndex: number, qIndex: number) {
        if (!session) return;
        gameSession.selectQuestion(session.currentRoundIndex, catIndex, qIndex);
    }

    function markCorrect() {
        if (!session?.activeTeamId) return;
        gameSession.markCorrect(session.activeTeamId);
    }

    function markWrong() {
        if (!session?.activeTeamId) return;
        gameSession.markWrong(session.activeTeamId);
    }

    function skipQuestion() {
        gameSession.skipQuestion();
    }

    function isTeamWrong(teamId: string) {
        return session?.wrongTeamIds?.includes(teamId) ?? false;
    }

    function confirmDailyDoubleWager() {
        if (!session?.activeTeamId) return;
        gameSession.setDailyDoubleWager(session.activeTeamId, wagerInput);
    }

    function adjustScore(teamId: string, amount: number) {
        gameSession.adjustScore(teamId, amount);
    }

    // Count daily doubles in a round (total)
    function countDailyDoubles(roundIndex: number) {
        if (!session) return 0;
        const round = session.rounds[roundIndex];
        return (
            round?.categories.reduce((count, cat) => {
                return (
                    count + cat.questions.filter((q) => q.isDailyDouble).length
                );
            }, 0) ?? 0
        );
    }

    // Count remaining (unrevealed) daily doubles in a round
    function countRemainingDailyDoubles(roundIndex: number) {
        if (!session) return 0;
        const round = session.rounds[roundIndex];
        return (
            round?.categories.reduce((count, cat) => {
                return (
                    count +
                    cat.questions.filter(
                        (q) => q.isDailyDouble && !q.isRevealed,
                    ).length
                );
            }, 0) ?? 0
        );
    }

    // Calculate total questions in current round
    let totalQuestionsInRound = $derived(
        currentRound?.categories.reduce(
            (total, cat) => total + cat.questions.length,
            0,
        ) ?? 0,
    );

    // Count answered questions in current round
    let answeredInRound = $derived(
        currentRound?.categories.reduce(
            (total, cat) =>
                total + cat.questions.filter((q) => q.isRevealed).length,
            0,
        ) ?? 0,
    );
</script>

{#if session}
    <div class="min-h-screen bg-kv-black flex flex-col gap-4 p-4">
        <!-- Header Section -->
        <header
            class="bg-kv-blue flex flex-col md:flex-row items-start md:items-center justify-between p-4 gap-4"
        >
            <!-- Left: Game Info -->
            <div class="flex flex-col gap-2 text-kv-white">
                <h1 class="kv-h1 m-0">
                    {session.name}
                </h1>
                <div class="flex items-center gap-2">
                    {#if session.phase.startsWith("final")}
                        <span class="kv-h2">
                            {m.kv_final_round()}
                        </span>
                    {:else}
                        <span class="kv-h2">
                            {session.currentRoundIndex === 0
                                ? m.kv_edit_r1()
                                : m.kv_edit_r2()}
                        </span>
                        <span class="kv-body-lg text-kv-yellow">
                            ({m.kv_edit_dd_short()}
                            {countRemainingDailyDoubles(
                                session.currentRoundIndex,
                            )}/{countDailyDoubles(session.currentRoundIndex)},
                            {m.kv_play_question_short()}: {answeredInRound}/{totalQuestionsInRound})
                        </span>
                    {/if}
                </div>
            </div>

            <!-- Right: Buttons and Settings -->
            <div class="flex flex-col gap-4 items-end w-full md:w-auto">
                <!-- Action Buttons -->
                <div class="flex flex-wrap gap-4 items-center justify-end">
                    <KvButton variant="primary" onclick={openProjector}>
                        {m.kv_play_open_projector()}
                    </KvButton>
                    {#if session.phase === "board"}
                        {#if session.rounds.length > 1 && session.currentRoundIndex === 0}
                            <!-- Two rounds and on first round: show Next Round button -->
                            <KvButton
                                variant="primary"
                                onclick={() => gameSession.nextRound()}
                            >
                                {m.kv_play_next_round()}
                            </KvButton>
                        {:else if session.settings.enableFinalRound && session.finalRound}
                            <!-- One round OR on second round: show Final Round button -->
                            <KvButton
                                variant="primary"
                                onclick={() => gameSession.goToFinalRound()}
                            >
                                {m.kv_play_go_to_final()}
                            </KvButton>
                        {/if}
                    {/if}
                    <KvButton
                        variant="secondary"
                        onclick={() => (showEndGameConfirm = true)}
                    >
                        {m.kv_play_end_game()}
                    </KvButton>
                </div>

                <!-- Last Answer & Score Adjustment -->
                <div class="flex flex-wrap items-center gap-16">
                    {#if session.lastCorrectTeamId}
                        {@const lastCorrectTeam = session.teams.find(
                            (t) => t.id === session.lastCorrectTeamId,
                        )}
                        <span class="kv-body-lg text-kv-white">
                            {m.kv_play_last_answer()}:
                            <span class="text-kv-yellow">
                                {lastCorrectTeam?.name}
                            </span>
                        </span>
                    {:else}
                        <span></span>
                    {/if}

                    <div class="flex items-center gap-4">
                        <span class="kv-body-lg text-kv-white">
                            {m.kv_play_adjust_score()}:
                        </span>
                        <KvNumberInput
                            bind:value={scoreAdjustment}
                            min={10}
                            step={10}
                        />
                        <!-- Settings Button -->
                        <button
                            onclick={openSettings}
                            class="text-kv-yellow hover:opacity-80 transition-opacity cursor-pointer bg-transparent border-none p-0"
                            aria-label={m.kv_settings()}
                        >
                            <svg
                                viewBox="0 0 48 48"
                                fill="currentColor"
                                class="w-10 h-10"
                            >
                                <path
                                    d="M19.4 44L18.4 37.35Q17.45 36.95 16.4 36.35Q15.35 35.75 14.55 35.1L8.3 37.8L4 30.2L9.45 26.05Q9.35 25.55 9.325 24.975Q9.3 24.4 9.3 24Q9.3 23.6 9.325 23.025Q9.35 22.45 9.45 21.95L4 17.8L8.3 10.2L14.55 12.9Q15.35 12.25 16.4 11.65Q17.45 11.05 18.4 10.65L19.4 4H28.6L29.6 10.65Q30.55 11.05 31.6 11.65Q32.65 12.25 33.45 12.9L39.7 10.2L44 17.8L38.55 21.95Q38.65 22.45 38.675 23.025Q38.7 23.6 38.7 24Q38.7 24.4 38.675 24.975Q38.65 25.55 38.55 26.05L44 30.2L39.7 37.8L33.45 35.1Q32.65 35.75 31.6 36.35Q30.55 36.95 29.6 37.35L28.6 44ZM24 30.5Q26.7 30.5 28.6 28.6Q30.5 26.7 30.5 24Q30.5 21.3 28.6 19.4Q26.7 17.5 24 17.5Q21.3 17.5 19.4 19.4Q17.5 21.3 17.5 24Q17.5 26.7 19.4 28.6Q21.3 30.5 24 30.5Z"
                                />
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <!-- Players Row -->
        <div class="flex gap-2 w-full">
            {#each session.teams as team (team.id)}
                {@const isAnswering =
                    session.phase === "question" &&
                    session.activeTeamId === team.id &&
                    !session.showAnswer}
                {@const canSelect =
                    (session.phase === "question" &&
                        !session.showAnswer &&
                        !isTeamWrong(team.id) &&
                        session.activeTeamId !== team.id) ||
                    (session.phase === "final-question" &&
                        !session.finalRevealed.includes(team.id) &&
                        session.activeTeamId !== team.id)}
                {@const isFinalMode = session.phase === "final-question"}
                {@const isFinalJudged = session.finalRevealed.includes(team.id)}
                {@const isFinalActive =
                    session.phase === "final-question" &&
                    session.activeTeamId === team.id}
                <KvEditCard
                    name={team.name}
                    score={team.score}
                    {scoreAdjustment}
                    answering={isAnswering}
                    selectable={canSelect}
                    finalMode={isFinalMode}
                    finalJudged={isFinalJudged}
                    finalActive={isFinalActive}
                    onSelect={() =>
                        isFinalMode
                            ? gameSession.selectFinalTeam(team.id)
                            : gameSession.setActiveTeam(team.id)}
                    onAdd={() => adjustScore(team.id, scoreAdjustment)}
                    onRemove={() => adjustScore(team.id, -scoreAdjustment)}
                    onCorrect={markCorrect}
                    onWrong={markWrong}
                    onFinalJudge={(correct, wager) =>
                        gameSession.judgeFinalAnswer(team.id, correct, wager)}
                />
            {/each}
        </div>

        <!-- Main Content Area -->
        {#if session.phase === "intro" || session.phase === "intro-categories"}
            <!-- Intro/Category Intro Phase -->
            <div class="flex-1 flex flex-col gap-4">
                <!-- Action area (categories hidden until board is revealed) -->
                <div
                    class="bg-kv-blue flex-1 flex flex-col items-center justify-center gap-8 p-8"
                >
                    {#if session.phase === "intro"}
                        <span class="kv-h1 text-kv-yellow">
                            {session.currentRoundIndex === 0
                                ? m.kv_edit_r1()
                                : m.kv_edit_r2()}
                        </span>
                        <div class="flex gap-4">
                            {#if !session.categoriesIntroduced}
                                <KvButton
                                    variant="primary"
                                    onclick={() =>
                                        gameSession.startCategoryIntro()}
                                >
                                    {m.kv_play_introduce_categories()}
                                </KvButton>
                            {/if}
                            <KvButton
                                variant="secondary"
                                onclick={() => gameSession.startBoard()}
                            >
                                {session.categoriesIntroduced
                                    ? m.kv_play_start_game()
                                    : m.kv_play_skip_to_game()}
                            </KvButton>
                        </div>
                    {:else if session.phase === "intro-categories"}
                        {#if !introDelayComplete && session.introCategoryIndex === 0}
                            <!-- Initial 3s delay - show round name with countdown -->
                            <span class="kv-h1 text-kv-yellow">
                                {session.currentRoundIndex === 0
                                    ? m.kv_edit_r1()
                                    : m.kv_edit_r2()}
                            </span>
                            <span class="kv-body-lg text-kv-white">
                                {m.kv_play_introducing_categories({
                                    seconds: introCountdown,
                                })}
                            </span>
                        {:else if currentRound?.categories[session.introCategoryIndex]}
                            <span class="kv-h1 text-kv-white">
                                {currentRound.categories[
                                    session.introCategoryIndex
                                ].name}
                            </span>
                            <span class="kv-h2 text-kv-yellow">
                                {session.introCategoryIndex + 1} / {currentRound
                                    .categories.length}
                            </span>
                        {:else}
                            <KvButton
                                variant="primary"
                                onclick={() => gameSession.startBoard()}
                            >
                                {m.kv_play_start_game()}
                            </KvButton>
                        {/if}
                    {/if}
                </div>
            </div>
        {:else if session.phase === "board"}
            <!-- Game Board Phase -->
            <div class="flex-1 flex flex-col gap-2">
                <!-- Categories -->
                <div class="grid grid-cols-6 gap-2">
                    {#each currentRound?.categories ?? [] as cat}
                        <div
                            class="bg-kv-blue flex items-center justify-center p-2 min-h-[40px]"
                        >
                            <span class="kv-h3 text-kv-white text-center">
                                {cat.name || "???"}
                            </span>
                        </div>
                    {/each}
                </div>

                <!-- Questions Grid - iterate by row (question index), then by column (category) -->
                <div class="grid grid-cols-6 gap-2 flex-1">
                    {#each { length: session.settings.questionsPerCategory } as _, qi}
                        {#each currentRound?.categories ?? [] as cat, ci}
                            {@const q = cat.questions[qi]}
                            {@const result = gameSession.getQuestionResult(
                                ci,
                                qi,
                            )}
                            <button
                                class="bg-kv-blue flex items-center justify-center p-2 cursor-pointer border-none transition-opacity hover:brightness-110 disabled:cursor-not-allowed box-border
                                    {q.isRevealed ? 'opacity-50' : ''}
                                    {q.isDailyDouble && !q.isRevealed
                                    ? 'ring-4 ring-inset ring-kv-yellow'
                                    : ''}"
                                disabled={q.isRevealed}
                                onclick={() => selectQuestion(ci, qi)}
                            >
                                <span
                                    class="font-kv-price text-2xl md:text-4xl text-kv-yellow kv-shadow-price"
                                >
                                    {q.points}€
                                </span>
                            </button>
                        {/each}
                    {/each}
                </div>
            </div>
        {:else if session.phase === "daily-double"}
            <!-- Daily Double Wager Phase -->
            <div
                class="bg-kv-blue flex-1 flex flex-col items-center justify-center gap-8 p-8"
            >
                <h2 class="kv-h1 text-kv-yellow">
                    {m.kv_play_daily_double()}!
                </h2>

                <!-- Team Selection -->
                <div class="flex flex-wrap gap-4 justify-center">
                    {#each session.teams as team}
                        <KvButton
                            variant="primary"
                            class={session.activeTeamId === team.id
                                ? "border-kv-yellow text-kv-yellow"
                                : ""}
                            onclick={() => gameSession.setActiveTeam(team.id)}
                        >
                            {team.name} ({team.score}€)
                        </KvButton>
                    {/each}
                </div>

                {#if session.activeTeamId}
                    {@const activeTeam = session.teams.find(
                        (t) => t.id === session.activeTeamId,
                    )}
                    {@const maxWager = Math.max(
                        activeTeam?.score ?? 0,
                        Math.max(...(session?.settings.pointValues ?? [50])) *
                            (currentRound?.pointMultiplier ?? 1),
                    )}
                    {@const isValidWager =
                        wagerInput >= 5 && wagerInput <= maxWager}
                    <div class="kv-body-lg text-kv-yellow">
                        {m.kv_play_wager_range({ min: 5, max: maxWager })}
                    </div>
                    <div class="flex items-center gap-4">
                        <span class="kv-h3 text-kv-white">
                            {m.kv_play_wager()}:
                        </span>
                        <input
                            type="number"
                            class="bg-transparent border-4 border-black box-border kv-h3-plain text-kv-white text-center px-4 py-2 w-32
                                {!isValidWager ? 'border-red-500' : ''}"
                            min="5"
                            max={maxWager}
                            step="5"
                            bind:value={wagerInput}
                        />
                        <KvButton
                            variant="primary"
                            onclick={confirmDailyDoubleWager}
                            disabled={!isValidWager}
                        >
                            {m.kv_play_confirm()}
                        </KvButton>
                    </div>
                {/if}
            </div>
        {:else if session.phase === "question" && questionData}
            <!-- Question View -->
            <div
                class="bg-kv-blue flex-1 flex flex-col items-center justify-center gap-8 p-4 md:p-8"
            >
                <!-- Status Message (at top) -->
                {#if session.revealCountdown !== null && session.revealCountdown > 0 && session.lastAnswerCorrect === true && !session.skippingQuestion}
                    {@const lastTeamName =
                        session.teams.find(
                            (t) => t.id === session.lastAnsweredTeamId,
                        )?.name ?? ""}
                    <!-- Correct answer - returning to board -->
                    <span class="kv-body-lg text-kv-green">
                        {m.kv_play_correct_return({
                            name: lastTeamName,
                            seconds: session.revealCountdown,
                        })}
                    </span>
                {:else if session.revealCountdown !== null && session.revealCountdown > 0}
                    <!-- Answer revealed - returning to board -->
                    <span class="kv-body-lg text-kv-yellow">
                        {m.kv_play_answer_revealed({
                            seconds: session.revealCountdown,
                        })}
                    </span>
                {:else if session.skippingQuestion && session.timeoutCountdown !== null && session.timeoutCountdown > 0}
                    <!-- Skipping question - revealing answer -->
                    <span class="kv-body-lg text-kv-yellow">
                        {m.kv_play_skip_reveal({
                            seconds: session.timeoutCountdown,
                        })}
                    </span>
                {:else if session.timeoutCountdown !== null && session.timeoutCountdown > 0 && session.lastAnswerCorrect === false}
                    {@const lastTeamName =
                        session.teams.find(
                            (t) => t.id === session.lastAnsweredTeamId,
                        )?.name ?? ""}
                    <!-- All wrong - revealing answer -->
                    <span class="kv-body-lg text-kv-red">
                        {m.kv_play_wrong_reveal({
                            name: lastTeamName,
                            seconds: session.timeoutCountdown,
                        })}
                    </span>
                {:else if session.timeoutCountdown !== null && session.timeoutCountdown > 0}
                    <!-- Timer ran out - revealing answer -->
                    <span class="kv-body-lg text-kv-red">
                        {m.kv_play_timeout_reveal({
                            seconds: session.timeoutCountdown,
                        })}
                    </span>
                {:else if session.lastAnswerCorrect === false && !session.activeTeamId && !session.showAnswer && !session.teams.every( (t) => session.wrongTeamIds.includes(t.id), )}
                    {@const lastTeamName =
                        session.teams.find(
                            (t) => t.id === session.lastAnsweredTeamId,
                        )?.name ?? ""}
                    <!-- Wrong answer - waiting for next player -->
                    <span class="kv-body-lg text-kv-red">
                        {m.kv_play_wrong_waiting({ name: lastTeamName })}
                    </span>
                {:else if session.activeTeamId && !session.timerRunning && !session.showAnswer}
                    {@const activeTeamName =
                        session.teams.find((t) => t.id === session.activeTeamId)
                            ?.name ?? ""}
                    <!-- Timer paused - someone answering -->
                    <span class="kv-body-lg text-kv-yellow">
                        {m.kv_play_timer_paused({ name: activeTeamName })}
                    </span>
                {:else if !session.activeTeamId && !session.showAnswer && (session.timerRunning || session.timerSeconds > 0)}
                    <!-- Waiting for team selection -->
                    <span class="kv-body-lg text-kv-white/70">
                        {m.kv_play_click_team_to_answer()}
                    </span>
                {/if}

                <!-- Question Text -->
                <div
                    class="font-kv-question text-3xl md:text-5xl lg:text-[64px] text-kv-white text-center uppercase leading-[1] kv-shadow-question"
                    style="transform: scaleX(0.9225);"
                >
                    {questionData.question.question}
                </div>

                <!-- Answer Text -->
                <div class="kv-h2 text-kv-yellow text-center">
                    {m.kv_play_answer_short()}: {questionData.question.answer}
                </div>

                <!-- Timer Controls -->
                <div class="flex flex-col items-center gap-4">
                    <div class="flex items-center gap-4">
                        <span class="kv-body-lg text-kv-white">
                            {m.kv_play_timer()}
                        </span>
                        <div
                            class="border-4 border-black box-border flex items-center justify-center h-12 px-4 min-w-[60px]"
                        >
                            <span
                                class="kv-body-lg-plain text-kv-white text-center"
                            >
                                {session.timerSeconds}
                            </span>
                        </div>
                        <span class="kv-body-lg text-kv-white">
                            {m.kv_play_seconds()}
                        </span>
                    </div>

                    <div class="flex items-center gap-4">
                        {#if session.timerRunning}
                            <KvButton
                                variant="danger"
                                onclick={() => gameSession.stopTimer()}
                            >
                                {m.kv_play_stop()}
                            </KvButton>
                        {:else}
                            <KvButton
                                variant="success"
                                onclick={() => gameSession.startTimer()}
                                disabled={session.showAnswer ||
                                    session.timeoutCountdown !== null ||
                                    session.revealCountdown !== null}
                            >
                                {m.kv_play_start()}
                            </KvButton>
                        {/if}
                        <KvButton
                            variant="ghost"
                            onclick={() => gameSession.resetTimer()}
                            disabled={session.showAnswer ||
                                session.timeoutCountdown !== null ||
                                session.revealCountdown !== null}
                        >
                            {m.kv_play_reset()}
                        </KvButton>
                        <KvButton
                            variant="warning"
                            onclick={skipQuestion}
                            disabled={session.showAnswer ||
                                session.timeoutCountdown !== null ||
                                session.revealCountdown !== null}
                        >
                            {m.kv_play_skip()}
                        </KvButton>
                    </div>
                </div>
            </div>
        {:else if session.phase === "final-intro" || session.phase === "final-category"}
            <!-- Final Round Intro/Category Reveal -->
            <div
                class="bg-kv-blue flex-1 flex flex-col items-center justify-center gap-8 p-8"
            >
                {#if session.finalCategoryRevealed || session.phase === "final-category"}
                    <!-- Category revealed - show prominently -->
                    <span class="kv-h1 text-kv-white">
                        {session.finalRound?.category}
                    </span>
                    <span class="kv-h2 text-kv-yellow">
                        {m.kv_play_final_round()}
                    </span>
                    {#if session.finalCategoryRevealed}
                        <!-- Only show question button after reveal completes -->
                        <KvButton
                            variant="primary"
                            onclick={() => gameSession.showFinalQuestion()}
                        >
                            {m.kv_play_question_short()}
                        </KvButton>
                    {/if}
                {:else}
                    <!-- Before reveal - show Final Round title -->
                    <span class="kv-h1 text-kv-yellow">
                        {m.kv_play_final_round()}
                    </span>
                    <KvButton
                        variant="primary"
                        onclick={() => gameSession.startFinalCategoryReveal()}
                    >
                        {m.kv_play_reveal_category()}
                    </KvButton>
                {/if}
            </div>
        {:else if session.phase === "final-question"}
            {@const activeTeam = session.teams.find(
                (t) => t.id === session.activeTeamId,
            )}
            <!-- Final Question -->
            <div
                class="bg-kv-blue flex-1 flex flex-col items-center justify-center gap-6 p-4 md:p-8"
            >
                <!-- Status Message -->
                {#if activeTeam}
                    <span class="kv-body-lg text-kv-yellow">
                        {m.kv_play_judging()}: {activeTeam.name}
                    </span>
                {:else}
                    <span class="kv-body-lg text-kv-white/70">
                        {m.kv_play_click_team_to_judge()}
                    </span>
                {/if}

                <!-- Question Text -->
                <div
                    class="font-kv-question text-3xl md:text-5xl lg:text-[64px] text-kv-white text-center uppercase leading-[1] kv-shadow-question"
                    style="transform: scaleX(0.9225);"
                >
                    {session.finalRound?.question}
                </div>

                <!-- Answer Text -->
                <div class="kv-h2 text-kv-yellow text-center">
                    {m.kv_play_answer_short()}: {session.finalRound?.answer}
                </div>

                <!-- Timer Controls -->
                <div class="flex flex-col items-center gap-4">
                    <div class="flex items-center gap-4">
                        <span class="kv-body-lg text-kv-white">
                            {m.kv_play_timer()}
                        </span>
                        <div
                            class="border-4 border-black box-border flex items-center justify-center h-12 px-4 min-w-[60px]"
                        >
                            <span
                                class="kv-body-lg-plain text-kv-white text-center"
                            >
                                {session.timerSeconds}
                            </span>
                        </div>
                        <span class="kv-body-lg text-kv-white">
                            {m.kv_play_seconds()}
                        </span>
                    </div>

                    <div class="flex items-center gap-4">
                        {#if session.timerRunning}
                            <KvButton
                                variant="danger"
                                onclick={() => gameSession.stopTimer()}
                            >
                                {m.kv_play_stop()}
                            </KvButton>
                        {:else}
                            <KvButton
                                variant="success"
                                onclick={() => gameSession.startTimer()}
                            >
                                {m.kv_play_start()}
                            </KvButton>
                        {/if}
                        <KvButton
                            variant="ghost"
                            onclick={() => gameSession.resetTimer()}
                        >
                            {m.kv_play_reset()}
                        </KvButton>
                    </div>
                </div>

                <!-- After all judged: Show Scores button (answer auto-reveals) -->
                {#if session.finalRevealed.length === session.teams.length}
                    <KvButton
                        variant="primary"
                        onclick={() => gameSession.showFinalScores()}
                    >
                        {m.kv_play_show_scores()}
                    </KvButton>
                {/if}
            </div>
        {:else if session.phase === "final-scores"}
            <!-- Final Scores Display - Flexible grid -->
            {@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 gap-4">
                <!-- Top row -->
                <div
                    class="flex-1 grid gap-2 bg-kv-black"
                    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-2 p-2"
                        >
                            <span
                                class="kv-h1 {team.score < 0
                                    ? 'text-kv-red'
                                    : 'text-kv-white'}"
                            >
                                {team.score}€
                            </span>
                            <span class="kv-h3 text-kv-white">
                                {team.name}
                            </span>
                            <span class="kv-h3 text-kv-white">
                                #{i + 1}
                            </span>
                        </div>
                    {/each}
                </div>
                <!-- Bottom row (if more than 3 players) -->
                {#if bottomRowCount > 0}
                    <div
                        class="flex-1 grid gap-2 bg-kv-black"
                        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-2 p-2"
                            >
                                <span
                                    class="kv-h1 {team.score < 0
                                        ? 'text-kv-red'
                                        : 'text-kv-white'}"
                                >
                                    {team.score}€
                                </span>
                                <span class="kv-h3 text-kv-white">
                                    {team.name}
                                </span>
                                <span class="kv-h3 text-kv-white">
                                    #{i + topRowCount + 1}
                                </span>
                            </div>
                        {/each}
                    </div>
                {/if}
                <div class="flex justify-center p-4 bg-kv-blue">
                    <KvButton
                        variant="primary"
                        onclick={() => (showEndGameConfirm = true)}
                    >
                        {m.kv_play_end_game()}
                    </KvButton>
                </div>
            </div>
        {:else if session.phase === "finished"}
            <!-- Game Over - Show Kuldvillak screen with end button -->
            <div
                class="bg-kv-blue flex-1 flex flex-col items-center justify-center gap-8 p-8"
            >
                <span class="kv-h1 text-kv-yellow">
                    {m.kv_play_game_over()}!
                </span>
                <KvButton
                    variant="primary"
                    onclick={finishGame}
                    disabled={isFinishing}
                >
                    {m.kv_play_finish()}
                </KvButton>
            </div>
        {/if}
    </div>
{/if}

<!-- Settings Modal -->
<Settings bind:open={settingsOpen} />

<!-- End Game Confirmation -->
<ConfirmDialog
    bind:open={showEndGameConfirm}
    title={m.kv_play_end_game()}
    message={m.kv_play_end_game_confirm()}
    confirmText={m.kv_play_end_game()}
    onconfirm={() => gameSession.endGame()}
/>

<!-- Loading overlay when finishing game -->
{#if isFinishing}
    <div
        class="fixed inset-0 bg-kv-black/90 flex flex-col items-center justify-center z-50 gap-4"
    >
        <div
            class="w-16 h-16 border-4 border-kv-yellow border-t-transparent rounded-full animate-spin"
        ></div>
    </div>
{/if}
