<script lang="ts">
    /**
     * src/routes/events/[event_id]/(leads)/leads/exhibit/[exhibit_id]/ae_tab__manage.svelte
     * Tab 4: Manage/Config - Exhibitor Settings and Profile.
     */
    import { page } from '$app/state';
    import { liveQuery } from 'dexie';
    import { db_events } from '$lib/ae_events/db_events';
    import { ae_api, ae_loc } from '$lib/stores/ae_stores';
    import { events_loc, events_sess } from '$lib/stores/ae_events_stores';
    import { events_func } from '$lib/ae_events_functions';
    import Element_ae_obj_field_editor_v3 from '$lib/elements/element_ae_obj_field_editor_v3.svelte';
    import Comp_exhibit_license_list from './ae_comp__exhibit_license_list.svelte';
    import Comp_exhibit_custom_questions from './ae_comp__exhibit_custom_questions.svelte';
    import Comp_exhibit_payment from './ae_comp__exhibit_payment.svelte';
    import {
        Store,
        Settings,
        Lock,
        Info,
        MessageSquare,
        CreditCard,
        Key,
        Users,
        ChevronRight,
        ChevronDown,
        LogOut
    } from 'lucide-svelte';

    const exhibit_id = $derived(page.params.exhibit_id ?? '');

    let lq__exhibit_obj = $derived(
        liveQuery(async () => {
            if (!exhibit_id) return null;
            return await db_events.exhibit.get(exhibit_id);
        })
    );

    // Track local status for specific actions
    let updating = $state(false);
    let show_license_mgmt = $state(false);
    let show_custom_questions = $state(false);
    let show_billing = $state(false);

    function handle_signout() {
        if (confirm('Sign out from this booth?')) {
            delete $events_loc.leads.auth_exhibit_kv[exhibit_id];
            $events_sess.leads.entered_passcode = null;
            // Navigate to start tab
            if (!$events_loc.leads.tab) $events_loc.leads.tab = {};
            $events_loc.leads.tab[exhibit_id] = 'start';
        }
    }
</script>

<div class="ae-tab-manage w-full space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300 pb-20">

    <!-- Section: Admin Tools (Manager Access Only) -->
    {#if $ae_loc.manager_access}
        <section class="space-y-4 p-4 border-2 border-primary-500/20 rounded-xl bg-primary-500/5">
            <div class="flex items-center gap-2 border-b border-primary-500/10 pb-2">
                <Settings size="1.2em" class="text-primary-500" />
                <h3 class="text-lg font-bold uppercase tracking-wider text-primary-500">Admin Tools</h3>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <!-- Priority / Payment Toggle -->
                <div class="card p-3 variant-soft flex items-center justify-between">
                    <div class="text-[10px] uppercase font-black opacity-40">Payment Status</div>
                    <Element_ae_obj_field_editor_v3
                        object_type="event_exhibit"
                        object_id={exhibit_id}
                        field_name="priority"
                        field_type="checkbox"
                        current_value={$lq__exhibit_obj?.priority}
                        on_success={() => events_func.load_ae_obj_id__event_exhibit({ api_cfg: $ae_api, exhibit_id })}
                    >
                        <div class="font-bold">{$lq__exhibit_obj?.priority ? 'PAID' : 'PENDING'}</div>
                    </Element_ae_obj_field_editor_v3>
                </div>

                <!-- Max Licenses -->
                <div class="card p-3 variant-soft flex items-center justify-between">
                    <div class="text-[10px] uppercase font-black opacity-40">Max Licenses</div>
                    <Element_ae_obj_field_editor_v3
                        object_type="event_exhibit"
                        object_id={exhibit_id}
                        field_name="license_max"
                        field_type="number"
                        current_value={$lq__exhibit_obj?.license_max}
                        class_li="font-mono"
                        on_success={() => events_func.load_ae_obj_id__event_exhibit({ api_cfg: $ae_api, exhibit_id })}
                    />
                </div>

                <!-- Small Devices -->
                <div class="card p-3 variant-soft flex items-center justify-between">
                    <div class="text-[10px] uppercase font-black opacity-40">Small Devices</div>
                    <Element_ae_obj_field_editor_v3
                        object_type="event_exhibit"
                        object_id={exhibit_id}
                        field_name="leads_device_sm_qty"
                        field_type="number"
                        current_value={$lq__exhibit_obj?.leads_device_sm_qty}
                        class_li="font-mono"
                        on_success={() => events_func.load_ae_obj_id__event_exhibit({ api_cfg: $ae_api, exhibit_id })}
                    />
                </div>

                <!-- Large Devices -->
                <div class="card p-3 variant-soft flex items-center justify-between">
                    <div class="text-[10px] uppercase font-black opacity-40">Large Devices</div>
                    <Element_ae_obj_field_editor_v3
                        object_type="event_exhibit"
                        object_id={exhibit_id}
                        field_name="leads_device_lg_qty"
                        field_type="number"
                        current_value={$lq__exhibit_obj?.leads_device_lg_qty}
                        class_li="font-mono"
                        on_success={() => events_func.load_ae_obj_id__event_exhibit({ api_cfg: $ae_api, exhibit_id })}
                    />
                </div>
            </div>
        </section>
    {/if}

    <!-- Section: Booth Profile -->
    <section class="space-y-4">
        <div class="flex items-center gap-2 border-b border-surface-500/10 pb-2">
            <Store size="1.2em" class="text-primary-500" />
            <h3 class="text-lg font-bold uppercase tracking-wider">Booth Profile</h3>
        </div>

        <div class="grid grid-cols-1 gap-6">
            <!-- Name -->
            <div class="card p-4 variant-soft shadow-sm">
                <div class="label mb-2">
                    <span class="text-xs uppercase font-black opacity-40 tracking-widest">Exhibitor Name</span>
                </div>
                <Element_ae_obj_field_editor_v3
                    object_type="event_exhibit"
                    object_id={exhibit_id}
                    field_name="name"
                    field_type="text"
                    current_value={$lq__exhibit_obj?.name}
                    display_block={true}
                    class_li="font-bold text-xl"
                    on_success={() => events_func.load_ae_obj_id__event_exhibit({ api_cfg: $ae_api, exhibit_id })}
                />
                <p class="text-[10px] opacity-50 mt-2 italic">This name is visible to attendees when you scan their badges.</p>
            </div>

            <!-- Description -->
            <div class="card p-4 variant-soft shadow-sm">
                <div class="label mb-2">
                    <span class="text-xs uppercase font-black opacity-40 tracking-widest">Booth Description / Promo</span>
                </div>
                <Element_ae_obj_field_editor_v3
                    object_type="event_exhibit"
                    object_id={exhibit_id}
                    field_name="description"
                    field_type="tiptap"
                    current_value={$lq__exhibit_obj?.description}
                    display_block={true}
                    class_li="text-sm"
                    on_success={() => events_func.load_ae_obj_id__event_exhibit({ api_cfg: $ae_api, exhibit_id })}
                />
            </div>
        </div>
    </section>

    <!-- Section: Staff Access -->
    <section class="space-y-4">
        <div class="flex items-center gap-2 border-b border-surface-500/10 pb-2">
            <Lock size="1.2em" class="text-warning-500" />
            <h3 class="text-lg font-bold uppercase tracking-wider">Access & Security</h3>
        </div>

        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <!-- Staff Passcode -->
            <div class="card p-4 bg-surface-500/5 border border-surface-500/10">
                <div class="flex items-center justify-between">
                    <div class="flex-1">
                        <div class="text-[10px] uppercase font-black opacity-40 tracking-widest mb-1">Staff Passcode</div>

                        <!-- Add a clear read-only display for admins to see the code at a glance -->
                        {#if $ae_loc.administrator_access}
                            <div class="font-mono text-xl tracking-widest font-bold text-primary-500 mb-2">
                                {$lq__exhibit_obj?.staff_passcode || '----'}
                            </div>
                        {/if}

                        <Element_ae_obj_field_editor_v3
                            object_type="event_exhibit"
                            object_id={exhibit_id}
                            field_name="staff_passcode"
                            field_type="text"
                            current_value={$lq__exhibit_obj?.staff_passcode}
                            display_block={true}
                            class_li="font-mono text-xl tracking-widest font-bold"
                            on_success={() => events_func.load_ae_obj_id__event_exhibit({ api_cfg: $ae_api, exhibit_id })}
                        />
                    </div>
                    <Key size="1.5em" class="opacity-20" />
                </div>
                <p class="text-[9px] opacity-40 mt-2 italic">Shared code for your team to sign in to this booth.</p>
            </div>

            <!-- Booth Code -->
            <div class="card p-4 bg-surface-500/5 border border-surface-500/10">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-[10px] uppercase font-black opacity-40 tracking-widest">Booth Identifier</div>
                        <div class="font-mono text-xl font-bold">#{$lq__exhibit_obj?.code || 'N/A'}</div>
                    </div>
                    <Info size="1.5em" class="opacity-20" />
                </div>
                <p class="text-[9px] opacity-40 mt-2 italic">Official floor plan booth number.</p>
            </div>
        </div>

        <!-- Sign Out -->
        {#if !$ae_loc.manager_access}
            <button
                class="btn variant-ghost-error w-full mt-2"
                onclick={handle_signout}
            >
                <LogOut size="1.2em" class="mr-2" /> Sign Out of Booth
            </button>
        {/if}
    </section>

    <!-- Section: Lead Settings -->
    <section class="space-y-4">
        <div class="flex items-center gap-2 border-b border-surface-500/10 pb-2">
            <Settings size="1.2em" class="text-secondary-500" />
            <h3 class="text-lg font-bold uppercase tracking-wider">Lead Retrieval Config</h3>
        </div>

        <div class="card p-0 divide-y divide-surface-500/10 overflow-hidden shadow-md">
            <!-- Licenses (Administrator Access Only for now) -->
            {#if $ae_loc.administrator_access}
                <div class="p-0">
                    <button
                        class="w-full p-4 flex items-center justify-between hover:bg-surface-500/5 transition-colors group"
                        onclick={() => show_license_mgmt = !show_license_mgmt}
                    >
                        <div class="flex items-center gap-4">
                            <div class="bg-primary-500/10 p-2 rounded-lg text-primary-500"><Users size="1.2em" /></div>
                            <div class="text-left">
                                <div class="font-bold text-sm">Exhibit Leads Licensees</div>
                                <div class="text-xs opacity-50">Manage assigned users and codes (Admin Only)</div>
                            </div>
                        </div>
                        {#if show_license_mgmt}
                            <ChevronDown size="1.2em" class="opacity-20" />
                        {:else}
                            <ChevronRight size="1.2em" class="opacity-20 group-hover:translate-x-1 transition-transform" />
                        {/if}
                    </button>

                    {#if show_license_mgmt}
                        <div class="p-4 bg-surface-500/5 border-t border-surface-500/10 animate-in fade-in slide-in-from-top-2">
                            <Comp_exhibit_license_list
                                {exhibit_id}
                                event_id={page.params.event_id ?? ''}
                                license_li_json={$lq__exhibit_obj?.license_li_json ?? '[]'}
                                license_max={$lq__exhibit_obj?.license_max}
                            />
                        </div>
                    {/if}
                </div>
            {/if}

            <!-- Custom Questions -->
            <div class="p-0">
                <button
                    class="w-full p-4 flex items-center justify-between hover:bg-surface-500/5 transition-colors group"
                    onclick={() => show_custom_questions = !show_custom_questions}
                >
                    <div class="flex items-center gap-4">
                        <div class="bg-secondary-500/10 p-2 rounded-lg text-secondary-500"><MessageSquare size="1.2em" /></div>
                        <div class="text-left">
                            <div class="font-bold text-sm">Qualifiers & Questions</div>
                            <div class="text-xs opacity-50">Configure lead capture follow-up responses</div>
                        </div>
                    </div>
                    {#if show_custom_questions}
                        <ChevronDown size="1.2em" class="opacity-20" />
                    {:else}
                        <ChevronRight size="1.2em" class="opacity-20 group-hover:translate-x-1 transition-transform" />
                    {/if}
                </button>

                {#if show_custom_questions}
                    <div class="p-4 bg-surface-500/5 border-t border-surface-500/10 animate-in fade-in slide-in-from-top-2">
                        <Comp_exhibit_custom_questions
                            {exhibit_id}
                            event_id={page.params.event_id ?? ''}
                            custom_questions_json={$lq__exhibit_obj?.leads_custom_questions_json ?? '[]'}
                        />
                    </div>
                {/if}
            </div>

            <!-- Billing -->
            <div class="p-0">
                <button
                    class="w-full p-4 flex items-center justify-between hover:bg-surface-500/5 transition-colors group"
                    onclick={() => show_billing = !show_billing}
                >
                    <div class="flex items-center gap-4">
                        <div class="bg-success-500/10 p-2 rounded-lg text-success-500"><CreditCard size="1.2em" /></div>
                        <div class="text-left">
                            <div class="font-bold text-sm">Licenses & Billing</div>
                            <div class="text-xs opacity-50">Review licenses and manage payment</div>
                        </div>
                    </div>
                    {#if show_billing}
                        <ChevronDown size="1.2em" class="opacity-20" />
                    {:else}
                        <ChevronRight size="1.2em" class="opacity-20 group-hover:translate-x-1 transition-transform" />
                    {/if}
                </button>

                {#if show_billing}
                    <div class="p-4 bg-surface-500/5 border-t border-surface-500/10 animate-in fade-in slide-in-from-top-2">
                        <Comp_exhibit_payment />
                    </div>
                {/if}
            </div>
        </div>
    </section>

    <!-- Section: App Settings -->
    <section class="space-y-4">
        <div class="flex items-center gap-2 border-b border-surface-500/10 pb-2">
            <Settings size="1.2em" class="text-secondary-500" />
            <h3 class="text-lg font-bold uppercase tracking-wider">App Settings</h3>
        </div>

        <div class="card p-4 space-y-6 variant-soft shadow-inner">
            <!-- Interface Prefs -->
            <div class="space-y-3">
                <div class="text-[10px] uppercase font-black opacity-40 tracking-widest">Interface Preferences</div>

                <div class="grid grid-cols-1 gap-2">
                    <label class="flex items-center justify-between p-2 hover:bg-surface-500/10 rounded-lg cursor-pointer transition-colors">
                        <span class="text-sm">Auto-hide Header/Footer</span>
                        <input type="checkbox" class="checkbox" bind:checked={$ae_loc.auto_hide_nav} />
                    </label>
                    <label class="flex items-center justify-between p-2 hover:bg-surface-500/10 rounded-lg cursor-pointer transition-colors">
                        <span class="text-sm">Show Payment Tab</span>
                        <input type="checkbox" class="checkbox" bind:checked={$ae_loc.show_leads_payment} />
                    </label>
                    <label class="flex items-center justify-between p-2 hover:bg-surface-500/10 rounded-lg cursor-pointer transition-colors">
                        <span class="text-sm">Show Extra Details</span>
                        <input type="checkbox" class="checkbox" bind:checked={$events_loc.show_details} />
                    </label>
                </div>
            </div>

            <!-- List Refresh -->
            <div class="space-y-3">
                <div class="flex items-center justify-between">
                    <div class="text-[10px] uppercase font-black opacity-40 tracking-widest">Data Synchronization</div>
                    <div class="flex items-center gap-2 text-[10px] font-mono opacity-60">
                        <span class="fas fa-clock"></span>
                        {#if $events_sess.leads.last_refresh_time}
                            Last: {new Date($events_sess.leads.last_refresh_time).toLocaleTimeString()}
                        {:else}
                            Waiting...
                        {/if}
                    </div>
                </div>

                <div class="flex items-center gap-4 p-2 bg-surface-500/5 rounded-lg border border-surface-500/10">
                    <div class="flex-1 space-y-1">
                        <span class="text-sm block">Refresh Interval (sec)</span>
                        <div class="text-[9px] opacity-40 uppercase font-bold">
                            Next Sync in <span class="text-primary-500">{$events_sess.leads.next_refresh_countdown}s</span>
                        </div>
                    </div>
                    <input
                        type="number"
                        class="input w-20 text-right font-mono p-1 bg-transparent border-b border-surface-500/20"
                        min="1"
                        max="120"
                        bind:value={$events_loc.leads.refresh_interval_sec}
                        placeholder="25"
                    />
                </div>
            </div>

            <!-- Maintenance -->
            <div class="space-y-3">
                <div class="text-[10px] uppercase font-black opacity-40 tracking-widest">Maintenance & Reset</div>
                <div class="grid grid-cols-2 gap-2">
                    <button class="btn btn-sm variant-filled-warning" onclick={() => window.location.reload()}>
                        <span class="fas fa-sync mr-2"></span> Reload App
                    </button>
                    <button class="btn btn-sm variant-ghost-error" onclick={() => {
                        if(confirm('Clear all local cached data (IDB)?')) {
                            db_events.delete().then(() => window.location.reload());
                        }
                    }}>
                        <span class="fas fa-database mr-2"></span> Clear IDB
                    </button>
                    <button class="btn btn-sm variant-ghost-error col-span-2" onclick={() => {
                        if(confirm('Reset all local app settings and sign out?')) {
                            localStorage.clear();
                            window.location.reload();
                        }
                    }}>
                        <span class="fas fa-user-slash mr-2"></span> Clear Local Settings (Hard Reset)
                    </button>
                </div>
            </div>
        </div>
    </section>

    <!-- Help Footer -->
    <div class="pt-10 pb-20 text-center space-y-2 opacity-40">
        <p class="text-xs">Exhibitor Management Module v3.0</p>
        <p class="text-[10px] font-mono">Exhibit ID: {$lq__exhibit_obj?.event_exhibit_id}</p>
    </div>

</div>

<style lang="postcss">
    /* Custom tab styles if needed */
</style>
