<script lang="ts">
/**
 * Leads / Exhibits Config Page
 * Route: /events/[event_id]/leads/config
 *
 * Admin UI for managing event.mod_exhibits_json (ExhibitsRemoteCfg).
 * Access: administrator_access only.
 *
 * Controls:
 *   - leads_require_payment  — show/hide Stripe billing UI event-wide
 *   - Stripe keys            — publishable key + buy button IDs per license tier
 *                              (previously lived in site_cfg_json; moved here so they
 *                              are per-event rather than per-site)
 *
 * Save pattern: load → merge draft → PATCH event.mod_exhibits_json via V3 API.
 */
import { untrack } from 'svelte';
import { page } from '$app/state';
import { liveQuery } from 'dexie';
import { db_events } from '$lib/ae_events/db_events';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { events_func } from '$lib/ae_events/ae_events_functions';
import { api } from '$lib/ae_api/api';
import {
    TriangleAlert,
    ArrowLeft,
    Check,
    ChevronDown,
    ChevronUp,
    CreditCard,
    Info,
    Lock,
    Save,
    Settings
} from '@lucide/svelte';

interface ExhibitsRemoteCfg {
    /** When true, Stripe billing UI (header CreditCard button + Manage tab accordion) is visible. */
    leads_require_payment: boolean;
    /** Stripe publishable key (pk_live_... or pk_test_...). */
    stripe_publishable_key: string | null;
    /** Stripe Buy Button IDs per license tier. */
    stripe_btn_1_license:  string | null;
    stripe_btn_3_license:  string | null;
    stripe_btn_6_license:  string | null;
    stripe_btn_10_license: string | null;
}

let event_id = $derived(page.params.event_id ?? '');

let lq__event_obj = $derived(
    liveQuery(async () => {
        if (!event_id) return null;
        return await db_events.event.get(event_id);
    })
);

// ---------------------------------------------------------------------------
// Draft state — initialized from the live event config
// ---------------------------------------------------------------------------
const cfg_defaults: ExhibitsRemoteCfg = {
    leads_require_payment: false,
    stripe_publishable_key: null,
    stripe_btn_1_license:   null,
    stripe_btn_3_license:   null,
    stripe_btn_6_license:   null,
    stripe_btn_10_license:  null
};

let draft: ExhibitsRemoteCfg = $state({ ...cfg_defaults });
let draft_initialized = $state(false);
let initial_json = $state('');

$effect(() => {
    const event_obj = $lq__event_obj;
    if (event_obj && !draft_initialized) {
        untrack(() => {
            const saved = (event_obj.mod_exhibits_json ?? {}) as Partial<ExhibitsRemoteCfg>;
            draft = { ...cfg_defaults, ...saved };
            initial_json = JSON.stringify(draft);
            draft_initialized = true;
        });
    }
});

let is_dirty = $derived(draft_initialized && JSON.stringify(draft) !== initial_json);

// Section collapse state
let sections: Record<string, boolean> = $state({
    payment: true,
    stripe: true
});
function toggle(key: string) {
    sections[key] = !sections[key];
}

// ---------------------------------------------------------------------------
// Save
// ---------------------------------------------------------------------------
let save_status: 'idle' | 'saving' | 'success' | 'error' = $state('idle');

async function save() {
    if (!event_id) return;
    save_status = 'saving';
    try {
        // Preserve any unknown keys already in mod_exhibits_json (future-proofing).
        const current_cfg = ($lq__event_obj?.mod_exhibits_json ?? {}) as any;
        const new_cfg = { ...current_cfg, ...draft };

        await api.update_ae_obj({
            api_cfg: $ae_api,
            obj_type: 'event',
            obj_id: event_id,
            fields: { mod_exhibits_json: new_cfg },
            log_lvl: 1
        });

        // Reload event so consumers pick up the new config immediately.
        await events_func.load_ae_obj_id__event({
            api_cfg: $ae_api,
            event_id: event_id,
            log_lvl: 1
        });

        initial_json = JSON.stringify(draft);
        save_status = 'success';
        setTimeout(() => (save_status = 'idle'), 3000);
    } catch (e) {
        console.error('Failed to save exhibits config', e);
        save_status = 'error';
        setTimeout(() => (save_status = 'idle'), 5000);
    }
}
</script>

<svelte:head>
    <title>Leads Config</title>
</svelte:head>

{#if !$ae_loc.administrator_access}
    <div class="p-8 text-center opacity-50">
        <Lock size="3em" class="mx-auto mb-2" />
        <p>Administrator access required.</p>
    </div>
{:else}
    <div class="mx-auto w-full max-w-2xl space-y-4 px-2 py-4">

        <!-- Header -->
        <header class="flex items-center justify-between gap-4">
            <div class="flex items-center gap-2">
                <a
                    href="/events/{event_id}/leads"
                    class="btn btn-sm preset-tonal-surface"
                    title="Back to Leads">
                    <ArrowLeft size="1em" />
                </a>
                <Settings size="1.2em" class="text-primary-500" />
                <h1 class="text-xl font-bold">Leads Config</h1>
            </div>
            <div class="flex items-center gap-2">
                {#if save_status === 'success'}
                    <span class="badge preset-tonal-success flex items-center gap-1">
                        <Check size="1em" /> Saved
                    </span>
                {:else if save_status === 'error'}
                    <span class="badge preset-tonal-error flex items-center gap-1">
                        <TriangleAlert size="1em" /> Error saving
                    </span>
                {/if}
                <button
                    type="button"
                    class="btn preset-filled-primary-500"
                    onclick={save}
                    disabled={!is_dirty || save_status === 'saving'}>
                    <Save size="1em" class="mr-1" />
                    {save_status === 'saving' ? 'Saving...' : 'Save'}
                </button>
            </div>
        </header>

        <p class="text-surface-500 text-sm">
            Changes here update <code>event.mod_exhibits_json</code> and take effect immediately
            for all exhibitors at this event (no re-login required).
        </p>

        {#if !draft_initialized}
            <p class="text-surface-400 italic">Loading event config...</p>
        {:else}

        <!-- ================================================================ -->
        <!-- PAYMENT -->
        <!-- ================================================================ -->
        <section class="border-surface-200-800 rounded-xl border">
            <button
                type="button"
                class="flex w-full items-center justify-between px-4 py-3 text-left font-semibold"
                onclick={() => toggle('payment')}>
                <span class="flex items-center gap-2">
                    <CreditCard size="1em" class="text-success-500" />
                    Payment
                </span>
                {#if sections.payment}<ChevronUp size="1em" />{:else}<ChevronDown size="1em" />{/if}
            </button>
            {#if sections.payment}
                <div class="border-surface-200-800 space-y-3 border-t px-4 py-4">
                    <label class="flex items-start gap-3">
                        <input
                            type="checkbox"
                            class="checkbox mt-0.5"
                            bind:checked={draft.leads_require_payment} />
                        <span>
                            <span class="font-semibold">Require Payment (Stripe)</span>
                            <span class="text-surface-500 ml-2 text-sm">
                                Shows the Stripe billing UI to exhibitors — the header CreditCard
                                button and the "Licenses &amp; Billing" accordion in the Manage tab.
                                Leave <strong>off</strong> when the client is covering costs.
                            </span>
                        </span>
                    </label>
                    <div class="flex items-start gap-2 rounded-lg bg-surface-500/5 p-3 text-xs opacity-60">
                        <Info size="1em" class="mt-0.5 shrink-0" />
                        <span>
                            The Stripe payment component code is always present. This toggle only
                            controls visibility — no code changes needed when switching events.
                        </span>
                    </div>
                </div>
            {/if}
        </section>

        <!-- ================================================================ -->
        <!-- STRIPE CONFIG -->
        <!-- ================================================================ -->
        <section class="border-surface-200-800 rounded-xl border">
            <button
                type="button"
                class="flex w-full items-center justify-between px-4 py-3 text-left font-semibold"
                onclick={() => toggle('stripe')}>
                <span>
                    Stripe Keys
                    <span class="text-surface-500 text-xs font-normal ml-1">(per-event)</span>
                </span>
                {#if sections.stripe}<ChevronUp size="1em" />{:else}<ChevronDown size="1em" />{/if}
            </button>
            {#if sections.stripe}
                <div class="border-surface-200-800 space-y-4 border-t px-4 py-4">
                    <div class="flex items-start gap-2 text-xs opacity-60">
                        <Info size="1em" class="mt-0.5 shrink-0" />
                        <span>
                            These keys apply only to this event's Exhibitor Leads module.
                            Find them in the Stripe Dashboard → Products → Buy Buttons.
                            The Buy Button IDs are per license tier (1, 3, 6, or 10 users).
                        </span>
                    </div>

                    <label class="flex flex-col gap-1">
                        <span class="text-sm font-medium">Publishable Key</span>
                        <input
                            type="text"
                            class="input input-sm font-mono text-xs"
                            placeholder="pk_live_... or pk_test_..."
                            bind:value={draft.stripe_publishable_key} />
                    </label>

                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <label class="flex flex-col gap-1">
                            <span class="text-sm font-medium">Buy Button — 1 License</span>
                            <input
                                type="text"
                                class="input input-sm font-mono text-xs"
                                placeholder="buy_btn_..."
                                bind:value={draft.stripe_btn_1_license} />
                        </label>
                        <label class="flex flex-col gap-1">
                            <span class="text-sm font-medium">Buy Button — 3 Licenses</span>
                            <input
                                type="text"
                                class="input input-sm font-mono text-xs"
                                placeholder="buy_btn_..."
                                bind:value={draft.stripe_btn_3_license} />
                        </label>
                        <label class="flex flex-col gap-1">
                            <span class="text-sm font-medium">Buy Button — 6 Licenses</span>
                            <input
                                type="text"
                                class="input input-sm font-mono text-xs"
                                placeholder="buy_btn_..."
                                bind:value={draft.stripe_btn_6_license} />
                        </label>
                        <label class="flex flex-col gap-1">
                            <span class="text-sm font-medium">Buy Button — 10 Licenses</span>
                            <input
                                type="text"
                                class="input input-sm font-mono text-xs"
                                placeholder="buy_btn_..."
                                bind:value={draft.stripe_btn_10_license} />
                        </label>
                    </div>
                </div>
            {/if}
        </section>

        <!-- Bottom save -->
        <div class="flex justify-end">
            <button
                type="button"
                class="btn preset-filled-primary-500"
                onclick={save}
                disabled={!is_dirty || save_status === 'saving'}>
                <Save size="1em" class="mr-1" />
                {save_status === 'saving' ? 'Saving...' : 'Save Config'}
            </button>
        </div>

        {/if}
    </div>
{/if}
