<script lang="ts">
    /**
     * src/routes/events/[event_id]/(leads)/leads/exhibit/[exhibit_id]/ae_comp__exhibit_license_list.svelte
     * Exhibitor License Management - Handles parsing and editing event_exhibit.license_li_json
     */
    import { untrack } from 'svelte';
    import { ae_api } from '$lib/stores/ae_stores';
    import { events_func } from '$lib/ae_events_functions';
    import { Plus, Trash2, Mail, Key, User, Save, LoaderCircle, Users } from 'lucide-svelte';

    interface Props {
        exhibit_id: string;
        event_id: string;
        license_li_json?: string; // Raw JSON string from DB
        license_max?: number;
    }

    let { exhibit_id, event_id, license_li_json = '[]', license_max = 0 }: Props = $props();

    // Local state for the parsed list
    let local_license_li: any[] = $state([]);
    let is_saving = $state(false);

    // Parse JSON into local state
    $effect(() => {
        try {
            const raw = license_li_json;
            if (!raw) {
                untrack(() => local_license_li = []);
                return;
            }

            // Handle both string and pre-parsed array/object formats
            let parsed = [];
            if (Array.isArray(raw)) {
                parsed = raw;
            } else if (typeof raw === 'string') {
                parsed = JSON.parse(raw || '[]');
            }

            untrack(() => {
                local_license_li = Array.isArray(parsed) ? parsed : [];
            });
        } catch (e) {
            console.error('Failed to parse license_li_json', e);
            untrack(() => {
                local_license_li = [];
            });
        }
    });

    async function save_licenses() {
        if (!exhibit_id) return;
        is_saving = true;
        try {
            const json_str = JSON.stringify(local_license_li);
            await events_func.update_ae_obj__exhibit({
                api_cfg: $ae_api,
                event_id: event_id,
                exhibit_id: exhibit_id,
                data_kv: {
                    license_li_json: json_str
                }
            });
        } catch (e) {
            console.error('Failed to save licenses', e);
        } finally {
            is_saving = false;
        }
    }

    function add_license() {
        if (local_license_li.length >= (license_max || 1)) {
            alert(`Maximum licenses (${license_max}) reached.`);
            return;
        }
        local_license_li.push({
            full_name: '',
            email: '',
            passcode: Math.random().toString(36).substring(2, 8).toUpperCase()
        });
    }

    function remove_license(index: number) {
        if (confirm('Remove this license? The user will lose access immediately.')) {
            local_license_li.splice(index, 1);
        }
    }
</script>

<div class="exhibit-license-list space-y-4">
    <div class="flex items-center justify-between">
        <h3 class="text-sm font-bold uppercase tracking-widest opacity-50">Assigned Licenses</h3>
        <span class="text-xs font-mono bg-surface-500/10 px-2 py-1 rounded">
            {local_license_li.length} / {license_max || 1}
        </span>
    </div>

    <div class="space-y-3">
        {#each local_license_li as license, i}
            <div class="card p-4 variant-soft border border-surface-500/10 space-y-3 relative group animate-in fade-in slide-in-from-right-2">
                <button 
                    class="absolute top-2 right-2 p-2 text-error-500 opacity-0 group-hover:opacity-100 transition-opacity"
                    onclick={() => remove_license(i)}
                    title="Remove License"
                >
                    <Trash2 size="1.2em" />
                </button>

                <!-- Name -->
                <div class="flex items-center gap-3">
                    <User size="1.2em" class="opacity-30" />
                    <input 
                        type="text" 
                        bind:value={license.full_name} 
                        placeholder="Full Name" 
                        class="bg-transparent border-b border-surface-500/20 focus:border-primary-500 outline-none flex-1 text-sm font-bold"
                    />
                </div>

                <!-- Email -->
                <div class="flex items-center gap-3">
                    <Mail size="1.2em" class="opacity-30" />
                    <input 
                        type="email" 
                        bind:value={license.email} 
                        placeholder="email@example.com" 
                        class="bg-transparent border-b border-surface-500/20 focus:border-primary-500 outline-none flex-1 text-sm"
                    />
                </div>

                <!-- Passcode -->
                <div class="flex items-center gap-3">
                    <Key size="1.2em" class="opacity-30" />
                    <input 
                        type="text" 
                        bind:value={license.passcode} 
                        placeholder="PASSCODE" 
                        class="bg-transparent border-b border-surface-500/20 focus:border-primary-500 outline-none w-32 text-sm font-mono font-bold"
                    />
                </div>
            </div>
        {/each}

        {#if local_license_li.length === 0}
            <div class="p-8 text-center border-2 border-dashed border-surface-500/20 rounded-xl opacity-30">
                <Users size="2em" class="mx-auto mb-2" />
                <p class="text-sm italic">No licenses assigned yet.</p>
            </div>
        {/if}
    </div>

    <div class="flex gap-2 pt-2">
        <button 
            class="btn btn-sm variant-filled-secondary flex-1" 
            onclick={add_license}
            disabled={local_license_li.length >= (license_max || 1)}
        >
            <Plus size="1.2em" class="mr-2" /> Add Leads Licensee
        </button>

        <button 
            class="btn btn-sm variant-filled-primary flex-1" 
            onclick={save_licenses}
            disabled={is_saving}
        >
            {#if is_saving}
                <LoaderCircle size="1.2em" class="animate-spin mr-2" />
            {:else}
                <Save size="1.2em" class="mr-2" />
            {/if}
            Save Changes
        </button>
    </div>
</div>