<script lang="ts">
    /**
     * src/routes/events/[event_id]/(leads)/leads/exhibit/[exhibit_id]/ae_comp__lead_qr_scanner.svelte
     * Badge QR Scanner for adding leads.
     *
     * scan_qualify modes (controlled by parent ae_tab__add):
     *  - 'rapid':   after add → auto-reset scanner (scan next person fast)
     *  - 'qualify': after add → navigate to lead detail (fill notes/qualifiers)
     */
    import { page } from '$app/state';
    import { goto } from '$app/navigation';
    import { liveQuery } from 'dexie';
    import { db_events } from '$lib/ae_events/db_events';
    import { ae_api } from '$lib/stores/ae_stores';
    import { events_loc } from '$lib/stores/ae_events_stores';
    import { events_func } from '$lib/ae_events_functions';
    import Element_qr_scanner_v3 from '$lib/element_qr_scanner_v3.svelte';
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import { LoaderCircle, UserPlus, CheckCircle, CircleAlert, Eye } from 'lucide-svelte';
    import type { ae_EventBadge } from '$lib/types/ae_types';

    interface Props {
        exhibit_id: string;
        scan_qualify?: 'rapid' | 'qualify';
        on_lead_added?: (badge: ae_EventBadge) => void;
    }

    let { exhibit_id, scan_qualify = 'rapid', on_lead_added }: Props = $props();

    // Track existing leads to prevent duplicates
    let existing_leads_map = $derived(
        liveQuery(async () => {
            const leads = await db_events.exhibit_tracking
                .where('event_exhibit_id')
                .equals(exhibit_id)
                .toArray();

            const map = new Map();
            leads.forEach(l => {
                const b_id = l.event_badge_id_random || l.event_badge_id?.toString();
                if (b_id) map.set(b_id, l.event_exhibit_tracking_id_random || l.event_exhibit_tracking_id?.toString());
            });
            return map;
        })
    );

    let start_qr_scanner = $state(true);
    let scanning_status = $state('idle'); // idle, scanning, found, adding, success, error, already_added
    let found_badge: ae_EventBadge | null = $state(null);
    let existing_tracking_id = $state('');
    let new_tracking_id = $state(''); // ID of the lead just created — used for "View Details" link
    let error_msg = $state('');

    async function handle_qr_scan_result(event: { detail: { result: string; entry_method: string } }) {
        const qr_result = event.detail.result;
        const obj = ae_util.process_data_string(qr_result);

        if (obj && obj.type === 'event_badge' && obj.id) {
            start_qr_scanner = false;

            // Check if already exists
            if ($existing_leads_map?.has(obj.id)) {
                scanning_status = 'already_added';
                existing_tracking_id = $existing_leads_map.get(obj.id);
            } else {
                scanning_status = 'found';
            }

            // Load full badge info
            try {
                found_badge = await events_func.load_ae_obj_id__event_badge({
                    api_cfg: $ae_api,
                    event_badge_id: obj.id,
                    log_lvl: 1
                });
            } catch (e) {
                console.error('Failed to load badge info', e);
            }
        } else {
            scanning_status = 'error';
            error_msg = 'Invalid QR code. Please scan an Event Badge.';
        }
    }

    async function confirm_add_lead() {
        if (!found_badge || !found_badge.event_badge_id_random) return;

        scanning_status = 'adding';

        // Use the actual signed-in licensed user's email
        const user_email = $events_loc.leads.auth_exhibit_kv?.[exhibit_id]?.key || 'shared_passcode';

        try {
            const result = await events_func.create_ae_obj__exhibit_tracking({
                api_cfg: $ae_api,
                exhibit_id: exhibit_id,
                event_badge_id: found_badge.event_badge_id_random,
                external_person_id: user_email,
                group: user_email
            });

            if (result) {
                // Capture the new tracking ID so we can link to it
                new_tracking_id = result.event_exhibit_tracking_id_random || String(result.event_exhibit_tracking_id || '');
                scanning_status = 'success';
                if (on_lead_added) on_lead_added(found_badge);

                if (scan_qualify === 'qualify' && new_tracking_id) {
                    // Qualify mode: navigate directly to lead detail to fill in notes/qualifiers
                    goto(`/events/${page.params.event_id}/leads/exhibit/${exhibit_id}/lead/${new_tracking_id}`);
                } else {
                    // Rapid mode: auto-reset after 2 seconds to scan the next person
                    setTimeout(reset_scanner, 2000);
                }
            }
        } catch (e) {
            scanning_status = 'error';
            error_msg = 'Failed to add lead. They might already be added.';
        }
    }

    function reset_scanner() {
        scanning_status = 'idle';
        found_badge = null;
        new_tracking_id = '';
        error_msg = '';
        start_qr_scanner = true;
    }
</script>

<div class="lead-qr-scanner flex flex-col items-center space-y-4 w-full min-h-100 justify-center">
    {#if scanning_status === 'idle' || scanning_status === 'scanning'}
        <div class="w-full max-w-sm mx-auto aspect-square overflow-hidden rounded-xl border-4 border-surface-500/20 shadow-xl relative bg-surface-900/10">
            <Element_qr_scanner_v3
                bind:start_qr_scanner
                on_qr_scan_result={handle_qr_scan_result}
            />
            <div class="absolute inset-0 pointer-events-none border-2 border-primary-500/50 m-8 sm:m-12 rounded-lg animate-pulse"></div>
        </div>
        <p class="text-center opacity-70 italic text-sm">Point camera at the badge QR code</p>

    {:else if scanning_status === 'already_added'}
        <div class="card p-6 w-full max-w-md space-y-4 variant-soft-secondary shadow-xl border-2 border-secondary-500 animate-in zoom-in">
            <div class="text-center space-y-2">
                <CheckCircle size="3em" class="mx-auto text-secondary-500" />
                <h3 class="h3 font-bold">Already Captured</h3>
                <p class="text-xl font-bold">{found_badge?.full_name || 'Attendee'}</p>
                <p class="opacity-70 text-sm">This attendee is already in your leads list.</p>
            </div>

            <a
                href={`/events/${page.params.event_id}/leads/exhibit/${exhibit_id}/lead/${existing_tracking_id}`}
                class="btn btn-xl w-full variant-filled-secondary font-bold py-6"
            >
                <Eye size="1.5em" class="mr-2" />
                View Lead Details
            </a>

            <button
                type="button"
                class="btn btn-sm w-full opacity-50"
                onclick={reset_scanner}
            >
                Scan Next
            </button>
        </div>

    {:else if scanning_status === 'found' || scanning_status === 'adding'}
        <div class="card p-6 w-full max-w-md space-y-4 variant-soft-primary shadow-xl border-2 border-primary-500">
            <div class="text-center">
                <h3 class="h3 font-bold">{found_badge?.full_name || 'Badge Found'}</h3>
                <p class="opacity-70">{found_badge?.affiliations || ''}</p>
            </div>

            <button
                type="button"
                class="btn btn-xl w-full preset-filled-primary font-bold py-6"
                disabled={scanning_status === 'adding'}
                onclick={confirm_add_lead}
            >
                {#if scanning_status === 'adding'}
                    <LoaderCircle class="animate-spin mr-2" size="1.5em" />
                    Adding Lead...
                {:else}
                    <UserPlus size="1.5em" class="mr-2" />
                    Add as Lead
                {/if}
            </button>

            <button
                type="button"
                class="btn btn-sm w-full opacity-50"
                disabled={scanning_status === 'adding'}
                onclick={reset_scanner}
            >
                Cancel / Scan Again
            </button>
        </div>

    {:else if scanning_status === 'success'}
        <div class="card p-10 w-full max-w-md flex flex-col items-center space-y-4 variant-soft-success shadow-xl">
            <CheckCircle size="4em" class="text-success-500 animate-bounce" />
            <div class="text-center">
                <h3 class="h4 font-bold">Lead Added!</h3>
                <p class="text-xl font-bold">{found_badge?.full_name}</p>
            </div>
            <!-- In rapid mode: offer a View Details escape hatch while the reset countdown runs -->
            {#if new_tracking_id}
                <a
                    href={`/events/${page.params.event_id}/leads/exhibit/${exhibit_id}/lead/${new_tracking_id}`}
                    class="btn btn-sm variant-ghost-surface w-full"
                >
                    <Eye size="1em" class="mr-1" /> View Details
                </a>
            {/if}
            <p class="text-sm opacity-40">Resetting scanner...</p>
        </div>

    {:else if scanning_status === 'error'}
        <div class="card p-6 w-full max-w-md flex flex-col items-center space-y-4 variant-soft-error">
            <CircleAlert size="3em" class="text-error-500" />
            <p class="text-center font-bold">{error_msg}</p>
            <button type="button" class="btn btn-sm preset-filled-error" onclick={reset_scanner}>
                Try Again
            </button>
        </div>
    {/if}
</div>