<script lang="ts">
    import { goto } from "@roxi/routify"
    import { invoke } from "@tauri-apps/api/core"
    import { onMount, onDestroy } from "svelte"
    import { currentLanguage, setLanguage, translations, translate } from "@/stores"

    let appVersion = ""
    let commandsCount = 0

    let selectedLang = "?"
    let langDropdownOpen = false

    const languages = [
        { code: "ru", label: "RU", flag: "🇷🇺", name: "Русский" },
        { code: "en", label: "EN", flag: "🇬🇧", name: "English" },
        { code: "ua", label: "UA", flag: "🇺🇦", name: "Українська" },
    ]

    // Profile chip — shows the active profile icon + name, click to swap.
    interface ProfileInfo {
        name: string
        description: string
        icon: string
        greeting: string
    }
    let activeProfile: ProfileInfo | null = null
    let profileNames: string[] = []
    let profileDropdownOpen = false
    let profilePoll: ReturnType<typeof setInterval> | null = null

    async function refreshProfile() {
        try {
            activeProfile = await invoke<ProfileInfo>("profile_active")
        } catch { /* ignore */ }
    }

    async function loadProfileNames() {
        try {
            profileNames = await invoke<string[]>("profile_list")
        } catch { /* ignore */ }
    }

    async function selectProfile(name: string) {
        try {
            activeProfile = await invoke<ProfileInfo>("profile_set", { name })
        } catch (err) {
            console.error("profile set failed:", err)
        }
        profileDropdownOpen = false
    }

    function toggleProfileDropdown(e: MouseEvent) {
        e.stopPropagation()
        if (!profileDropdownOpen) {
            loadProfileNames()
        }
        profileDropdownOpen = !profileDropdownOpen
    }

    onMount(async () => {
        try {
            appVersion = await invoke<string>("get_app_version")
            commandsCount = await invoke<number>("get_commands_count")

            const savedLang = await invoke<string>("db_read", { key: "language" })
            if (savedLang) {
                selectedLang = savedLang
            }
        } catch {
            commandsCount = 0
        }
        refreshProfile()
        loadProfileNames()
        profilePoll = setInterval(refreshProfile, 5000)
    })

    onDestroy(() => {
        if (profilePoll !== null) clearInterval(profilePoll)
    })

    async function selectLanguage(code: string) {
        await setLanguage(code)
        langDropdownOpen = false
    }

    function toggleLangDropdown() {
        langDropdownOpen = !langDropdownOpen
    }

    function closeDropdowns(e: MouseEvent) {
        const target = e.target as HTMLElement
        if (!target.closest('.lang-selector')) {
            langDropdownOpen = false
        }
        if (!target.closest('.profile-selector')) {
            profileDropdownOpen = false
        }
    }

    $: currentLang = languages.find(l => l.code === $currentLanguage) || languages[0]
    $: t = (key: string) => translate($translations, key)
</script>

<svelte:window on:click={closeDropdowns} />

<header id="header" class="header">
    <div class="header-left">
        <div class="logo">
            <a href="/" title="JARVIS">
                <img src="/media/128x128.png" alt="Jarvis Logo" />
            </a>
            <div class="logo-text">
                <span class="logo-title"><a href="/" id="jarvis-logo">&nbsp;</a></span>
                <span class="logo-version"><small>v</small>{appVersion} <span class="v-badge">BETA</span></span>
            </div>
        </div>
    </div>
    
    <div class="header-right">
        {#if activeProfile && activeProfile.name !== 'default'}
            <div class="profile-selector">
                <button
                    class="profile-chip"
                    title="{activeProfile.name} — {activeProfile.description}. Кликни чтобы сменить."
                    on:click|stopPropagation={toggleProfileDropdown}
                >
                    <span class="profile-icon">{activeProfile.icon || '★'}</span>
                    <span class="profile-name">{activeProfile.name}</span>
                </button>
                {#if profileDropdownOpen}
                    <div class="profile-dropdown">
                        {#each profileNames as pname}
                            <button
                                class="profile-option"
                                class:active={pname === activeProfile.name}
                                on:click|stopPropagation={() => selectProfile(pname)}
                            >
                                {pname}
                            </button>
                        {/each}
                    </div>
                {/if}
            </div>
        {:else if activeProfile}
            <div class="profile-selector">
                <button
                    class="profile-chip default"
                    title="Текущий профиль — обычный. Кликни чтобы сменить."
                    on:click|stopPropagation={toggleProfileDropdown}
                >
                    <span class="profile-icon">★</span>
                </button>
                {#if profileDropdownOpen}
                    <div class="profile-dropdown">
                        {#each profileNames as pname}
                            <button
                                class="profile-option"
                                class:active={pname === activeProfile.name}
                                on:click|stopPropagation={() => selectProfile(pname)}
                            >
                                {pname}
                            </button>
                        {/each}
                    </div>
                {/if}
            </div>
        {/if}

        <button class="header-btn" on:click={() => $goto('/commands')}>
            <span class="btn-text">{t('header-commands')}</span>
            <span class="btn-badge purple">{commandsCount}+</span>
        </button>

        <button class="header-btn" on:click={() => $goto('/macros')} title="Voice macros">
            <span class="btn-text">{t('header-macros') || 'Макросы'}</span>
        </button>

        <button class="header-btn" on:click={() => $goto('/scheduler')} title="Scheduled tasks">
            <span class="btn-text">{t('header-scheduler') || 'Расписание'}</span>
        </button>

        <button class="header-btn" on:click={() => $goto('/memory')} title="Long-term memory">
            <span class="btn-text">{t('header-memory') || 'Память'}</span>
        </button>

        <button class="header-btn" on:click={() => $goto('/plugins')} title="User plugins">
            <span class="btn-text">{t('header-plugins') || 'Плагины'}</span>
        </button>

        <button class="header-btn" on:click={() => $goto('/settings')}>
            <span class="btn-text">{t('header-settings')}</span>
        </button>

        <div class="lang-selector">
            <button class="lang-btn" on:click|stopPropagation={toggleLangDropdown}>
                <span class="lang-flag"><img src="/media/flags/{currentLang.label}.png" width="23px" alt="{currentLang.flag}"></span>
            </button>
            
            {#if langDropdownOpen}
                <div class="lang-dropdown">
                    {#each languages as lang}
                        <button 
                            class="lang-option" 
                            class:active={lang.code === $currentLanguage}
                            on:click|stopPropagation={() => selectLanguage(lang.code)}
                        >
                            <span class="lang-flag"><img src="/media/flags/{lang.label}.png" width="20px" alt="{lang.flag}"></span>
                            <span class="lang-name">{lang.name}</span>
                        </button>
                    {/each}
                </div>
            {/if}
        </div>
    </div>
</header>

<style lang="scss">
    .profile-selector {
        position: relative;
        margin-right: 6px;
    }

    .profile-chip {
        display: inline-flex;
        align-items: center;
        gap: 5px;
        padding: 4px 9px;
        background: rgba(255, 168, 60, 0.12);
        border: 1px solid rgba(255, 168, 60, 0.35);
        border-radius: 14px;
        color: #ffa83c;
        font-size: 12px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.15s ease;

        &.default {
            background: rgba(255, 255, 255, 0.04);
            border-color: rgba(255, 255, 255, 0.12);
            color: rgba(255, 255, 255, 0.55);
        }

        &:hover {
            background: rgba(255, 168, 60, 0.22);
            border-color: rgba(255, 168, 60, 0.55);
        }
    }

    .profile-icon {
        font-size: 14px;
        line-height: 1;
    }

    .profile-dropdown {
        position: absolute;
        top: calc(100% + 6px);
        right: 0;
        background: rgba(20, 30, 35, 0.98);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 6px;
        overflow: hidden;
        z-index: 100;
        min-width: 130px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
    }

    .profile-option {
        display: block;
        width: 100%;
        padding: 0.55rem 0.85rem;
        background: transparent;
        border: none;
        color: rgba(255, 255, 255, 0.75);
        font-size: 0.78rem;
        cursor: pointer;
        text-align: left;
        transition: all 0.15s ease;

        &:hover {
            background: rgba(255, 168, 60, 0.12);
            color: #fff;
        }

        &.active {
            background: rgba(255, 168, 60, 0.18);
            color: #ffa83c;
            font-weight: 600;
        }
    }

    .lang-selector {
        position: relative;
    }

    .lang-btn {
        display: flex;
        align-items: center;
        gap: 0.35rem;
        padding: 0.5rem 0.65rem;
        background: transparent;
        border: none;
        border-radius: 6px;
        color: #ffffff;
        font-size: 0.7rem;
        cursor: pointer;

        &:hover {
            background: rgba(35, 50, 55, 0.7);
        }
    }

    .lang-flag {
        font-size: 0.9rem;
        line-height: 1;
    }

    .lang-code {
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    .lang-arrow {
        font-size: 0.8rem;
        opacity: 0.6;
        transition: transform 0.2s ease;

        &.open {
            transform: rotate(180deg);
        }
    }

    .lang-dropdown {
        position: absolute;
        top: calc(100% + 0.35rem);
        right: 0;
        background: rgba(20, 30, 35, 0.98);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 6px;
        overflow: hidden;
        z-index: 100;
        min-width: 130px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
    }

    .lang-option {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        width: 100%;
        padding: 0.6rem 0.85rem;
        background: transparent;
        border: none;
        color: rgba(255, 255, 255, 0.75);
        font-size: 0.75rem;
        cursor: pointer;
        transition: all 0.15s ease;
        text-align: left;

        &:hover {
            background: rgba(82, 254, 254, 0.1);
            color: #ffffff;
        }

        &.active {
            background: rgba(82, 254, 254, 0.15);
            color: #52fefe;
        }
    }

    .lang-name {
        font-weight: 500;
    }
</style>