<script lang="ts">
interface Props {
    log_lvl?: number;
}

let { log_lvl = 0 }: Props = $props();

import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger,
    time
} from '$lib/stores/ae_stores';
import {
    events_sess,
    events_slct,
    events_trigger,
    events_trig
} from '$lib/stores/ae_events_stores';
import { launcher_loc } from '$lib/stores/ae_events_stores__launcher.svelte';

// Sub-components
import Launcher_Cfg_Native_OS from './cfg_components/launcher_cfg_native_os.svelte';
import Launcher_Cfg_Sync_Timers from './cfg_components/launcher_cfg_sync_timers.svelte';
import Launcher_Cfg_Health from './cfg_components/launcher_cfg_health.svelte';
import Launcher_Cfg_Updates from './cfg_components/launcher_cfg_updates.svelte';
import Launcher_Cfg_Controller from './cfg_components/launcher_cfg_controller.svelte';
import Launcher_Cfg_Screen_Saver from './cfg_components/launcher_cfg_screen_saver.svelte';
import Launcher_Cfg_App_Modes from './cfg_components/launcher_cfg_app_modes.svelte';
import Launcher_Cfg_Local_Actions from './cfg_components/launcher_cfg_local_actions.svelte';
import Launcher_Cfg_Launch_Timing from './cfg_components/launcher_cfg_launch_timing.svelte';
import Launcher_Cfg_Wallpaper from './cfg_components/launcher_cfg_wallpaper.svelte';
import {
    Bug,
    Code,
    Gamepad2,
    Image,
    LayoutGrid,
    Monitor,
    Pencil,
    RefreshCw,
    Settings,
    Wrench,
    X
} from '@lucide/svelte';

// UI Tab State
type TabId =
    | 'general'
    | 'connectivity'
    | 'sync'
    | 'native'
    | 'wallpaper'
    | 'advanced'
    | 'maintenance';
let active_tab: TabId = $state('general');

const TABS = [
    {
        id: 'general' as TabId,
        label: 'General',
        icon: LayoutGrid,
        title: 'App Modes, UI & Screen Saver'
    },
    {
        id: 'connectivity' as TabId,
        label: 'Connectivity',
        icon: Gamepad2,
        title: 'Remote Controller & WebSocket'
    },
    {
        id: 'sync' as TabId,
        label: 'Sync & Health',
        icon: RefreshCw,
        title: 'Sync Engine & System Status'
    },
    {
        id: 'native' as TabId,
        label: 'Native OS',
        icon: Monitor,
        title: 'Folders, Displays & Native Apps'
    },
    {
        id: 'wallpaper' as TabId,
        label: 'Wallpaper',
        icon: Image,
        title: 'Desktop Wallpaper Settings'
    },
    {
        id: 'advanced' as TabId,
        label: 'Advanced',
        icon: Code,
        title: 'Launch Timing & Updates',
        edit_only: true
    },
    {
        id: 'maintenance' as TabId,
        label: 'Maintenance',
        icon: Wrench,
        title: 'Local Resets & Debug Tools',
        edit_only: true
    }
];

/**
 * Auto-Collapse Coordinator
 * When a section is opened in 'auto' mode, collapse all other 'auto' sections.
 * Pinned sections are ignored and remain open.
 */
function handle_section_expand(current_key: string) {
    const launcher = launcher_loc.current;
    Object.keys(launcher).forEach((key) => {
        if (
            key.startsWith('section_state__') &&
            key !== `section_state__${current_key}`
        ) {
            if (launcher[key] === 'auto') {
                launcher[key] = 'collapsed';
            }
        }
    });
    launcher_loc.current = launcher; // Trigger store update
}

const current_tab_info = $derived(TABS.find((t) => t.id === active_tab));
</script>

<div
    class="bg-surface-100-900 flex h-full min-h-[500px] w-full flex-row overflow-hidden">
    <!-- Sidebar Navigation -->
    <div
        class="bg-surface-500/5 flex w-48 flex-shrink-0 flex-col border-r border-surface-500/20 p-2">
        <div class="mb-4 flex items-center gap-2 px-2 py-3">
            <Settings size="1.2em" class="text-primary-500" />
            <span class="text-xs font-bold tracking-widest uppercase opacity-80"
                >Launcher</span>
        </div>

        <nav class="flex flex-grow flex-col gap-1">
            {#each TABS as tab}
                {#if !tab.edit_only || $ae_loc.edit_mode}
                    <button
                        type="button"
                        onclick={() => (active_tab = tab.id)}
                        class="btn btn-sm justify-start gap-3 px-3 py-2 text-[11px] font-medium transition-all"
                        class:preset-filled-primary={active_tab === tab.id}
                        class:preset-tonal-surface={active_tab !== tab.id}
                        class:hover:preset-tonal-primary={active_tab !==
                            tab.id}>
                        <tab.icon size="1.1em" class="shrink-0" />
                        {tab.label}
                    </button>
                {/if}
            {/each}
        </nav>

        <div class="mt-auto flex flex-col gap-2 p-1">
            <button
                type="button"
                onclick={() => ($ae_loc.edit_mode = !$ae_loc.edit_mode)}
                class="btn btn-sm justify-start gap-3 px-3 py-2 text-[10px] font-medium transition-all"
                class:text-primary-500={$ae_loc.edit_mode}
                class:opacity-50={!$ae_loc.edit_mode}
                title="{$ae_loc.edit_mode ? 'Disable' : 'Enable'} Technical Mode">
                <Pencil size="1em" />
                <span>Technical Mode</span>
            </button>

            <button
                type="button"
                onclick={() => (launcher_loc.current.hide_drawer__cfg = true)}
                class="btn btn-sm preset-tonal-surface hover:preset-filled-surface-500 justify-start gap-3 px-3 py-2 text-[10px] transition-all">
                <X size="1em" />
                <span>Close Settings</span>
            </button>
        </div>
    </div>

    <!-- Main Content Area -->
    <div class="flex flex-grow flex-col overflow-hidden">
        <!-- Tab Header -->
        <header
            class="border-surface-500/10 flex flex-shrink-0 items-center justify-between border-b px-6 py-4">
            <div class="flex flex-col">
                <h2 class="text-lg font-bold text-gray-800 dark:text-gray-100">
                    {current_tab_info?.label}
                </h2>
                <p class="text-[10px] opacity-50">{current_tab_info?.title}</p>
            </div>

            <div class="flex items-center gap-2">
                <button
                    type="button"
                    onclick={() => location.reload()}
                    class="btn btn-sm preset-tonal-surface hover:preset-tonal-secondary text-[10px] font-bold"
                    title="Reload Application">
                    <RefreshCw size="1em" class="mr-1" /> Reload
                </button>
            </div>
        </header>

        <div class="flex-grow overflow-y-auto p-6">
            {#key active_tab}
                <div class="mx-auto flex w-full max-w-2xl flex-col gap-6">
                    {#if active_tab === 'general'}
                        <div
                            class="animate-in fade-in slide-in-from-bottom-2 flex flex-col gap-6 duration-300">
                            <Launcher_Cfg_App_Modes
                                on_expand={() =>
                                    handle_section_expand('app_modes')} />
                            <Launcher_Cfg_Screen_Saver
                                on_expand={() =>
                                    handle_section_expand('screen_saver')} />
                        </div>
                    {/if}

                    {#if active_tab === 'connectivity'}
                        <div
                            class="animate-in fade-in slide-in-from-bottom-2 flex flex-col gap-6 duration-300">
                            <Launcher_Cfg_Controller
                                on_expand={() =>
                                    handle_section_expand('controller')} />
                        </div>
                    {/if}

                    {#if active_tab === 'sync'}
                        <div
                            class="animate-in fade-in slide-in-from-bottom-2 flex flex-col gap-6 duration-300">
                            <Launcher_Cfg_Sync_Timers
                                on_expand={() =>
                                    handle_section_expand('sync_timers')} />
                            <Launcher_Cfg_Health
                                on_expand={() =>
                                    handle_section_expand('health')} />
                        </div>
                    {/if}

                    {#if active_tab === 'native'}
                        <div
                            class="animate-in fade-in slide-in-from-bottom-2 flex flex-col gap-6 duration-300">
                            {#if $ae_loc.is_native || $ae_loc.edit_mode}
                                <Launcher_Cfg_Native_OS
                                    on_expand={() =>
                                        handle_section_expand('native_os')} />
                            {:else}
                                <div
                                    class="flex flex-col items-center gap-3 py-12 text-center text-sm italic opacity-40">
                                    <Monitor size="3em" class="opacity-20" />
                                    <div class="flex flex-col gap-1">
                                        <p>
                                            Native OS controls are only
                                            available when running in Aether
                                            Desktop.
                                        </p>
                                        <p class="text-[10px]">
                                            Enable Technical Mode to preview
                                            layout.
                                        </p>
                                    </div>
                                </div>
                            {/if}
                        </div>
                    {/if}

                    {#if active_tab === 'wallpaper'}
                        <div
                            class="animate-in fade-in slide-in-from-bottom-2 flex flex-col gap-6 duration-300">
                            <Launcher_Cfg_Wallpaper
                                on_expand={() =>
                                    handle_section_expand('wallpaper')} />
                        </div>
                    {/if}

                    {#if active_tab === 'advanced' && $ae_loc.edit_mode}
                        <div
                            class="animate-in fade-in slide-in-from-bottom-2 flex flex-col gap-6 duration-300">
                            <Launcher_Cfg_Launch_Timing
                                on_expand={() =>
                                    handle_section_expand('launch_timing')} />
                            {#if $ae_loc.is_native || $ae_loc.edit_mode}
                                <Launcher_Cfg_Updates
                                    on_expand={() =>
                                        handle_section_expand('updates')} />
                            {/if}
                        </div>
                    {/if}

                    {#if active_tab === 'maintenance' && $ae_loc.edit_mode}
                        <div
                            class="animate-in fade-in slide-in-from-bottom-2 flex flex-col gap-6 duration-300">
                            <Launcher_Cfg_Local_Actions
                                on_expand={() =>
                                    handle_section_expand('local_actions')} />

                            <div class="flex flex-col gap-2">
                                <p
                                    class="ml-1 text-[9px] font-bold uppercase opacity-50">
                                    Debug Access
                                </p>
                                <button
                                    type="button"
                                    onclick={() =>
                                        (launcher_loc.current.hide_drawer__debug = false)}
                                    class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500 w-full transition-all">
                                    <Bug size="1.2em" class="mr-2" />
                                    Open Debug Panel
                                </button>
                            </div>
                        </div>
                    {/if}
                </div>
            {/key}
        </div>

        <!-- Content Footer -->
        <footer
            class="border-surface-500/10 flex flex-shrink-0 items-center justify-between border-t px-6 py-3">
            <p class="text-[9px] font-bold tracking-widest uppercase opacity-30">
                Aether Platform &bull; Events Launcher v3.1
            </p>
            <div class="flex items-center gap-4 text-[9px] opacity-40">
                <span>Account: {$ae_loc.account_id || 'None'}</span>
                <span
                    >Device: {$ae_loc.native_device?.event_device_id ||
                        'Web'}</span
                >
            </div>
        </footer>
    </div>
</div>
