<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_sess } from '$lib/stores/ae_events_stores';
import { leads_loc } from '$lib/stores/ae_events_stores__leads.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';
import Element_ae_obj_field_editor from '$lib/elements/element_ae_obj_field_editor.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 {
    ChevronDown,
    ChevronRight,
    ChevronUp,
    Clock,
    CreditCard,
    Database,
    Download,
    Info,
    Key,
    Lock,
    LogOut,
    MessageSquare,
    RefreshCw,
    Settings,
    Store,
    UserX,
    Users
} from '@lucide/svelte';
interface StripeCfg {
    stripe_publishable_key?: string | null;
    stripe_btn_1_license?:   string | null;
    stripe_btn_3_license?:   string | null;
    stripe_btn_6_license?:   string | null;
    stripe_btn_10_license?:  string | null;
}

// leads_require_payment: event-level flag from mod_exhibits_json.
// When false (default), all billing UI is hidden — client is covering costs.
// Set mod_exhibits_json.leads_require_payment = true in event settings to enable Stripe.
// stripe_cfg: Stripe keys from mod_exhibits_json, passed through to the payment component.
let {
    leads_require_payment = false,
    stripe_cfg = {}
}: { leads_require_payment?: boolean; stripe_cfg?: StripeCfg } = $props();

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);
let desc_expanded = $state(false);

function handle_signout() {
    if (confirm('Sign out from this booth?')) {
        // Use object spread instead of delete — `delete` on a PersistedState proxy
        // does not reliably trigger Svelte 5 reactivity, so is_signed_in in the parent
        // page would never re-evaluate and the sign-in gate would stay open.
        leads_loc.current.auth_exhibit_kv = Object.fromEntries(
            Object.entries(leads_loc.current.auth_exhibit_kv).filter(([k]) => k !== exhibit_id)
        );
        $events_sess.leads.entered_passcode = null;
        leads_loc.current.tab[exhibit_id] = 'start';
    }
}
</script>

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

            <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <!-- Priority / Payment Toggle -->
                <div
                    class="card preset-tonal-surface flex items-center justify-between p-3">
                    <div class="text-[10px] font-black uppercase opacity-40">
                        Payment Status
                    </div>
                    <Element_ae_obj_field_editor
                        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>
                </div>

                <!-- Max Licenses -->
                <div
                    class="card preset-tonal-surface flex items-center justify-between p-3">
                    <div class="text-[10px] font-black uppercase opacity-40">
                        Max Licenses
                    </div>
                    <Element_ae_obj_field_editor
                        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 preset-tonal-surface flex items-center justify-between p-3">
                    <div class="text-[10px] font-black uppercase opacity-40">
                        Small Devices
                    </div>
                    <Element_ae_obj_field_editor
                        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 preset-tonal-surface flex items-center justify-between p-3">
                    <div class="text-[10px] font-black uppercase opacity-40">
                        Large Devices
                    </div>
                    <Element_ae_obj_field_editor
                        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>

                <!-- API / Export Access — gates the CSV export button and backend export endpoint -->
                <div
                    class="card preset-tonal-surface flex items-center justify-between p-3">
                    <div class="text-[10px] font-black uppercase opacity-40">
                        API / Export Access
                    </div>
                    <Element_ae_obj_field_editor
                        object_type="event_exhibit"
                        object_id={exhibit_id}
                        field_name="leads_api_access"
                        field_type="checkbox"
                        current_value={$lq__exhibit_obj?.leads_api_access}
                        on_success={() =>
                            events_func.load_ae_obj_id__event_exhibit({
                                api_cfg: $ae_api,
                                exhibit_id
                            })}>
                        <div class="font-bold">
                            {$lq__exhibit_obj?.leads_api_access ? 'ON' : 'OFF'}
                        </div>
                    </Element_ae_obj_field_editor>
                </div>
            </div>
        </section>
    {/if}

    <!-- Section: Account Status (read-only for non-admin signed-in users) -->
    <!-- Admins see the editable Admin Tools section above; this is for exhibitor staff. -->
    {#if !$ae_loc.manager_access}
        <section class="space-y-3">
            <div
                class="border-surface-500/10 flex items-center gap-2 border-b pb-2">
                <Info size="1.2em" class="text-tertiary-500" />
                <h3 class="text-lg font-bold tracking-wider uppercase">
                    Account Status
                </h3>
            </div>

            <div class="grid grid-cols-3 gap-3">
                <!-- Payment / Priority -->
                <div
                    class="card preset-tonal-surface flex flex-col items-center justify-center gap-1 p-3 text-center">
                    <div
                        class="text-[9px] font-black tracking-widest uppercase opacity-40">
                        Payment
                    </div>
                    <div
                        class="text-sm font-bold"
                        class:text-success-500={$lq__exhibit_obj?.priority}
                        class:text-warning-500={!$lq__exhibit_obj?.priority}>
                        {$lq__exhibit_obj?.priority ? 'PAID' : 'PENDING'}
                    </div>
                </div>

                <!-- Max Licenses -->
                <div
                    class="card preset-tonal-surface flex flex-col items-center justify-center gap-1 p-3 text-center">
                    <div
                        class="text-[9px] font-black tracking-widest uppercase opacity-40">
                        Licenses
                    </div>
                    <div class="font-mono text-sm font-bold">
                        {$lq__exhibit_obj?.license_max ?? '—'}
                    </div>
                </div>

                <!-- API / Export Access -->
                <div
                    class="card preset-tonal-surface flex flex-col items-center justify-center gap-1 p-3 text-center">
                    <div
                        class="text-[9px] font-black tracking-widest uppercase opacity-40">
                        Export
                    </div>
                    <div
                        class="text-sm font-bold"
                        class:text-success-500={$lq__exhibit_obj?.leads_api_access}
                        class:opacity-40={!$lq__exhibit_obj?.leads_api_access}>
                        {$lq__exhibit_obj?.leads_api_access ? 'ON' : 'OFF'}
                    </div>
                </div>
            </div>

            <!-- Export button — only when API access is enabled for this exhibit -->
            {#if $lq__exhibit_obj?.leads_api_access}
                <button
                    type="button"
                    class="btn btn-sm preset-outlined-secondary w-full"
                    onclick={() =>
                        events_func.download_export__event_exhibit_tracking({
                            api_cfg: $ae_api,
                            exhibit_id,
                            log_lvl: 1
                        })}>
                    <Download size="1.2em" class="mr-2" /> Export Leads (CSV)
                </button>
            {/if}
        </section>
    {/if}

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

        <div
            class="card divide-surface-500/10 divide-y overflow-hidden p-0 shadow-md">
            <!-- Licenses — visible to: Aether admins OR someone signed in with the shared exhibit passcode.
                 Spec: "A client staff (Trusted Access or above) or someone signed in with an Exhibit passcode
                 can add/edit/remove licenses." — PROJECT__AE_Events_Exhibitor_Leads_v3.md -->
            {#if $ae_loc.administrator_access || leads_loc.current.auth_exhibit_kv?.[exhibit_id]?.type === 'shared'}
                <div class="p-0">
                    <button
                        class="hover:bg-surface-500/5 group flex w-full items-center justify-between p-4 transition-colors"
                        onclick={() =>
                            (show_license_mgmt = !show_license_mgmt)}>
                        <div class="flex items-center gap-4">
                            <div
                                class="bg-primary-500/10 text-primary-500 rounded-lg p-2">
                                <Users size="1.2em" />
                            </div>
                            <div class="text-left">
                                <div class="text-sm font-bold">
                                    Exhibit Leads Licensees
                                </div>
                                <div class="text-xs opacity-50">
                                    Manage assigned users and codes
                                </div>
                            </div>
                        </div>
                        {#if show_license_mgmt}
                            <ChevronDown size="1.2em" class="opacity-20" />
                        {:else}
                            <ChevronRight
                                size="1.2em"
                                class="opacity-20 transition-transform group-hover:translate-x-1" />
                        {/if}
                    </button>

                    {#if show_license_mgmt}
                        <div
                            class="bg-surface-500/5 border-surface-500/10 animate-in fade-in slide-in-from-top-2 border-t p-4">
                            <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="hover:bg-surface-500/5 group flex w-full items-center justify-between p-4 transition-colors"
                    onclick={() =>
                        (show_custom_questions = !show_custom_questions)}>
                    <div class="flex items-center gap-4">
                        <div
                            class="bg-secondary-500/10 text-secondary-500 rounded-lg p-2">
                            <MessageSquare size="1.2em" />
                        </div>
                        <div class="text-left">
                            <div class="text-sm font-bold">
                                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 transition-transform group-hover:translate-x-1" />
                    {/if}
                </button>

                {#if show_custom_questions}
                    <div
                        class="bg-surface-500/5 border-surface-500/10 animate-in fade-in slide-in-from-top-2 border-t p-4">
                        <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 — only shown when event-level leads_require_payment is enabled -->
            {#if leads_require_payment}
                <div class="p-0">
                    <button
                        class="hover:bg-surface-500/5 group flex w-full items-center justify-between p-4 transition-colors"
                        onclick={() => (show_billing = !show_billing)}>
                        <div class="flex items-center gap-4">
                            <div
                                class="bg-success-500/10 text-success-500 rounded-lg p-2">
                                <CreditCard size="1.2em" />
                            </div>
                            <div class="text-left">
                                <div class="text-sm font-bold">
                                    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 transition-transform group-hover:translate-x-1" />
                        {/if}
                    </button>

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

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

        <div class="grid grid-cols-1 gap-6">
            <!-- Name -->
            <div class="card preset-tonal-surface p-4 shadow-sm">
                <div class="label mb-2">
                    <span
                        class="text-xs font-black tracking-widest uppercase opacity-40"
                        >Exhibitor Name</span>
                </div>
                <Element_ae_obj_field_editor
                    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="mt-2 text-[10px] italic opacity-50">
                    This name should match your booth name.
                </p>
            </div>

            <!-- Description — collapsed by default (can be long) -->
            <div class="card preset-tonal-surface p-4 shadow-sm">
                <button
                    type="button"
                    class="focus-visible:ring-primary-500 flex w-full items-center justify-between gap-2 rounded text-left focus-visible:ring-2"
                    onclick={() => (desc_expanded = !desc_expanded)}
                    aria-expanded={desc_expanded}>
                    <span class="text-xs font-black tracking-widest uppercase opacity-40"
                        >Booth Description / Promo</span>
                    <span class="shrink-0 text-xs opacity-40">
                        {#if desc_expanded}
                            <ChevronUp size="1em" />
                        {:else}
                            <ChevronDown size="1em" />
                        {/if}
                    </span>
                </button>
                {#if desc_expanded}
                    <div class="mt-3">
                        <Element_ae_obj_field_editor
                            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>
                {/if}
            </div>
        </div>
    </section>

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

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

                        <Element_ae_obj_field_editor
                            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="mt-2 text-[9px] italic opacity-40">
                    Shared code for your team to sign in to this booth.
                </p>
            </div>

            <!-- Booth Code -->
            <div class="card bg-surface-500/5 border-surface-500/10 border p-4">
                <div class="flex items-center justify-between">
                    <div class="flex-1">
                        <div
                            class="mb-1 text-[10px] font-black tracking-widest uppercase opacity-40">
                            Booth Identifier
                        </div>
                        <Element_ae_obj_field_editor
                            object_type="event_exhibit"
                            object_id={exhibit_id}
                            field_name="code"
                            field_type="text"
                            current_value={$lq__exhibit_obj?.code}
                            display_block={true}
                            class_li="font-mono text-xl font-bold"
                            on_success={() =>
                                events_func.load_ae_obj_id__event_exhibit({
                                    api_cfg: $ae_api,
                                    exhibit_id
                                })} />
                    </div>
                    <Info size="1.5em" class="opacity-20" />
                </div>
                <p class="mt-2 text-[9px] italic opacity-40">
                    Official floor plan booth number.
                </p>
            </div>
        </div>

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

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

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

                <div class="grid grid-cols-1 gap-2">
                    <label
                        class="hover:bg-surface-500/10 flex cursor-pointer items-center justify-between rounded-lg p-2 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="hover:bg-surface-500/10 flex cursor-pointer items-center justify-between rounded-lg p-2 transition-colors">
                        <span class="text-sm">Show Extra Details</span>
                        <input
                            type="checkbox"
                            class="checkbox"
                            bind:checked={leads_loc.current.show_details} />
                    </label>
                </div>
            </div>

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

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

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

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

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