<script lang="ts">
    import Slider from "./Slider.svelte";
    import ColorPicker from "./ColorPicker.svelte";
    import ConfirmDialog from "./ConfirmDialog.svelte";
    import {
        KvButtonPrimary,
        KvButtonSecondary,
    } from "$lib/components/kuldvillak/ui";
    import * as m from "$lib/paraglide/messages";
    import { audioStore } from "$lib/stores/audio.svelte";
    import { themeStore } from "$lib/stores/theme.svelte";
    import { getLocale, setLocale } from "$lib/paraglide/runtime";

    interface SettingsProps {
        open?: boolean;
        onclose?: () => void;
    }

    let { open = $bindable(false), onclose }: SettingsProps = $props();

    // Confirmation dialog state
    let showConfirmClose = $state(false);

    // Show confirmation before closing
    function handleCloseClick() {
        showConfirmClose = true;
    }

    // Confirm close - revert and close
    function confirmClose() {
        showConfirmClose = false;
        themeStore.revert();
        audioStore.revert();
        open = false;
        onclose?.();
    }

    // Cancel close - go back to settings
    function cancelClose() {
        showConfirmClose = false;
    }

    // Close without saving (revert colors) - used by backdrop
    function handleCancel() {
        showConfirmClose = true;
    }

    // Save and close
    function handleSaveAndExit() {
        themeStore.save();
        audioStore.save();
        open = false;
        onclose?.();
    }

    // Reset colors to defaults (preview only, not saved until Save is clicked)
    function handleResetSettings() {
        themeStore.resetToDefaults();
    }

    function handleKeydown(e: KeyboardEvent) {
        if (e.key === "Escape") {
            if (showConfirmClose) {
                cancelClose();
            } else {
                handleCancel();
            }
        }
    }

    function handleMusicChange(value: number) {
        audioStore.setMusicVolume(value);
    }

    function handleSfxChange(value: number) {
        audioStore.setSfxVolume(value);
    }

    function switchLanguage(lang: "et" | "en") {
        setLocale(lang);
    }
</script>

<svelte:window onkeydown={handleKeydown} />

{#if open}
    <!-- Backdrop - clicking outside cancels without saving -->
    <div
        class="fixed inset-0 bg-kv-background/50 z-40"
        onclick={handleCancel}
        role="button"
        tabindex="-1"
        onkeydown={(e) => e.key === "Enter" && handleCancel()}
    ></div>

    <!-- Modal -->
    <div
        class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-50
               bg-kv-blue border-8 md:border-[16px] border-kv-black
               p-4 md:p-8 w-[95vw] md:min-w-[420px] md:w-auto max-w-[500px]
               flex flex-col gap-4 md:gap-8 items-center max-h-[90vh] overflow-y-auto"
        role="dialog"
        aria-modal="true"
        aria-labelledby="settings-title"
    >
        <!-- Header with Title and Close Button -->
        <div class="flex items-start justify-between w-full">
            <h2
                id="settings-title"
                class="text-[28px] text-kv-white uppercase font-kv-body kv-shadow-text"
            >
                {m.kv_settings_title()}
            </h2>
            <button
                onclick={handleCloseClick}
                class="w-6 h-6 cursor-pointer bg-transparent border-none p-0 hover:opacity-70"
                aria-label="Close"
            >
                <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    class="w-full h-full text-kv-yellow"
                >
                    <path d="M18 6L6 18M6 6l12 12" />
                </svg>
            </button>
        </div>

        <!-- Audio & Language Settings -->
        <div class="flex flex-col gap-4 w-full">
            <Slider
                label={m.kv_settings_music()}
                bind:value={audioStore.musicVolume}
                onchange={handleMusicChange}
            />
            <Slider
                label={m.kv_settings_sfx()}
                bind:value={audioStore.sfxVolume}
                onchange={handleSfxChange}
            />
            <!-- Language -->
            <div class="flex items-center justify-between w-full gap-4">
                <span
                    class="text-2xl text-kv-white uppercase font-kv-body kv-shadow-text"
                >
                    {m.kv_settings_language()}
                </span>
                <div class="flex gap-4">
                    <button
                        class="w-8 h-8 cursor-pointer transition-all overflow-hidden bg-transparent border-none p-0 {getLocale() ===
                        'et'
                            ? 'opacity-100'
                            : 'opacity-60 hover:opacity-80'}"
                        onclick={() => switchLanguage("et")}
                        aria-label="Eesti"
                    >
                        <svg
                            viewBox="0 0 36 36"
                            class="w-full h-full"
                            aria-hidden="true"
                        >
                            <path fill="#141414" d="M0 14h36v9H0z"></path>
                            <path
                                fill="#4891D9"
                                d="M32 5H4a4 4 0 0 0-4 4v5h36V9a4 4 0 0 0-4-4z"
                            ></path>
                            <path
                                fill="#EEE"
                                d="M32 31H4a4 4 0 0 1-4-4v-4h36v4a4 4 0 0 1-4 4z"
                            ></path>
                        </svg>
                    </button>
                    <button
                        class="w-8 h-8 cursor-pointer transition-all overflow-hidden bg-transparent border-none p-0 {getLocale() ===
                        'en'
                            ? 'opacity-100'
                            : 'opacity-60 hover:opacity-80'}"
                        onclick={() => switchLanguage("en")}
                        aria-label="English"
                    >
                        <svg
                            viewBox="0 0 36 36"
                            class="w-full h-full"
                            aria-hidden="true"
                        >
                            <path
                                fill="#00247D"
                                d="M0 9.059V13h5.628zM4.664 31H13v-5.837zM23 25.164V31h8.335zM0 23v3.941L5.63 23zM31.337 5H23v5.837zM36 26.942V23h-5.631zM36 13V9.059L30.371 13zM13 5H4.664L13 10.837z"
                            ></path>
                            <path
                                fill="#CF1B2B"
                                d="M25.14 23l9.712 6.801a3.977 3.977 0 0 0 .99-1.749L28.627 23H25.14zM13 23h-2.141l-9.711 6.8c.521.53 1.189.909 1.938 1.085L13 23.943V23zm10-10h2.141l9.711-6.8a3.988 3.988 0 0 0-1.937-1.085L23 12.057V13zm-12.141 0L1.148 6.2a3.994 3.994 0 0 0-.991 1.749L7.372 13h3.487z"
                            ></path>
                            <path
                                fill="#EEE"
                                d="M36 21H21v10h2v-5.836L31.335 31H32a3.99 3.99 0 0 0 2.852-1.199L25.14 23h3.487l7.215 5.052c.093-.337.158-.686.158-1.052v-.058L30.369 23H36v-2zM0 21v2h5.63L0 26.941V27c0 1.091.439 2.078 1.148 2.8l9.711-6.8H13v.943l-9.914 6.941c.294.07.598.116.914.116h.664L13 25.163V31h2V21H0zM36 9a3.983 3.983 0 0 0-1.148-2.8L25.141 13H23v-.943l9.915-6.942A4.001 4.001 0 0 0 32 5h-.663L23 10.837V5h-2v10h15v-2h-5.629L36 9.059V9zM13 5v5.837L4.664 5H4a3.985 3.985 0 0 0-2.852 1.2l9.711 6.8H7.372L.157 7.949A3.968 3.968 0 0 0 0 9v.059L5.628 13H0v2h15V5h-2z"
                            ></path>
                            <path
                                fill="#CF1B2B"
                                d="M21 15V5h-6v10H0v6h15v10h6V21h15v-6z"
                            ></path>
                        </svg>
                    </button>
                </div>
            </div>
        </div>

        <!-- Colors Section Title -->
        <div class="flex items-center w-full">
            <h3
                class="text-[28px] text-kv-white uppercase font-kv-body kv-shadow-text"
            >
                {m.kv_settings_colors()}
            </h3>
        </div>

        <!-- Color Swatches -->
        <div class="flex flex-col gap-4 w-full">
            <!-- Primary Color -->
            <div class="flex items-center justify-between w-full">
                <span
                    class="text-2xl text-kv-white uppercase font-kv-body kv-shadow-text"
                >
                    {m.kv_settings_primary()}
                </span>
                <ColorPicker
                    bind:value={themeStore.primary}
                    onchange={(c) => (themeStore.primary = c)}
                />
            </div>
            <!-- Secondary Color -->
            <div class="flex items-center justify-between w-full">
                <span
                    class="text-2xl text-kv-white uppercase font-kv-body kv-shadow-text"
                >
                    {m.kv_settings_secondary()}
                </span>
                <ColorPicker
                    bind:value={themeStore.secondary}
                    onchange={(c) => (themeStore.secondary = c)}
                />
            </div>
            <!-- Text Color -->
            <div class="flex items-center justify-between w-full">
                <span
                    class="text-2xl text-kv-white uppercase font-kv-body kv-shadow-text"
                >
                    {m.kv_settings_text_color()}
                </span>
                <ColorPicker
                    bind:value={themeStore.text}
                    onchange={(c) => (themeStore.text = c)}
                />
            </div>
            <!-- Background Color -->
            <div class="flex items-center justify-between w-full">
                <span
                    class="text-2xl text-kv-white uppercase font-kv-body kv-shadow-text"
                >
                    {m.kv_settings_background()}
                </span>
                <ColorPicker
                    bind:value={themeStore.background}
                    onchange={(c) => (themeStore.background = c)}
                />
            </div>
        </div>

        <!-- Reset Settings Button -->
        <KvButtonPrimary
            onclick={handleResetSettings}
            class="!text-2xl !py-4 !px-4"
        >
            {m.kv_settings_reset()}
        </KvButtonPrimary>

        <!-- Save and Exit Button -->
        <KvButtonSecondary
            onclick={handleSaveAndExit}
            class="!text-2xl !py-4 !px-4"
        >
            {m.kv_settings_save_exit()}
        </KvButtonSecondary>
    </div>

    <!-- Confirmation Dialog -->
    <ConfirmDialog
        bind:open={showConfirmClose}
        title={m.kv_confirm_close_title()}
        message={m.kv_confirm_close_message()}
        confirmText={m.kv_confirm_discard()}
        cancelText={m.kv_confirm_cancel()}
        onconfirm={confirmClose}
        oncancel={cancelClose}
    />
{/if}
