<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_sess } from '$lib/stores/ae_events_stores';
import { leads_loc } from '$lib/stores/ae_events_stores__leads.svelte';
import {
    ArrowRight,
    CircleAlert,
    CircleCheck,
    Key,
    LoaderCircle,
    Lock,
    Mail,
    User
} 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
    leads_loc.current.auth_exhibit_kv[exhibit_id] = {
        key: key,
        type: type,
        updated_on: new Date().toISOString()
    };

    if (type === 'shared') {
        $events_sess.leads.entered_passcode = key;
        // Shared passcode users land on Manage — their purpose is configuring
        // lead retrieval (licenses, custom questions), not capturing leads.
        leads_loc.current.tab[exhibit_id] = 'manage';
    }
}
</script>

<div
    class="exhibit-signin card preset-tonal-surface border-surface-500/20 space-y-6 border p-6 shadow-xl">
    <!-- Tab Toggle -->
    <div class="bg-surface-500/10 flex rounded-xl p-1">
        <button
            class="flex flex-1 items-center justify-center gap-2 rounded-lg py-2 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 flex-1 items-center justify-center gap-2 rounded-lg py-2 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="animate-in fade-in slide-in-from-left-2 space-y-2">
                <label class="label">
                    <span
                        class="ml-1 text-[10px] font-bold tracking-widest uppercase opacity-50"
                        >Booth Passcode</span>
                    <div
                        class="input-group input-group-divider preset-tonal-surface border-surface-500/20 grid-cols-[auto_1fr] overflow-hidden rounded-xl border">
                        <div class="input-group-shim"><Key size="1.2em" /></div>
                        <input
                            type="text"
                            bind:value={passcode}
                            placeholder="Enter shared code..."
                            class="bg-transparent text-center font-mono font-bold tracking-[0.3em]"
                            autocomplete="off" />
                    </div>
                </label>
            </div>
        {:else}
            <div class="animate-in fade-in slide-in-from-right-2 space-y-4">
                <label class="label">
                    <span
                        class="ml-1 text-[10px] font-bold tracking-widest uppercase opacity-50"
                        >Email Address</span>
                    <div
                        class="input-group input-group-divider preset-tonal-surface border-surface-500/20 grid-cols-[auto_1fr] overflow-hidden rounded-xl border">
                        <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="ml-1 text-[10px] font-bold tracking-widest uppercase opacity-50"
                        >Personal Passcode</span>
                    <div
                        class="input-group input-group-divider preset-tonal-surface border-surface-500/20 grid-cols-[auto_1fr] overflow-hidden rounded-xl border">
                        <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="preset-tonal-error animate-shake flex items-start gap-3 rounded-lg p-3">
                <CircleAlert size="1.2em" class="mt-0.5 shrink-0" />
                <p class="text-xs leading-tight font-bold">{error_msg}</p>
            </div>
        {/if}

        <button
            type="submit"
            class="btn btn-lg preset-filled-primary shadow-primary-500/20 group w-full font-bold shadow-lg"
            disabled={status === 'submitting' || !$lq__exhibit_obj}>
            {#if !$lq__exhibit_obj}
                <!-- Exhibit record still loading from Dexie/API — block submission
                     until it's ready so handle_signin() doesn't return silently. -->
                <LoaderCircle size="1.5em" class="mr-2 animate-spin" />
                Loading...
            {:else if status === 'submitting'}
                <LoaderCircle size="1.5em" class="mr-2 animate-spin" />
                Signing In...
            {:else if status === 'success'}
                <CircleCheck size="1.5em" class="mr-2" />
                Welcome!
            {:else}
                Get Started <ArrowRight
                    size="1.2em"
                    class="ml-2 transition-transform group-hover:translate-x-1" />
            {/if}
        </button>
    </form>

    <p class="text-center text-[10px] italic opacity-40">
        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>
