<script lang="ts">
    /**
     * src/routes/events/[event_id]/(leads)/leads/exhibit/[exhibit_id]/ae_comp__exhibit_signin.svelte
     * Exhibitor Sign-In Component - Handles both Shared Passcode and Licensed User login.
     */
    import { page } from '$app/state';
    import { liveQuery } from 'dexie';
    import { db_events } from '$lib/ae_events/db_events';
    import { ae_loc } from '$lib/stores/ae_stores';
    import { events_loc, events_sess } from '$lib/stores/ae_events_stores';
    import { Key, Mail, Lock, User, ArrowRight, LoaderCircle, CircleAlert, CircleCheck } from 'lucide-svelte';
    import { untrack } from '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);
        })
    );

    // Form State
    let signin_mode = $state('passcode'); // 'passcode' or 'licensed'
    let passcode = $state('');
    let email = $state('');
    let user_passcode = $state('');
    let status = $state('idle'); // 'idle', 'submitting', 'error', 'success'
    let error_msg = $state('');

    // --- Auto-prefill for Trusted Users ---
    $effect(() => {
        if ($ae_loc.trusted_access && $lq__exhibit_obj?.staff_passcode) {
            untrack(() => {
                if (!passcode) passcode = $lq__exhibit_obj?.staff_passcode ?? '';
            });
        }
    });

    async function handle_signin() {
        if (!$lq__exhibit_obj) return;
        status = 'submitting';
        error_msg = '';

        // Delay for better UX
        await new Promise(r => setTimeout(r, 800));

        if (signin_mode === 'passcode') {
            // 1. Shared Passcode logic
            if (passcode === $lq__exhibit_obj.staff_passcode) {
                // SUCCESS
                complete_signin($lq__exhibit_obj.staff_passcode, 'shared');
            } else {
                status = 'error';
                error_msg = 'Invalid shared passcode. Please check with your booth manager.';
            }
        } else {
            // 2. Licensed User logic
            try {
                // Determine raw JSON string
                const raw_json = $lq__exhibit_obj?.license_li_json;

                // Parse if string, otherwise use empty array
                const licenses = typeof raw_json === 'string' ? JSON.parse(raw_json || '[]') : (Array.isArray(raw_json) ? raw_json : []);

                const found = licenses.find((l: any) => l.email?.toLowerCase() === email.toLowerCase().trim());

                if (found && found.passcode === user_passcode) {
                    // SUCCESS
                    complete_signin(found.email, 'licensed');
                } else {
                    status = 'error';
                    error_msg = 'Invalid email or personal passcode.';
                }
            } catch (e) {
                status = 'error';
                error_msg = 'System error validating licenses.';
            }
        }
    }

    function complete_signin(key: string, type: string) {
        status = 'success';

        // Save to persistent store
        if (!$events_loc.leads.auth_exhibit_kv) $events_loc.leads.auth_exhibit_kv = {};

        $events_loc.leads.auth_exhibit_kv[exhibit_id] = {
            key: key,
            type: type,
            updated_on: new Date().toISOString()
        };

        // Also update session passcode if shared mode
        if (type === 'shared') {
            $events_sess.leads.entered_passcode = key;
        }

        // Trigger a reload or UI update if needed
        // (The parent +page.svelte should reactively update is_signed_in)
    }
</script>

<div class="exhibit-signin card p-6 variant-filled-surface shadow-xl border border-surface-500/20 space-y-6">

    <!-- Tab Toggle -->
    <div class="flex p-1 bg-surface-500/10 rounded-xl">
        <button
            class="flex-1 flex items-center justify-center gap-2 py-2 rounded-lg text-sm font-bold transition-all"
            class:bg-surface-100-900={signin_mode === 'passcode'}
            class:shadow-sm={signin_mode === 'passcode'}
            class:opacity-50={signin_mode !== 'passcode'}
            onclick={() => signin_mode = 'passcode'}
        >
            <Lock size="1.2em" /> Shared Code
        </button>
        <button
            class="flex-1 flex items-center justify-center gap-2 py-2 rounded-lg text-sm font-bold transition-all"
            class:bg-surface-100-900={signin_mode === 'licensed'}
            class:shadow-sm={signin_mode === 'licensed'}
            class:opacity-50={signin_mode !== 'licensed'}
            onclick={() => signin_mode = 'licensed'}
        >
            <User size="1.2em" /> Licensed User
        </button>
    </div>

    <!-- Forms -->
    <form onsubmit={(e) => { e.preventDefault(); handle_signin(); }} class="space-y-4">

        {#if signin_mode === 'passcode'}
            <div class="space-y-2 animate-in fade-in slide-in-from-left-2">
                <label class="label">
                    <span class="text-[10px] uppercase font-bold opacity-50 ml-1 tracking-widest">Booth Passcode</span>
                    <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-soft rounded-xl overflow-hidden border border-surface-500/20">
                        <div class="input-group-shim"><Key size="1.2em" /></div>
                        <input
                            type="text"
                            bind:value={passcode}
                            placeholder="Enter shared code..."
                            class="bg-transparent font-mono tracking-[0.3em] font-bold text-center"
                            autocomplete="off"
                        />
                    </div>
                </label>
            </div>
        {:else}
            <div class="space-y-4 animate-in fade-in slide-in-from-right-2">
                <label class="label">
                    <span class="text-[10px] uppercase font-bold opacity-50 ml-1 tracking-widest">Email Address</span>
                    <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-soft rounded-xl overflow-hidden border border-surface-500/20">
                        <div class="input-group-shim"><Mail size="1.2em" /></div>
                        <input
                            type="email"
                            bind:value={email}
                            placeholder="your@email.com"
                            class="bg-transparent"
                        />
                    </div>
                </label>

                <label class="label">
                    <span class="text-[10px] uppercase font-bold opacity-50 ml-1 tracking-widest">Personal Passcode</span>
                    <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-soft rounded-xl overflow-hidden border border-surface-500/20">
                        <div class="input-group-shim"><Key size="1.2em" /></div>
                        <input
                            type="text"
                            bind:value={user_passcode}
                            placeholder="Your code..."
                            class="bg-transparent font-mono font-bold"
                            autocomplete="off"
                        />
                    </div>
                </label>
            </div>
        {/if}

        {#if status === 'error'}
            <div class="p-3 rounded-lg variant-soft-error flex items-start gap-3 animate-shake">
                <CircleAlert size="1.2em" class="shrink-0 mt-0.5" />
                <p class="text-xs font-bold leading-tight">{error_msg}</p>
            </div>
        {/if}

        <button
            type="submit"
            class="btn btn-lg variant-filled-primary w-full font-bold shadow-lg shadow-primary-500/20 group"
            disabled={status === 'submitting'}
        >
            {#if status === 'submitting'}
                <LoaderCircle size="1.5em" class="animate-spin mr-2" />
                Signing In...
            {:else if status === 'success'}
                <CircleCheck size="1.5em" class="mr-2" />
                Welcome!
            {:else}
                Get Started <ArrowRight size="1.2em" class="ml-2 group-hover:translate-x-1 transition-transform" />
            {/if}
        </button>
    </form>

    <p class="text-[10px] text-center opacity-40 italic">
        Check your welcome email or ask your booth manager for login details.
    </p>

</div>

<style lang="postcss">
    /* Shake animation for errors */
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-4px); }
        75% { transform: translateX(4px); }
    }
    .animate-shake {
        animation: shake 0.2s ease-in-out 0s 2;
    }
</style>