<script lang="ts">
import { untrack } from 'svelte';
/**
 * AE_Comp_Site_Config_Editor.svelte
 * Specialized UI for managing site.cfg_json settings.
 * Supports General, AI, Performance, and IDAA-specific configurations.
 */
import {
    Brain,
    CodeXml,
    ExternalLink,
    Eye,
    EyeOff,
    Globe,
    Mail,
    Minus,
    Palette,
    Plus,
    Save,
    ShieldCheck,
    Timer
} from '@lucide/svelte';
import AE_Comp_Editor_CodeMirror from '$lib/elements/element_editor_codemirror.svelte';
import { ae_loc } from '$lib/stores/ae_stores';

interface Props {
    cfg_json: any;
    on_save?: () => void;
}

let { cfg_json = $bindable({}), on_save }: Props = $props();

// Ensure we have a valid object (handle strings/nulls)
$effect(() => {
    if (typeof cfg_json === 'string') {
        try {
            cfg_json = JSON.parse(cfg_json);
        } catch {
            cfg_json = {};
        }
    }
    if (!cfg_json) cfg_json = {};
});

// Internal State
let active_tab: 'visuals' | 'email' | 'ai' | 'refresh' | 'idaa' | 'raw' =
    $state('visuals');
let raw_json_str = $state('');
let show_llm_api_token = $state(false);

// Ensure we have a valid object
if (!cfg_json) cfg_json = {};

function add_to_list(key: string, prompt_label: string) {
    if (!cfg_json[key]) cfg_json[key] = [];
    const val = prompt(prompt_label);
    if (val) cfg_json[key].push(val);
}

function remove_from_list(key: string, index: number) {
    cfg_json[key].splice(index, 1);
}

function list_count(key: string): number {
    return Array.isArray(cfg_json[key]) ? cfg_json[key].length : 0;
}

// Sync Raw JSON string when entering the tab
$effect(() => {
    if (active_tab === 'raw') {
        untrack(() => {
            raw_json_str = JSON.stringify(cfg_json, null, 2);
        });
    }
});

// Update cfg_json when raw string changes
$effect(() => {
    if (active_tab === 'raw' && raw_json_str) {
        try {
            const parsed = JSON.parse(raw_json_str);
            cfg_json = parsed;
        } catch {
            // Ignore invalid JSON while typing
        }
    }
});
</script>

<div class="ae-site-config-editor flex h-full flex-col space-y-4">
    <!-- Tab Navigation -->
    <div
        class="bg-surface-500/10 flex max-w-fit flex-wrap gap-1 rounded-lg p-1">
        <button
            class="btn btn-sm transition-all {active_tab === 'visuals'
                ? 'variant-filled-primary'
                : 'variant-soft-surface'}"
            onclick={() => (active_tab = 'visuals')}>
            <Palette size="1.1em" class="mr-1" /> Visuals
        </button>
        <button
            class="btn btn-sm transition-all {active_tab === 'email'
                ? 'variant-filled-primary'
                : 'variant-soft-surface'}"
            onclick={() => (active_tab = 'email')}>
            <Mail size="1.1em" class="mr-1" /> Email
        </button>
        <button
            class="btn btn-sm transition-all {active_tab === 'ai'
                ? 'variant-filled-primary'
                : 'variant-soft-surface'}"
            onclick={() => (active_tab = 'ai')}>
            <Brain size="1.1em" class="mr-1" /> AI/LLM
        </button>
        <button
            class="btn btn-sm transition-all {active_tab === 'refresh'
                ? 'variant-filled-primary'
                : 'variant-soft-surface'}"
            onclick={() => (active_tab = 'refresh')}>
            <Timer size="1.1em" class="mr-1" /> Refresh
        </button>
        <button
            class="btn btn-sm transition-all {active_tab === 'idaa'
                ? 'variant-filled-primary'
                : 'variant-soft-surface'}"
            onclick={() => (active_tab = 'idaa')}>
            <ShieldCheck size="1.1em" class="mr-1" /> IDAA
        </button>
        <button
            class="btn btn-sm transition-all {active_tab === 'raw'
                ? 'variant-filled-primary'
                : 'variant-soft-surface'}"
            onclick={() => (active_tab = 'raw')}>
            <CodeXml size="1.1em" class="mr-1" /> Raw JSON
        </button>
    </div>

    <!-- Scrollable Content Area -->
    <div class="max-h-[60vh] grow space-y-6 overflow-y-auto p-1 pr-2">
        {#if active_tab === 'visuals'}
            <div
                class="animate-in fade-in grid grid-cols-1 gap-4 duration-200 md:grid-cols-2">
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Theme Name</span>
                    <input
                        type="text"
                        bind:value={cfg_json.theme_name}
                        class="input variant-form-material"
                        placeholder="e.g. AE_OSIT_default" />
                </label>
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Theme Mode</span>
                    <select
                        bind:value={cfg_json.theme_mode}
                        class="select variant-form-material">
                        <option value="light">Light</option>
                        <option value="dark">Dark</option>
                        <option value="auto">Auto (System)</option>
                    </select>
                </label>
                <label class="label md:col-span-2">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Header Image Path (URL)</span>
                    <div class="flex gap-2">
                        <input
                            type="text"
                            bind:value={cfg_json.header_image_path}
                            class="input variant-form-material grow"
                            placeholder="https://..." />
                        {#if cfg_json.header_image_path}
                            <a
                                href={cfg_json.header_image_path}
                                target="_blank"
                                rel="noopener noreferrer"
                                class="btn-icon variant-soft-surface"
                                ><ExternalLink size="1.2em" /></a>
                        {/if}
                    </div>
                </label>
            </div>
        {:else if active_tab === 'email'}
            <div
                class="animate-in fade-in grid grid-cols-1 gap-4 duration-200 md:grid-cols-2">
                <section class="border-surface-500/10 space-y-4 border-r pr-4">
                    <h4 class="text-primary-500 text-sm font-black">
                        Admin Contact
                    </h4>
                    <label class="label">
                        <span class="text-xs font-bold uppercase opacity-50"
                            >Admin Name</span>
                        <input
                            type="text"
                            bind:value={cfg_json.admin_name}
                            class="input variant-form-material" />
                    </label>
                    <label class="label">
                        <span class="text-xs font-bold uppercase opacity-50"
                            >Admin Email</span>
                        <input
                            type="email"
                            bind:value={cfg_json.admin_email}
                            class="input variant-form-material" />
                    </label>
                </section>
                <section class="space-y-4">
                    <h4 class="text-secondary-500 text-sm font-black">
                        System (No-Reply)
                    </h4>
                    <label class="label">
                        <span class="text-xs font-bold uppercase opacity-50"
                            >No-Reply Name</span>
                        <input
                            type="text"
                            bind:value={cfg_json.noreply_name}
                            class="input variant-form-material" />
                    </label>
                    <label class="label">
                        <span class="text-xs font-bold uppercase opacity-50"
                            >No-Reply Email</span>
                        <input
                            type="email"
                            bind:value={cfg_json.noreply_email}
                            class="input variant-form-material" />
                    </label>
                </section>
            </div>
        {:else if active_tab === 'ai'}
            <div class="animate-in fade-in space-y-4 duration-200">
                <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                    <label class="label">
                        <span class="text-xs font-bold uppercase opacity-50"
                            >LLM API Base URL</span>
                        <input
                            type="text"
                            bind:value={cfg_json.llm__api_base_url}
                            class="input variant-form-material" />
                    </label>
                    <label class="label">
                        <span class="text-xs font-bold uppercase opacity-50"
                            >LLM Model</span>
                        <input
                            type="text"
                            autocomplete="off"
                            autocapitalize="off"
                            autocorrect="off"
                            spellcheck="false"
                            name="site_llm_model"
                            data-bwignore="true"
                            data-lpignore="true"
                            data-1p-ignore="true"
                            bind:value={cfg_json.llm__api_model}
                            class="input variant-form-material" />
                    </label>
                </div>
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >API Token</span>
                    <div class="flex gap-2">
                        <input
                            type={show_llm_api_token ? 'text' : 'password'}
                            autocomplete="off"
                            autocapitalize="off"
                            autocorrect="off"
                            spellcheck="false"
                            name="site_llm_api_token"
                            data-bwignore="true"
                            data-lpignore="true"
                            data-1p-ignore="true"
                            bind:value={cfg_json.llm__api_token}
                            class="input variant-form-material grow font-mono" />
                        <button
                            type="button"
                            class="btn btn-sm variant-soft-surface"
                            onclick={() =>
                                (show_llm_api_token = !show_llm_api_token)}
                            title={show_llm_api_token
                                ? 'Hide API Token'
                                : 'Show API Token'}>
                            {#if show_llm_api_token}
                                <EyeOff size="1.1em" />
                            {:else}
                                <Eye size="1.1em" />
                            {/if}
                        </button>
                    </div>
                </label>
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >System Prompt</span>
                    <textarea
                        bind:value={cfg_json.llm__system_prompt}
                        class="textarea variant-form-material h-24 text-sm"
                    ></textarea>
                </label>
                <label class="flex items-center space-x-2">
                    <input
                        type="checkbox"
                        bind:checked={cfg_json.llm__api_dangerous_browser}
                        class="checkbox" />
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Allow Browser Fetch (Dangerously)</span>
                </label>
            </div>
        {:else if active_tab === 'refresh'}
            <div
                class="animate-in fade-in grid grid-cols-1 gap-4 duration-200 md:grid-cols-2">
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Default (Minutes)</span>
                    <input
                        type="number"
                        bind:value={cfg_json.default_refresh_minutes}
                        class="input variant-form-material" />
                </label>
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Authenticated (Minutes)</span>
                    <input
                        type="number"
                        bind:value={cfg_json.authenticated_refresh_time}
                        class="input variant-form-material" />
                </label>
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Trusted (Minutes)</span>
                    <input
                        type="number"
                        bind:value={cfg_json.trusted_refresh_minutes}
                        class="input variant-form-material" />
                </label>
                <label class="label">
                    <span class="text-xs font-bold uppercase opacity-50"
                        >Manager (Minutes)</span>
                    <input
                        type="number"
                        bind:value={cfg_json.manager_refresh_minutes}
                        class="input variant-form-material" />
                </label>
            </div>
        {:else if active_tab === 'idaa'}
            <div class="animate-in fade-in space-y-6 duration-200">
                <!-- Novi API -->
                <section
                    class="bg-surface-500/5 border-surface-500/10 space-y-4 rounded-xl border p-4">
                    <h4 class="flex items-center gap-2 text-sm font-black">
                        <Globe size="1.1em" class="text-primary-500" /> Novi API Connection
                    </h4>
                    <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                        <label class="label">
                            <span class="text-xs font-bold uppercase opacity-50"
                                >Root URL</span>
                            <input
                                type="text"
                                bind:value={cfg_json.novi_api_root_url}
                                class="input variant-form-material" />
                        </label>
                        <label class="label">
                            <span class="text-xs font-bold uppercase opacity-50"
                                >API Key</span>
                            <input
                                type="password"
                                bind:value={cfg_json.novi_idaa_api_key}
                                class="input variant-form-material font-mono" />
                        </label>
                    </div>
                </section>

                <!-- UUID Lists -->
                <section class="grid grid-cols-1 gap-4 md:grid-cols-2">
                    {#each [{ key: 'novi_admin_li', label: 'Novi Admins', color: 'text-error-500', prompt: 'Enter Novi UUID:' }, { key: 'novi_trusted_li', label: 'Novi Trusted', color: 'text-warning-500', prompt: 'Enter Novi UUID:' }, { key: 'novi_jitsi_mod_li', label: 'Jitsi Moderators', color: 'text-primary-500', prompt: 'Enter Novi UUID:' }, { key: 'novi_idaa_group_guid_li', label: 'Member Group GUIDs', color: 'text-secondary-500', prompt: 'Enter Group GUID:' }, { key: 'jitsi_exclude_uuids', label: 'Jitsi Excluded UUIDs', color: 'text-error-500', prompt: 'Enter Novi UUID to exclude:' }, { key: 'jitsi_known_meetings', label: 'Known IDAA Meetings', color: 'text-primary-500', prompt: 'Enter meeting name to allow:' }] as list (list.key)}
                        <details class="bg-surface-500/5 rounded-lg p-3">
                            <summary
                                class="flex cursor-pointer list-none items-center justify-between gap-2 [&::-webkit-details-marker]:hidden">
                                <span class="min-w-0">
                                    <span
                                        class="text-[10px] font-black tracking-wider uppercase {list.color}"
                                        >{list.label}</span>
                                    <span class="ml-2 text-[10px] opacity-50"
                                        >({list_count(list.key)})</span>
                                </span>
                                <button
                                    class="btn btn-icon btn-icon-sm variant-soft-primary"
                                    onclick={(e) => {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        add_to_list(list.key, list.prompt);
                                    }}>
                                    <Plus size="12" />
                                </button>
                            </summary>
                            <div class="mt-3 space-y-1">
                                {#each cfg_json[list.key] ?? [] as item, i (i)}
                                    <div
                                        class="bg-surface-500/10 flex items-center gap-1 rounded p-1 font-mono text-[10px]">
                                        <span class="grow truncate">{item}</span>
                                        <button
                                            class="text-error-500 transition-transform hover:scale-110"
                                            onclick={() =>
                                                remove_from_list(list.key, i)}>
                                            <Minus size="12" />
                                        </button>
                                    </div>
                                {/each}
                            </div>
                        </details>
                    {/each}
                </section>

                <!-- Notifications -->
                <section
                    class="bg-surface-500/5 grid grid-cols-1 gap-4 rounded-xl p-4 md:grid-cols-2">
                    <div class="space-y-2">
                        <h4 class="text-[10px] font-black uppercase opacity-50">
                            Bulletin Board
                        </h4>
                        <label class="flex items-center space-x-2 text-xs">
                            <input
                                type="checkbox"
                                bind:checked={cfg_json.bb_send_staff_new_email}
                                class="checkbox checkbox-sm" />
                            <span>Notify Staff (New)</span>
                        </label>
                        <label class="flex items-center space-x-2 text-xs">
                            <input
                                type="checkbox"
                                bind:checked={
                                    cfg_json.bb_send_staff_update_email
                                }
                                class="checkbox checkbox-sm" />
                            <span>Notify Staff (Update)</span>
                        </label>
                        <label class="flex items-center space-x-2 text-xs">
                            <input
                                type="checkbox"
                                bind:checked={cfg_json.bb_send_poster_email}
                                class="checkbox checkbox-sm" />
                            <span>Notify Poster</span>
                        </label>
                        <label class="flex items-center space-x-2 text-xs">
                            <input
                                type="checkbox"
                                bind:checked={cfg_json.bb_send_commenter_email}
                                class="checkbox checkbox-sm" />
                            <span>Notify Commenters</span>
                        </label>
                    </div>
                    <div class="space-y-2">
                        <h4 class="text-[10px] font-black uppercase opacity-50">
                            Recovery Meetings
                        </h4>
                        <label class="flex items-center space-x-2 text-xs">
                            <input
                                type="checkbox"
                                bind:checked={
                                    cfg_json.recovery_mtg_send_staff_new_email
                                }
                                class="checkbox checkbox-sm" />
                            <span>Notify Staff (New)</span>
                        </label>
                        <label class="flex items-center space-x-2 text-xs">
                            <input
                                type="checkbox"
                                bind:checked={
                                    cfg_json.recovery_mtg_send_staff_update_email
                                }
                                class="checkbox checkbox-sm" />
                            <span>Notify Staff (Update)</span>
                        </label>
                    </div>
                </section>
            </div>
        {:else if active_tab === 'raw'}
            <div class="animate-in fade-in h-[50vh] duration-200">
                <AE_Comp_Editor_CodeMirror
                    content={raw_json_str}
                    bind:new_content={raw_json_str}
                    language="json"
                    theme_mode={$ae_loc.theme_mode}
                    class_li="h-full border border-surface-500/20 rounded-lg shadow-inner" />
            </div>
        {/if}
    </div>

    <!-- Action Bar -->
    <div
        class="border-surface-500/10 flex items-center justify-between border-t pt-4">
        <div class="flex items-center gap-2">
            <label class="flex cursor-pointer items-center space-x-2">
                <input
                    type="checkbox"
                    bind:checked={cfg_json.test}
                    class="checkbox" />
                <span class="text-warning-500 text-xs font-bold uppercase"
                    >Test Mode</span>
            </label>
        </div>
        <button
            class="btn btn-sm variant-filled-primary font-bold shadow-lg"
            onclick={on_save}>
            <Save size="1.1em" class="mr-2" /> Save Config
        </button>
    </div>
</div>
