<script lang="ts">
import { untrack } from 'svelte';
/**
 * ae_comp__modal_journal_config.svelte
 * Standardized Module-level settings for Journals.
 * Fixed Svelte 5 state placement and reactivity loops.
 */
import {
    CalendarClock,
    Check,
    CircleAlert,
    CodeXml,
    Database,
    MousePointerClick,
    Settings,
    ShieldCheck,
    Wrench,
    X
} from '@lucide/svelte';
import { Modal } from 'flowbite-svelte';

// *** Import Aether specific variables and functions
import { ae_loc } from '$lib/stores/ae_stores';
import type { key_val } from '$lib/stores/ae_stores';
import {
    journals_loc,
    journals_sess
} from '$lib/ae_journals/ae_journals_stores';
import AE_Comp_Editor_CodeMirror from '$lib/elements/element_editor_codemirror.svelte';

interface Props {
    show?: boolean;
}

let { show = $bindable(false) }: Props = $props();

// Internal State
let tab: 'config' | 'local_json' | 'session_json' = $state('config');
let tmp_config: key_val = $state({
    journal: {},
    entry: {}
});

const panel_class =
    'space-y-4 rounded-xl border border-surface-500/20 bg-surface-500/5 p-4 shadow-sm';
const panel_title_class =
    'flex items-center gap-2 border-b border-surface-500/20 pb-2 text-lg font-bold';
const field_card_class =
    'bg-surface-500/5 border-surface-500/10 flex cursor-pointer items-center space-x-3 rounded-lg border p-3 transition-colors hover:bg-surface-500/10';
const tab_button_base_class = 'btn btn-sm border transition-all duration-200';
const tab_button_active_class =
    'border-surface-200-800 bg-surface-200-800 text-surface-950-50 shadow-sm';
const tab_button_inactive_class =
    'border-transparent bg-surface-50-900/60 text-surface-600-400 hover:border-surface-200-800 hover:bg-surface-100-900 hover:text-surface-950-50';

function tab_button_class(is_active: boolean): string {
    return `${tab_button_base_class} ${is_active ? tab_button_active_class : tab_button_inactive_class}`;
}

$effect(() => {
    if (show) {
        untrack(() => {
            const fresh_config = JSON.parse(JSON.stringify($journals_loc));
            // Ensure the structure is preserved
            if (!fresh_config.entry) fresh_config.entry = {};
            tmp_config = fresh_config;
        });
    }
});

function handle_save() {
    journals_loc.set(tmp_config);
    show = false;
}
</script>

<Modal
    bind:open={show}
    autoclose={false}
    dismissable={false}
    placement="top-center"
    size="xl"
    class="border-surface-200-800 bg-surface-50-900 text-surface-950-50 relative mx-auto flex h-[calc(100dvh-2rem)] max-h-[calc(100dvh-2rem)] w-full flex-col rounded-xl border shadow-xl"
    headerClass="flex w-full flex-row items-center justify-between gap-2 rounded-t-xl border-b border-surface-200-800 bg-surface-100-900 p-4"
    footerClass="flex w-full flex-row items-center justify-center gap-2 rounded-b-xl border-t border-surface-200-800 bg-surface-100-900 p-4">
    {#snippet header()}
        <h3 class="flex flex-1 items-center gap-2 text-lg font-bold">
            <Wrench class="text-primary-500" />
            <span>&AElig; Journals Module Config</span>
        </h3>
        <button
            type="button"
            class="btn-icon btn-icon-sm preset-tonal-surface ml-2"
            onclick={() => (show = false)}>
            <X size="1.1em" />
        </button>
    {/snippet}

    <div class="min-h-0 flex-1 space-y-6 overflow-y-auto px-4 py-3">
        <!-- Navigation Tabs -->
        <div
            class="bg-surface-500/10 sticky top-0 z-10 mx-auto mb-4 flex max-w-fit justify-center gap-1 rounded-lg p-1 backdrop-blur-sm">
            <button
                type="button"
                class={tab_button_class(tab === 'config')}
                onclick={() => (tab = 'config')}>
                <Settings size="1.1em" class="mr-1" /> Config
            </button>
            <button
                type="button"
                class={tab_button_class(tab === 'local_json')}
                onclick={() => (tab = 'local_json')}>
                <Database size="1.1em" class="mr-1" /> Local JSON
            </button>
            <button
                type="button"
                class={tab_button_class(tab === 'session_json')}
                onclick={() => (tab = 'session_json')}>
                <CodeXml size="1.1em" class="mr-1" /> Session JSON
            </button>
        </div>

        {#if tab === 'config'}
            <div class="animate-in fade-in space-y-4 duration-300">
                <!-- Date/Time Section -->
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <CalendarClock size="1.2em" class="text-primary-500" />
                        Date and Time Display
                    </h2>
                    <div class="grid grid-cols-1 gap-4 p-2 md:grid-cols-2">
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >DateTime Format</span>
                            <select
                                bind:value={tmp_config.datetime_format}
                                class="select select-sm">
                                <option value="datetime_12_short"
                                    >MMM D, YY hh:mm A</option>
                                <option value="datetime_12_long"
                                    >MMMM D, YYYY hh:mm A</option>
                                <option value="datetime_short"
                                    >MMM D, YY HH:mm</option>
                                <option value="datetime_long"
                                    >MMMM D, YYYY HH:mm</option>
                                <option value="datetime_us"
                                    >US (MM/DD/YYYY hh:mm:ss A)</option>
                                <option value="datetime_iso"
                                    >ISO (YYYY-MM-DD HH:mm:ss)</option>
                            </select>
                        </label>
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Time-Only Format</span>
                            <select
                                bind:value={tmp_config.time_format}
                                class="select select-sm">
                                <option value="time_12_short"
                                    >12-hour short (3:30 PM)</option>
                                <option value="time_12_long"
                                    >12-hour long (3:30:45 PM)</option>
                                <option value="time_short"
                                    >24-hour short (15:30)</option>
                                <option value="time_long"
                                    >24-hour long (15:30:45)</option>
                            </select>
                        </label>
                    </div>
                </section>

                <!-- UI Section -->
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <MousePointerClick
                            size="1.2em"
                            class="text-primary-500" />
                        User Interface Preferences
                    </h2>
                    <div class="grid grid-cols-1 gap-4 p-2 md:grid-cols-2">
                        <label class={field_card_class}>
                            <input
                                type="checkbox"
                                bind:checked={tmp_config.entry.auto_save}
                                class="checkbox" />
                            <div class="space-y-0.5">
                                <span class="font-bold">Enable Auto-Save</span>
                                <p class="text-xs opacity-60">
                                    Automatically sync changes while editing
                                </p>
                            </div>
                        </label>
                        <label class={field_card_class}>
                            <input
                                type="checkbox"
                                bind:checked={tmp_config.show_id_random}
                                class="checkbox" />
                            <div class="space-y-0.5">
                                <span class="font-bold"
                                    >Show Technical IDs</span>
                                <p class="text-xs opacity-60">
                                    Display UUIDs in metadata footers
                                </p>
                            </div>
                        </label>
                    </div>
                </section>

                <!-- Journal Query Filters Section -->
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <Database size="1.2em" class="text-primary-500" />
                        Journal Query Filters
                    </h2>
                    <div class="grid grid-cols-1 gap-4 p-2 md:grid-cols-3">
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Enabled Status</span>
                            <select
                                bind:value={tmp_config.journal.qry__enabled}
                                class="select select-sm">
                                <option value="enabled">Enabled Only</option>
                                <option value="not_enabled"
                                    >Disabled Only</option>
                                <option value="all"
                                    >All (Enabled & Disabled & NULL)</option>
                            </select>
                        </label>
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Hidden Status</span>
                            <select
                                bind:value={tmp_config.journal.qry__hidden}
                                class="select select-sm">
                                <option value="not_hidden">Visible Only</option>
                                <option value="hidden">Hidden Only</option>
                                <option value="all"
                                    >All (Visible & Hidden & NULL)</option>
                            </select>
                        </label>
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Query Limit</span>
                            <select
                                bind:value={tmp_config.journal.qry__limit}
                                class="select select-sm">
                                <option value={10}>10</option>
                                <option value={20}>20</option>
                                <option value={50}>50</option>
                                <option value={100}>100</option>
                                <option value={250}>250</option>
                                <option value={500}>500</option>
                                <option value={1000}>1000</option>
                            </select>
                        </label>
                    </div>
                </section>

                <!-- Entry Query Filters Section -->
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <Database size="1.2em" class="text-primary-500" />
                        Entry Query Filters
                    </h2>
                    <div class="grid grid-cols-1 gap-4 p-2 md:grid-cols-3">
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Enabled Status</span>
                            <select
                                bind:value={tmp_config.entry.qry__enabled}
                                class="select select-sm">
                                <option value="enabled">Enabled Only</option>
                                <option value="not_enabled"
                                    >Disabled Only</option>
                                <option value="all"
                                    >All (Enabled & Disabled & NULL)</option>
                            </select>
                        </label>
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Hidden Status</span>
                            <select
                                bind:value={tmp_config.entry.qry__hidden}
                                class="select select-sm">
                                <option value="not_hidden">Visible Only</option>
                                <option value="hidden">Hidden Only</option>
                                <option value="all"
                                    >All (Visible & Hidden & NULL)</option>
                            </select>
                        </label>
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Query Limit</span>
                            <select
                                bind:value={tmp_config.entry.qry__limit}
                                class="select select-sm">
                                <option value={10}>10</option>
                                <option value={20}>20</option>
                                <option value={50}>50</option>
                                <option value={100}>100</option>
                                <option value={250}>250</option>
                                <option value={500}>500</option>
                                <option value={1000}>1000</option>
                            </select>
                        </label>
                    </div>
                </section>

                <!-- Security Section -->
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <ShieldCheck size="1.2em" class="text-primary-500" />
                        Security & Encryption
                    </h2>
                    <div
                        class="border-surface-500/10 bg-surface-500/5 space-y-4 rounded-lg border p-4">
                        <div class="text-sm italic opacity-80">
                            Global security overrides for the journal module.
                        </div>
                        <label class={field_card_class}>
                            <input
                                type="checkbox"
                                bind:checked={
                                    $journals_sess.enable_session_passcode_cache
                                }
                                class="checkbox checkbox-primary" />
                            <span class="text-sm font-bold"
                                >Cache Passcodes in Session</span>
                        </label>
                    </div>
                </section>

                <!-- Alerts Section -->
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <CircleAlert size="1.2em" class="text-primary-500" />
                        Alerts & Messaging
                    </h2>
                    <div
                        class="border-surface-500/10 bg-surface-500/5 space-y-4 rounded-xl border p-4">
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Alert Message</span>
                            <textarea
                                bind:value={tmp_config.alert_msg}
                                class="textarea min-h-24 w-full"
                                placeholder="Optional alert or notice shown with the journal"
                            ></textarea>
                        </label>

                        <label class={field_card_class}>
                            <input
                                type="checkbox"
                                bind:checked={tmp_config.alert}
                                class="checkbox checkbox-primary" />
                            <div class="flex flex-col">
                                <span class="font-bold">Enable Alert</span>
                                <span class="text-xs opacity-60">
                                    Mark this journal for attention in lists and
                                    headers.
                                </span>
                            </div>
                        </label>
                    </div>
                </section>

                <!-- Admin Section -->
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <Settings size="1.2em" class="text-primary-500" />
                        Admin
                    </h2>
                    <div
                        class="border-surface-500/10 bg-surface-500/5 space-y-4 rounded-xl border p-4">
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Notes</span>
                            <textarea
                                bind:value={tmp_config.notes}
                                class="textarea min-h-24 w-full"
                                placeholder="Internal notes for administrators and trusted access"
                            ></textarea>
                        </label>

                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                            <label class={field_card_class}>
                                <input
                                    type="checkbox"
                                    bind:checked={tmp_config.enable}
                                    class="checkbox checkbox-primary" />
                                <div class="flex flex-col">
                                    <span class="font-bold">Enabled</span>
                                    <span class="text-xs opacity-60">
                                        Allow access to this journal.
                                    </span>
                                </div>
                            </label>

                            <label class={field_card_class}>
                                <input
                                    type="checkbox"
                                    bind:checked={tmp_config.hide}
                                    class="checkbox checkbox-primary" />
                                <div class="flex flex-col">
                                    <span class="font-bold">Hidden</span>
                                    <span class="text-xs opacity-60">
                                        Hide this journal from standard lists.
                                    </span>
                                </div>
                            </label>

                            <label class={field_card_class}>
                                <input
                                    type="checkbox"
                                    bind:checked={tmp_config.priority}
                                    class="checkbox checkbox-primary" />
                                <div class="flex flex-col">
                                    <span class="font-bold">Priority</span>
                                    <span class="text-xs opacity-60">
                                        Pin this journal ahead of the standard
                                        order.
                                    </span>
                                </div>
                            </label>

                            <label
                                class="bg-surface-500/5 border-surface-500/10 flex items-center justify-between rounded-lg border p-3">
                                <div class="flex flex-col">
                                    <span class="text-sm font-bold"
                                        >Sort Order</span>
                                    <span class="text-xs opacity-60">
                                        Lower numbers appear earlier in lists.
                                    </span>
                                </div>
                                <input
                                    type="number"
                                    bind:value={tmp_config.sort}
                                    class="input input-sm w-24 text-right" />
                            </label>
                        </div>

                        <div
                            class="border-surface-500/10 bg-surface-500/5 rounded-xl border p-4">
                            <p class="text-xs italic opacity-70">
                                Admin changes apply to the journal module state
                                and are saved with the rest of this config.
                            </p>
                        </div>
                    </div>
                </section>
            </div>
        {:else if tab === 'local_json'}
            <div class="h-full min-h-100">
                <AE_Comp_Editor_CodeMirror
                    readonly={true}
                    content={JSON.stringify(tmp_config, null, 2)}
                    theme_mode={$ae_loc.theme_mode}
                    class_li="rounded-lg border border-surface-500/30" />
            </div>
        {:else if tab === 'session_json'}
            <div class="h-full min-h-100">
                <AE_Comp_Editor_CodeMirror
                    readonly={true}
                    content={JSON.stringify($journals_sess, null, 2)}
                    theme_mode={$ae_loc.theme_mode}
                    class_li="rounded-lg border border-surface-500/30" />
            </div>
        {/if}
    </div>

    {#snippet footer()}
        <div class="flex gap-4">
            <button
                type="button"
                class="btn preset-tonal-surface min-w-25 font-bold"
                onclick={() => (show = false)}>
                <X size="1.2em" class="mr-2" /> Cancel
            </button>
            <button
                type="button"
                class="btn preset-filled-primary min-w-30 font-bold shadow-lg"
                onclick={handle_save}>
                <Check size="1.2em" class="mr-2" /> Save Changes
            </button>
        </div>
    {/snippet}
</Modal>
