<script lang="ts">
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { launcher_loc } from '$lib/stores/ae_events_stores__launcher.svelte';
import { cleanup_tmp_files } from '$lib/electron/electron_relay';
import Launcher_Cfg_Section from './launcher_cfg_section.svelte';
import { Bug, BugOff, Eraser, Eye, EyeOff, Wrench } from '@lucide/svelte';
interface Props {
    on_expand?: () => void;
}
let { on_expand }: Props = $props();

let selected_reset = $state('');
let cleanup_status = $state('');

async function handle_cleanup_now() {
    const cache_root = $ae_loc.local_file_cache_path;
    if (!cache_root) {
        cleanup_status = 'Error: Cache path not set.';
        return;
    }
    const max_age_hours = launcher_loc.current.cleanup_tmp_max_age_hours ?? 24;
    cleanup_status = 'Cleaning...';
    const result = await cleanup_tmp_files({
        cache_root,
        max_age_minutes: max_age_hours * 60
    });
    cleanup_status =
        (result as any).success !== false
            ? 'Done.'
            : `Error: ${(result as any).error}`;
    setTimeout(() => (cleanup_status = ''), 4000);
}

function handle_reset_action(val: string) {
    if (!val) return;

    if (val == 'delete_idbs') {
        if (
            confirm('Are you sure you want to delete ALL IndexedDB databases?')
        ) {
            indexedDB.deleteDatabase('ae_archives_db');
            indexedDB.deleteDatabase('ae_core_db');
            indexedDB.deleteDatabase('ae_events_db');
            indexedDB.deleteDatabase('ae_journals_db');
            indexedDB.deleteDatabase('ae_posts_db');
            indexedDB.deleteDatabase('ae_sponsorships_db');
            alert('All IndexedDB databases deleted. Please reload the app.');
        }
    } else if (val == 'delete_idbs_events') {
        if (
            confirm(
                'Are you sure you want to delete ONLY the Events IndexedDB database?'
            )
        ) {
            indexedDB.deleteDatabase('ae_events_db');
            alert('Events IndexedDB database deleted. Please reload the app.');
        }
    } else if (val == 'delete_local') {
        if (confirm('Are you sure you want to delete ALL local config?')) {
            localStorage.removeItem('ae_loc');
            localStorage.removeItem('ae_events_loc');
            localStorage.removeItem('ae_idaa_loc');
            localStorage.removeItem('ae_journals_loc');
            location.reload();
        }
    } else if (val == 'delete_local_events') {
        if (
            confirm(
                'Are you sure you want to delete ONLY the Events local config?'
            )
        ) {
            localStorage.removeItem('ae_events_loc');
            location.reload();
        }
    }
    selected_reset = '';
}
</script>

<Launcher_Cfg_Section
    title="Local Reset & Actions"
    icon={Wrench}
    bind:state={launcher_loc.current.section_state__local_actions}
    {on_expand}
    description="Cache wiping and global menu toggles">
    <div class="col-span-full flex flex-col gap-3">
        <!-- 1. Reset Actions -->
        <div class="flex flex-col gap-1">
            <span
                class="text-error-500 ml-1 text-[9px] font-bold uppercase opacity-50"
                >Maintenance & Resets</span>
            <select
                bind:value={selected_reset}
                onchange={(e) =>
                    handle_reset_action((e.target as HTMLSelectElement).value)}
                class="select select-sm preset-tonal-surface text-error-500 border-error-500/20 h-8 text-xs">
                <option value="">-- Select a reset action --</option>
                <option value="delete_idbs">Delete ALL Databases</option>
                <option value="delete_idbs_events"
                    >Delete Events DB Only</option>
                <option value="delete_local">Wipe ALL Local Storage</option>
                <option value="delete_local_events"
                    >Wipe Events Storage Only</option>
            </select>
            <span class="ml-1 text-[8px] leading-tight italic opacity-40">
                * Destructive actions require browser confirmation.
            </span>
        </div>

        <!-- 2. UI Toggles -->
        <div class="mt-1 grid grid-cols-2 gap-2">
            <button
                type="button"
                onclick={() => ($ae_loc.sys_menu.hide = !$ae_loc.sys_menu.hide)}
                class="btn btn-xs preset-tonal-surface hover:preset-filled-primary-500"
                title="Show/Hide Aether global system menu">
                {#if $ae_loc.sys_menu.hide}<Eye
                        size="1em"
                        class="mr-2" />{:else}<EyeOff
                        size="1em"
                        class="mr-2" />{/if}
                {$ae_loc.sys_menu.hide ? 'Show' : 'Hide'} Sys Menu
            </button>

            <button
                type="button"
                onclick={() =>
                    ($ae_loc.debug_menu.hide = !$ae_loc.debug_menu.hide)}
                class="btn btn-xs preset-tonal-surface hover:preset-filled-primary-500"
                title="Show/Hide Aether global debug menu">
                {#if $ae_loc.debug_menu.hide}<Bug
                        size="1em"
                        class="mr-2" />{:else}<BugOff
                        size="1em"
                        class="mr-2" />{/if}
                {$ae_loc.debug_menu.hide ? 'Show' : 'Hide'} Debug
            </button>
        </div>

        <!-- 3. Cache .tmp Cleanup (Native Only) -->
        {#if $ae_loc.is_native && $ae_loc.local_file_cache_path}
            <div
                class="border-surface-500/20 mt-1 flex flex-col gap-1 border-t pt-2">
                <span class="ml-1 text-[9px] font-bold uppercase opacity-50"
                    >Cache Maintenance</span>
                <div class="flex items-center gap-2">
                    <label
                        for="cleanup_max_age"
                        class="text-[10px] whitespace-nowrap opacity-70"
                        >Max age (hrs):</label>
                    <input
                        id="cleanup_max_age"
                        type="number"
                        min="1"
                        max="168"
                        bind:value={
                            launcher_loc.current.cleanup_tmp_max_age_hours
                        }
                        class="input input-sm preset-tonal-surface h-7 w-16 text-center text-xs"
                        placeholder="24" />
                    <button
                        type="button"
                        onclick={handle_cleanup_now}
                        class="btn btn-xs preset-tonal-warning hover:preset-filled-warning-500 grow">
                        <Eraser size="0.85em" class="mr-1" /> Clean .tmp Now
                    </button>
                </div>
                {#if cleanup_status}
                    <span class="ml-1 text-[9px] italic opacity-60"
                        >{cleanup_status}</span>
                {/if}
                <span class="ml-1 text-[8px] leading-tight italic opacity-40">
                    Removes stale in-progress download artifacts. Auto-runs on
                    startup.
                </span>
            </div>
        {/if}

        <!-- 4. Connection Summary (Edit Mode Only) -->
        {#if $ae_loc.edit_mode}
            <div
                class="border-surface-500/20 col-span-full mt-1 flex flex-col gap-1 border-t pt-2">
                <p class="ml-1 text-[9px] font-bold uppercase opacity-50">
                    API Context
                </p>
                <div
                    class="rounded bg-black/10 p-2 font-mono text-[9px] leading-tight break-all opacity-60">
                    Endpoint: {$ae_api.base_url}<br />
                    Account: {$ae_loc.account_id}
                </div>
            </div>
        {/if}
    </div>
</Launcher_Cfg_Section>
