<script lang="ts">
interface Props {
    exhibit_id: string;
    log_lvl?: number;
}

let { exhibit_id, log_lvl = 0 }: Props = $props();

// *** Import other supporting libraries
import {
    Eye,
    EyeOff,
    Library,
    LoaderCircle,
    RemoveFormatting,
    Search
} from '@lucide/svelte';
import { untrack } from 'svelte';
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 { liveQuery } from 'dexie';
import { db_events } from '$lib/ae_events/db_events';
import { onMount } from 'svelte';

let exhibit_obj: any = $state(null);

onMount(() => {
    const observable = liveQuery(async () => {
        if (!exhibit_id) return null;
        // 1. Try primary lookup
        let res = await db_events.exhibit.get(exhibit_id);
        // 2. Fallback to random ID index
        if (!res) {
            res = await db_events.exhibit
                .where('event_exhibit_id_random')
                .equals(exhibit_id)
                .first();
        }
        return res;
    });
    const subscription = observable.subscribe((value) => {
        exhibit_obj = value;
    });
    return () => subscription.unsubscribe();
});

// Reactive list derived from the exhibit state (Licensed Exhibit Leads Users)
let licensee_li = $derived.by(() => {
    try {
        const raw = exhibit_obj?.license_li_json;
        if (!raw) return [];

        // If it's already an array, return it. If it's a string, parse it.
        if (Array.isArray(raw)) return raw;
        if (typeof raw === 'string') return JSON.parse(raw || '[]');

        return [];
    } catch (e) {
        console.error('Failed to parse licensee_li_json', e);
        return [];
    }
});

// Default selection: resolve to the real identity on first load.
// Also migrates any stale 'my' values persisted from older sessions.
// Identity map: shared passcode → 'shared_passcode'; licensed → their email; admin bypass → 'all'.
$effect(() => {
    if (!exhibit_obj) return;
    untrack(() => {
        const cur = leads_loc.current.tracking__qry__licensee_email;
        // Act on 'all' (first load) OR stale 'my' (persisted from before this change)
        if ((cur === 'all' || cur === 'my') && !$ae_loc.administrator_access) {
            const kv = leads_loc.current.auth_exhibit_kv?.[exhibit_id];
            if (kv?.type === 'shared') {
                leads_loc.current.tracking__qry__licensee_email = 'shared_passcode';
            } else if (kv?.type === 'licensed' && kv.key) {
                leads_loc.current.tracking__qry__licensee_email = kv.key;
            }
            // No kv entry means admin/manager bypass — leave as 'all'
        }
    });
});

function handle_search_trigger() {
    leads_loc.current.tracking__search_version++;
}

function prevent_default<T extends Event>(fn: (event: T) => void) {
    return function (event: T) {
        event.preventDefault();
        fn(event);
    };
}
</script>

<div
    class="ae_group filters_and_search flex w-full flex-col items-center justify-center gap-2">
    <form
        onsubmit={prevent_default(() => {
            handle_search_trigger();
        })}
        autocomplete="off"
        class="search_form preset-tonal-primary flex w-full flex-row flex-wrap items-center justify-center gap-1 rounded-lg px-2 py-2 shadow-sm">
        <div
            class="flex grow flex-col items-center justify-center gap-1 md:flex-row">
            <input
                type="search"
                placeholder="Search leads (name, email, notes)..."
                id="exhibit_tracking_fulltext_search_qry_str"
                bind:value={leads_loc.current.tracking__qry__search_text}
                autocomplete="off"
                data-lpignore="true"
                class="input grow font-mono text-lg transition-all"
                onkeyup={(e) => {
                    if (e.key === 'Enter') {
                        handle_search_trigger();
                    }
                }}
                title="Search by name, email or notes. Press Enter." />

            <select
                bind:value={leads_loc.current.tracking__qry__sort_order}
                onchange={handle_search_trigger}
                class="select select-sm max-w-fit px-1 text-xs">
                <option value="created_desc">Newest First</option>
                <option value="created_asc">Oldest First</option>
                <option value="name_asc">Name ASC</option>
                <option value="name_desc">Name DESC</option>
            </select>

            <select
                bind:value={leads_loc.current.tracking__qry__licensee_email}
                onchange={handle_search_trigger}
                class="select select-sm max-w-fit px-1 text-xs">
                <option value="all">All Leads</option>
                <!-- Shared passcode leads are always a distinct bucket — anyone who signed
                     in with the booth passcode (not a personal license) lands here. -->
                <option value="shared_passcode">Booth (Shared)</option>
                {#each licensee_li as l (l.email)}
                    <option value={l.email}>{l.full_name || l.email}</option>
                {/each}
            </select>
        </div>

        <div class="flex flex-row items-center justify-center gap-1">
            <button
                type="submit"
                class="btn btn-lg preset-tonal-primary border-primary-500 hover:preset-tonal-primary w-48 border text-2xl font-bold transition-all">
                {#if $events_sess.leads.submit_status__search === 'searching'}
                    <LoaderCircle class="mx-1 animate-spin" />
                {:else}
                    <Search class="mx-1" />
                {/if}
                Search
            </button>

            <button
                type="button"
                class:hidden={!leads_loc.current.tracking__qry__search_text}
                onclick={() => {
                    leads_loc.current.tracking__qry__search_text = '';
                    handle_search_trigger();
                }}
                class="btn btn-sm preset-outlined-tertiary-100-900 hover:preset-filled-tertiary-100-900 text-xs transition-all"
                title="Clear search query">
                <RemoveFormatting size="1.25em" />
                <span class="hidden md:inline"> Clear </span>
            </button>
        </div>
    </form>

    <div
        class="flex flex-row flex-wrap items-center justify-center gap-2 opacity-70 transition-all hover:opacity-100">
        <!-- Show/Hide hidden records toggle — always visible -->
        <button
            type="button"
            class="rounded-token flex cursor-pointer items-center gap-1 px-2 py-1 text-xs font-semibold transition-colors"
            class:preset-tonal-warning={leads_loc.current.show_hidden}
            class:preset-tonal-surface={!leads_loc.current.show_hidden}
            onclick={() => {
                leads_loc.current.show_hidden = !leads_loc.current.show_hidden;
                handle_search_trigger();
            }}
            title={leads_loc.current.show_hidden
                ? 'Showing hidden leads — click to hide them'
                : 'Hidden leads excluded — click to show all'}>
            {#if leads_loc.current.show_hidden}
                <Eye size="1em" />
                <span>Showing Hidden</span>
            {:else}
                <EyeOff size="1em" />
                <span>Hidden Excluded</span>
            {/if}
        </button>

        {#if $ae_loc.edit_mode}
            <label
                class="bg-surface-200-800 rounded-token flex cursor-pointer items-center gap-1 px-2 py-1 text-xs font-semibold">
                <span> Remote First </span>
                <input
                    type="checkbox"
                    bind:checked={leads_loc.current.tracking__qry__remote_first}
                    onchange={handle_search_trigger}
                    class="checkbox checkbox-sm" />
            </label>
        {/if}
    </div>
</div>
