<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 {
        KvButtonPrimary,
        KvButtonSecondary,
        KvNumberInput,
        KvEditCard,
    } from "$lib/components/kuldvillak/ui";
    import { Settings, ConfirmDialog } from "$lib/components";

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

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

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

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

    function openSettings() {
        settingsOpen = true;
    }

    // Local state
    let wagerInput = $state(5);
    let scoreAdjustment = $state(10);
    let introDelayComplete = $state(false);
    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 delay
            introDelayComplete = false;
            setTimeout(() => {
                introDelayComplete = true;
            }, 3000);
        } else if (phase !== "intro-categories") {
            introDelayComplete = false;
        }
        prevIntroPhase = phase ?? null;
    });
    let currentRound = $derived(gameSession.currentRound);
    let questionData = $derived(gameSession.currentQuestionData);

    // Calculate total questions in all rounds
    let totalQuestions = $derived(() => {
        if (!session) return 30;
        return session.rounds.reduce((total, round) => {
            return (
                total +
                round.categories.reduce((catTotal, cat) => {
                    return catTotal + cat.questions.length;
                }, 0)
            );
        }, 0);
    });

    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);
    }

    function handleTeamClick(teamId: string) {
        if (
            session?.phase === "question" &&
            !session.showAnswer &&
            !isTeamWrong(teamId)
        ) {
            gameSession.setActiveTeam(teamId);
        }
    }

    // Count daily doubles in a round
    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
        );
    }
</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 font-kv-body text-kv-white uppercase"
            >
                <h1 class="text-2xl md:text-4xl kv-shadow-text m-0">
                    {session.name}
                </h1>
                <div class="flex items-center gap-2">
                    {#if session.phase.startsWith("final")}
                        <span class="text-xl md:text-[28px] kv-shadow-text">
                            {m.kv_final_round()}
                        </span>
                    {:else}
                        <span class="text-xl md:text-[28px] kv-shadow-text">
                            {session.currentRoundIndex === 0
                                ? "Villak"
                                : "Topeltvillak"}
                        </span>
                        <span class="text-base md:text-xl text-kv-yellow">
                            ({m.kv_edit_dd_short()}
                            {countDailyDoubles(
                                session.currentRoundIndex,
                            )}/{session.settings.dailyDoublesPerRound[
                                session.currentRoundIndex
                            ] ?? 1})
                        </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">
                    <KvButtonPrimary onclick={openProjector}>
                        {m.kv_play_open_projector()}
                    </KvButtonPrimary>
                    {#if session.phase === "board"}
                        {#if session.rounds.length > 1 && session.currentRoundIndex === 0}
                            <!-- Two rounds and on first round: show Next Round button -->
                            <KvButtonPrimary
                                onclick={() => gameSession.nextRound()}
                            >
                                {m.kv_play_next_round()}
                            </KvButtonPrimary>
                        {:else if session.settings.enableFinalRound && session.finalRound}
                            <!-- One round OR on second round: show Final Round button -->
                            <KvButtonPrimary
                                onclick={() => gameSession.goToFinalRound()}
                            >
                                {m.kv_play_go_to_final()}
                            </KvButtonPrimary>
                        {/if}
                    {/if}
                    <KvButtonSecondary
                        onclick={() => (showEndGameConfirm = true)}
                    >
                        {m.kv_play_end_game()}
                    </KvButtonSecondary>
                </div>

                <!-- Last Answer & Score Adjustment -->
                <div
                    class="flex flex-wrap items-center justify-between gap-8 w-full"
                >
                    {#if session.lastAnsweredTeamId}
                        {@const lastTeam = session.teams.find(
                            (t) => t.id === session.lastAnsweredTeamId,
                        )}
                        <span
                            class="font-kv-body text-lg md:text-xl text-kv-white uppercase kv-shadow-text"
                        >
                            {m.kv_play_last_answer()}:
                            <span
                                class={session.lastAnswerCorrect
                                    ? "text-kv-yellow"
                                    : "text-kv-red"}
                            >
                                {lastTeam?.name}
                            </span>
                        </span>
                    {:else}
                        <span></span>
                    {/if}

                    <div class="flex items-center gap-4">
                        <span
                            class="font-kv-body text-lg md:text-xl text-kv-white uppercase kv-shadow-text"
                        >
                            {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="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="font-kv-body text-4xl md:text-6xl text-kv-yellow uppercase kv-shadow-text"
                        >
                            Kuldvillak
                        </span>
                        <div class="flex gap-4">
                            <KvButtonPrimary
                                onclick={() => gameSession.startCategoryIntro()}
                            >
                                {m.kv_play_introduce_categories()}
                            </KvButtonPrimary>
                            <KvButtonSecondary
                                onclick={() => gameSession.startBoard()}
                            >
                                {m.kv_play_skip_to_game()}
                            </KvButtonSecondary>
                        </div>
                    {:else if session.phase === "intro-categories"}
                        {#if !introDelayComplete && session.introCategoryIndex === 0}
                            <!-- Initial 3s delay - show Villak/Topeltvillak -->
                            <span
                                class="font-kv-body text-4xl md:text-6xl text-kv-yellow uppercase kv-shadow-text"
                            >
                                {session.currentRoundIndex === 0
                                    ? "Villak"
                                    : "Topeltvillak"}
                            </span>
                        {:else if currentRound?.categories[session.introCategoryIndex]}
                            <span
                                class="font-kv-body text-4xl md:text-6xl text-kv-white uppercase kv-shadow-text"
                            >
                                {currentRound.categories[
                                    session.introCategoryIndex
                                ].name}
                            </span>
                            <span
                                class="font-kv-body text-2xl text-kv-yellow uppercase"
                            >
                                {session.introCategoryIndex + 1} / {currentRound
                                    .categories.length}
                            </span>
                        {:else}
                            <KvButtonPrimary
                                onclick={() => gameSession.startBoard()}
                            >
                                {m.kv_play_start_game()}
                            </KvButtonPrimary>
                        {/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="font-kv-body text-sm md:text-2xl text-kv-white text-center uppercase kv-shadow-text"
                            >
                                {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="font-kv-body text-4xl md:text-6xl text-kv-yellow uppercase kv-shadow-text"
                >
                    {m.kv_play_daily_double()}!
                </h2>

                <!-- Team Selection -->
                <div class="flex flex-wrap gap-4 justify-center">
                    {#each session.teams as team}
                        <button
                            class="bg-kv-blue border-4 border-black box-border font-kv-body text-xl md:text-2xl px-6 py-3 cursor-pointer uppercase hover:opacity-80 kv-shadow-text kv-shadow-button
                                {session.activeTeamId === team.id
                                ? 'border-kv-yellow text-kv-yellow'
                                : 'text-kv-white'}"
                            onclick={() => gameSession.setActiveTeam(team.id)}
                        >
                            {team.name} ({team.score}€)
                        </button>
                    {/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="font-kv-body text-lg text-kv-yellow uppercase kv-shadow-text"
                    >
                        Min: 5€ — Max: {maxWager}€
                    </div>
                    <div class="flex items-center gap-4">
                        <span
                            class="font-kv-body text-xl md:text-2xl text-kv-white uppercase kv-shadow-text"
                        >
                            {m.kv_play_wager()}:
                        </span>
                        <input
                            type="number"
                            class="bg-transparent border-4 border-black box-border font-kv-body text-xl md:text-2xl text-kv-white text-center px-4 py-2 w-32
                                {!isValidWager ? 'border-red-500' : ''}"
                            min="5"
                            max={maxWager}
                            step="5"
                            bind:value={wagerInput}
                        />
                        <KvButtonPrimary
                            onclick={confirmDailyDoubleWager}
                            disabled={!isValidWager}
                        >
                            {m.kv_play_confirm()}
                        </KvButtonPrimary>
                    </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="font-kv-body text-lg md:text-xl text-kv-green uppercase kv-shadow-text"
                    >
                        {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="font-kv-body text-lg md:text-xl text-kv-yellow uppercase kv-shadow-text"
                    >
                        {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="font-kv-body text-lg md:text-xl text-kv-yellow uppercase kv-shadow-text"
                    >
                        {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="font-kv-body text-lg md:text-xl text-kv-red uppercase kv-shadow-text"
                    >
                        {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="font-kv-body text-lg md:text-xl text-kv-red uppercase kv-shadow-text"
                    >
                        {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="font-kv-body text-lg md:text-xl text-kv-red uppercase kv-shadow-text"
                    >
                        {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="font-kv-body text-lg md:text-xl text-kv-yellow uppercase kv-shadow-text"
                    >
                        {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="font-kv-body text-lg text-kv-white/70 uppercase"
                    >
                        {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="font-kv-body text-2xl md:text-3xl lg:text-4xl text-kv-yellow text-center uppercase kv-shadow-text"
                >
                    {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="font-kv-body text-lg md:text-xl text-kv-white uppercase kv-shadow-text"
                        >
                            {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="font-kv-body text-lg md:text-xl text-kv-white text-center kv-shadow-text"
                            >
                                {session.timerSeconds}
                            </span>
                        </div>
                        <span
                            class="font-kv-body text-lg md:text-xl text-kv-white uppercase kv-shadow-text"
                        >
                            {m.kv_play_seconds()}
                        </span>
                    </div>

                    <div class="flex items-center gap-4">
                        {#if session.timerRunning}
                            <button
                                class="bg-kv-red border-4 border-black box-border font-kv-body text-xl md:text-2xl text-kv-white uppercase px-4 py-2 cursor-pointer hover:opacity-80 kv-shadow-text"
                                onclick={() => gameSession.stopTimer()}
                            >
                                {m.kv_play_stop()}
                            </button>
                        {:else}
                            <button
                                class="bg-kv-green border-4 border-black box-border font-kv-body text-xl md:text-2xl text-kv-white uppercase px-4 py-2 cursor-pointer hover:opacity-80 kv-shadow-text"
                                onclick={() => gameSession.startTimer()}
                            >
                                {m.kv_play_start()}
                            </button>
                        {/if}
                        <button
                            class="bg-transparent border-4 border-black box-border font-kv-body text-xl md:text-2xl text-kv-white uppercase px-4 py-2 cursor-pointer hover:opacity-80 kv-shadow-text"
                            onclick={() => gameSession.resetTimer()}
                        >
                            {m.kv_play_reset()}
                        </button>
                        <button
                            class="bg-kv-yellow border-4 border-black box-border font-kv-body text-xl md:text-2xl text-black uppercase px-4 py-2 cursor-pointer hover:opacity-80"
                            onclick={skipQuestion}
                            disabled={session.showAnswer}
                        >
                            {m.kv_play_skip()}
                        </button>
                    </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 like first round -->
                    <span
                        class="font-kv-body text-4xl md:text-6xl text-kv-white uppercase kv-shadow-text"
                    >
                        {session.finalRound?.category}
                    </span>
                    <span
                        class="font-kv-body text-2xl text-kv-yellow uppercase"
                    >
                        {m.kv_play_final_round()}
                    </span>
                    <KvButtonPrimary
                        onclick={() => gameSession.showFinalQuestion()}
                    >
                        {m.kv_play_question_short()}
                    </KvButtonPrimary>
                {:else}
                    <!-- Before reveal - show Final Round title -->
                    <span
                        class="font-kv-title text-5xl md:text-7xl text-kv-yellow uppercase kv-shadow-text"
                    >
                        {m.kv_play_final_round()}
                    </span>
                    <KvButtonPrimary
                        onclick={() => gameSession.startFinalCategoryReveal()}
                    >
                        {m.kv_play_reveal_category()}
                    </KvButtonPrimary>
                {/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="font-kv-body text-lg md:text-xl text-kv-yellow uppercase kv-shadow-text"
                    >
                        {m.kv_play_judging()}: {activeTeam.name}
                    </span>
                {:else}
                    <span
                        class="font-kv-body text-lg text-kv-white/70 uppercase"
                    >
                        {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="font-kv-body text-2xl md:text-3xl lg:text-4xl text-kv-yellow text-center uppercase kv-shadow-text"
                >
                    {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="font-kv-body text-lg md:text-xl text-kv-white uppercase kv-shadow-text"
                        >
                            {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="font-kv-body text-lg md:text-xl text-kv-white text-center kv-shadow-text"
                            >
                                {session.timerSeconds}
                            </span>
                        </div>
                        <span
                            class="font-kv-body text-lg md:text-xl text-kv-white uppercase kv-shadow-text"
                        >
                            {m.kv_play_seconds()}
                        </span>
                    </div>

                    <div class="flex items-center gap-4">
                        {#if session.timerRunning}
                            <button
                                class="bg-kv-red border-4 border-black box-border font-kv-body text-xl md:text-2xl text-kv-white uppercase px-4 py-2 cursor-pointer hover:opacity-80 kv-shadow-text"
                                onclick={() => gameSession.stopTimer()}
                            >
                                {m.kv_play_stop()}
                            </button>
                        {:else}
                            <button
                                class="bg-kv-green border-4 border-black box-border font-kv-body text-xl md:text-2xl text-kv-white uppercase px-4 py-2 cursor-pointer hover:opacity-80 kv-shadow-text"
                                onclick={() => gameSession.startTimer()}
                            >
                                {m.kv_play_start()}
                            </button>
                        {/if}
                        <button
                            class="bg-transparent border-4 border-black box-border font-kv-body text-xl md:text-2xl text-kv-white uppercase px-4 py-2 cursor-pointer hover:opacity-80 kv-shadow-text"
                            onclick={() => gameSession.resetTimer()}
                        >
                            {m.kv_play_reset()}
                        </button>
                    </div>
                </div>

                <!-- After all judged: Reveal Answer, then Show Scores -->
                {#if session.finalRevealed.length === session.teams.length}
                    {#if session.showAnswer}
                        <KvButtonPrimary
                            onclick={() => gameSession.showFinalScores()}
                        >
                            {m.kv_play_show_scores()}
                        </KvButtonPrimary>
                    {:else}
                        <KvButtonSecondary
                            onclick={() => gameSession.revealFinalAnswer()}
                        >
                            {m.kv_play_reveal_answer()}
                        </KvButtonSecondary>
                    {/if}
                {/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 p-4 gap-4">
                <!-- Top row -->
                <div
                    class="flex-1 grid gap-2"
                    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="font-kv-body text-2xl md:text-4xl uppercase kv-shadow-text {team.score <
                                0
                                    ? 'text-kv-red'
                                    : 'text-kv-white'}"
                            >
                                {team.score}€
                            </span>
                            <span
                                class="font-kv-body text-lg md:text-2xl text-kv-white uppercase kv-shadow-text"
                            >
                                {team.name}
                            </span>
                            <span
                                class="font-kv-body text-lg md:text-2xl 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-2"
                        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="font-kv-body text-2xl md:text-4xl uppercase kv-shadow-text {team.score <
                                    0
                                        ? 'text-kv-red'
                                        : 'text-kv-white'}"
                                >
                                    {team.score}€
                                </span>
                                <span
                                    class="font-kv-body text-lg md:text-2xl text-kv-white uppercase kv-shadow-text"
                                >
                                    {team.name}
                                </span>
                                <span
                                    class="font-kv-body text-lg md:text-2xl text-kv-white uppercase kv-shadow-text"
                                >
                                    #{i + topRowCount + 1}
                                </span>
                            </div>
                        {/each}
                    </div>
                {/if}
                <div class="flex justify-center">
                    <KvButtonPrimary onclick={() => gameSession.endGame()}>
                        {m.kv_play_end_game()}
                    </KvButtonPrimary>
                </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="font-kv-title text-5xl md:text-7xl text-kv-yellow uppercase kv-shadow-text"
                >
                    {m.kv_play_game_over()}!
                </span>
                <KvButtonPrimary
                    onclick={() => {
                        gameSession.clearSession();
                        goto("/kuldvillak/edit");
                    }}
                >
                    {m.kv_play_finish()}
                </KvButtonPrimary>
            </div>
        {/if}
    </div>
{:else}
    <div class="min-h-screen bg-kv-black flex items-center justify-center">
        <span class="font-kv-body text-2xl text-kv-white uppercase">
            {m.kv_play_loading()}
        </span>
    </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()}
/>
