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

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

    // *** Import other supporting libraries
    import {
        Library,
        RemoveFormatting,
        Search,
        LoaderCircle
    } from 'lucide-svelte';

    import { untrack } from 'svelte';
    import { ae_loc } from '$lib/stores/ae_stores';
    import { events_loc, events_sess } from '$lib/stores/ae_events_stores';
    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 logic: Aether Admins go to "all", Licensees go to "my"
    $effect(() => {
        // Wait for object to load and check if initialized
        if (!exhibit_obj) return;
        
        untrack(() => {
            if ($events_loc.leads.tracking__qry__licensee_email === 'all' && !$ae_loc.administrator_access) {
                $events_loc.leads.tracking__qry__licensee_email = 'my';
            }
        });
    });

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

            <select
                bind:value={$events_loc.leads.tracking__qry__sort_order}
                onchange={handle_search_trigger}
                class="select select-sm text-xs px-1 max-w-fit"
            >
                <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={$events_loc.leads.tracking__qry__licensee_email}
                onchange={handle_search_trigger}
                class="select select-sm text-xs px-1 max-w-fit"
            >
                <option value="all">All Leads</option>
                {#if !$ae_loc.administrator_access}
                    <option value="my">My Leads</option>
                {/if}
                {#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 border-primary-500 hover:preset-tonal-primary text-2xl font-bold w-48 transition-all"
            >
                {#if $events_sess.leads.submit_status__search === 'searching'}
                    <LoaderCircle class="animate-spin mx-1" />
                {:else}
                    <Search class="mx-1" />
                {/if}
                Search
            </button>

            <button
                type="button"
                class:hidden={!$events_loc.leads.tracking__qry__search_text}
                onclick={() => {
                    $events_loc.leads.tracking__qry__search_text = '';
                    handle_search_trigger();
                }}
                class="btn btn-sm text-xs preset-outlined-tertiary-100-900 hover:preset-filled-tertiary-100-900 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 hover:opacity-100 transition-all"
    >
        {#if $ae_loc.edit_mode}
            <label
                class="flex items-center gap-1 cursor-pointer bg-surface-200-800 px-2 py-1 rounded-token text-xs font-semibold"
            >
                <span> Remote First </span>
                <input
                    type="checkbox"
                    bind:checked={$events_loc.leads.tracking__qry__remote_first}
                    onchange={handle_search_trigger}
                    class="checkbox checkbox-sm"
                />
            </label>
        {/if}
    </div>
</div>
