<script lang="ts">
import { onMount, untrack } from 'svelte';
import { liveQuery } from 'dexie';
import { db_events } from '$lib/ae_events/db_events';
import {
    events_loc,
    events_sess,
    events_slct
} from '$lib/stores/ae_events_stores';
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import { page } from '$app/state';
import { events_func } from '$lib/ae_events/ae_events_functions';
import { LoaderCircle, Store } from '@lucide/svelte';
import Comp_exhibit_search from './ae_comp__exhibit_search.svelte';

// *** Initialization & Store Guard ***
if ($events_loc.leads) {
    if (typeof $events_loc.leads.search_version === 'undefined')
        $events_loc.leads.search_version = 0;
    if (typeof $events_loc.leads.qry__remote_first === 'undefined')
        $events_loc.leads.qry__remote_first = false;
    if (typeof $events_loc.leads.qry__search_text === 'undefined')
        $events_loc.leads.qry__search_text = '';
    if (typeof $events_loc.leads.qry__sort_order === 'undefined')
        $events_loc.leads.qry__sort_order = 'name_asc';
}

let exhibit_id_li: Array<string> = $state([]);
let search_debounce_timer: any = null;
let last_search_id = 0;
let last_executed_key = '';
let log_lvl = 0;

// Stable LiveQuery Pattern
let lq__event_exhibit_obj_li = $derived.by(() => {
    const ids = exhibit_id_li;
    const event_id = page.params.event_id;

    return liveQuery(async () => {
        // SCENARIO 1: Specific IDs provided (Search Results)
        if (Array.isArray(ids) && ids.length > 0) {
            const results = await db_events.exhibit.bulkGet(ids);
            return results.filter((item) => item !== undefined);
        }

        // SCENARIO 2: Fallback broad search
        if (event_id && !$events_loc.leads.qry__search_text) {
            return await db_events.exhibit
                .where('event_id')
                .equals(event_id)
                .sortBy('name');
        }

        return [];
    });
});

// Standardized Reactive Search Pattern
let search_params = $derived({
    v: $events_loc.leads.search_version,
    str: ($events_loc.leads.qry__search_text ?? '').toLowerCase().trim(),
    sort: $events_loc.leads.qry__sort_order,
    event_id: page.params.event_id,
    remote_first: $events_loc.leads.qry__remote_first
});

$effect(() => {
    const params = search_params;
    if (search_debounce_timer) clearTimeout(search_debounce_timer);
    search_debounce_timer = setTimeout(() => {
        untrack(() => {
            handle_search_refresh(params);
        });
    }, 300);
    return () => {
        if (search_debounce_timer) clearTimeout(search_debounce_timer);
    };
});

async function handle_search_refresh(params: any) {
    const qry_key = JSON.stringify(params);
    if (qry_key === last_executed_key) return;
    last_executed_key = qry_key;

    const current_search_id = ++last_search_id;
    const event_id = params.event_id;
    const remote_first = params.remote_first;
    const qry_str = params.str;

    if (!event_id) return;

    // --- Search Constraint: Min 3 characters for non-trusted users ---
    if (!$ae_loc.trusted_access && qry_str.length < 3) {
        if (log_lvl)
            console.log('🛑 [Trace] Search string too short for public user.');
        untrack(() => {
            exhibit_id_li = [];
            $events_sess.leads.submit_status__search = 'idle';
        });
        return;
    }

    if (log_lvl)
        console.log(
            `🔎 [Trace] Exhibit Search #${current_search_id}: START (remote=${remote_first}, event=${event_id}, str=${params.str})`
        );

    untrack(() => {
        $events_sess.leads.submit_status__search = 'searching';
    });

    // 1. FAST PATH: Local IDB Search
    if (!remote_first) {
        try {
            let local_results = await db_events.exhibit
                .where('event_id')
                .equals(event_id)
                .filter((exhibit) => {
                    // Priority Filter for Public
                    if (!$ae_loc.manager_access && !exhibit.priority)
                        return false;

                    if (qry_str) {
                        const name = (exhibit.name ?? '').toLowerCase();
                        const code = (exhibit.code ?? '').toLowerCase();
                        if (!name.includes(qry_str) && !code.includes(qry_str))
                            return false;
                    } else if (!$ae_loc.trusted_access) {
                        // Don't show default results to public if no search string
                        return false;
                    }
                    return true;
                })
                .toArray();

            local_results.sort((a, b) => {
                switch (params.sort) {
                    case 'name_asc':
                        return (a.name ?? '').localeCompare(b.name ?? '');
                    case 'name_desc':
                        return (b.name ?? '').localeCompare(a.name ?? '');
                    case 'code_asc':
                        return (a.code ?? '').localeCompare(b.code ?? '');
                    case 'code_desc':
                        return (b.code ?? '').localeCompare(a.code ?? '');
                    case 'updated_desc':
                        return (
                            new Date(b.updated_on || 0).getTime() -
                            new Date(a.updated_on || 0).getTime()
                        );
                    default:
                        return (a.name ?? '').localeCompare(b.name ?? '');
                }
            });

            const local_ids = local_results
                .map((e) => String(e.id || e.event_exhibit_id))
                .filter(Boolean);

            if (current_search_id === last_search_id) {
                if (log_lvl)
                    console.log(
                        `✅ [Trace] Exhibit Search #${current_search_id}: Local path found ${local_ids.length} items.`
                    );
                untrack(() => {
                    exhibit_id_li = local_ids;
                });
            }
        } catch (e) {
            console.warn('Exhibit Local Search failed.', e);
        }
    }

    // 2. REVALIDATE: API Request
    try {
        let order_by_li: any = {};
        switch (params.sort) {
            case 'name_asc':
                order_by_li = { name: 'ASC' };
                break;
            case 'name_desc':
                order_by_li = { name: 'DESC' };
                break;
            case 'code_asc':
                order_by_li = { code: 'ASC' };
                break;
            case 'code_desc':
                order_by_li = { code: 'DESC' };
                break;
            case 'updated_desc':
                order_by_li = { updated_on: 'DESC' };
                break;
            default:
                order_by_li = { name: 'ASC' };
        }

        const results = await events_func.search__exhibit({
            api_cfg: $ae_api,
            event_id: event_id,
            fulltext_search_qry_str: qry_str || null,
            priority: $ae_loc.manager_access ? 'all' : 'priority',
            order_by_li,
            limit: 100
        });

        if (current_search_id === last_search_id) {
            const api_ids = results
                .map((e: any) => String(e.id || e.event_exhibit_id))
                .filter(Boolean);

            if (log_lvl)
                console.log(
                    `📦 [Trace] Exhibit Search #${current_search_id}: API revalidation found ${api_ids.length} items.`
                );

            untrack(() => {
                exhibit_id_li = api_ids;
                $events_sess.leads.submit_status__search = 'done';
            });
        }
    } catch (error) {
        if (current_search_id === last_search_id) {
            console.error('Exhibit revalidation failed:', error);
            untrack(() => {
                $events_sess.leads.submit_status__search = 'error';
            });
        }
    }
}
</script>

<section
    class="ae_events_leads_new flex h-full w-full flex-col items-center space-y-4 p-4">
    <h1 class="h2">Exhibitor Leads</h1>

    <Comp_exhibit_search event_id={page.params.event_id ?? ''} />

    {#if $events_sess.leads.submit_status__search === 'searching' && exhibit_id_li.length === 0}
        <div
            class="flex flex-col items-center justify-center p-10 text-center opacity-50">
            <LoaderCircle size="3em" class="mx-auto mb-4 animate-spin" />
            <p class="text-xl">Searching exhibits...</p>
        </div>
    {:else if $lq__event_exhibit_obj_li && $lq__event_exhibit_obj_li.length > 0}
        <h2 class="h3">Select your exhibit from the list</h2>
        <div
            class="grid w-full max-w-6xl grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
            {#each $lq__event_exhibit_obj_li as exhibit_obj (exhibit_obj.event_exhibit_id)}
                <!-- Force iframe mode (hides header/footer and passes exhibit_id via URL param) so the exhibit view can optimize for lead capture and hide irrelevant info. -->
                <a
                    href="/events/{page.params
                        .event_id}/leads/exhibit/{exhibit_obj.event_exhibit_id}?iframe=true"
                    class="card card-hover preset-tonal flex flex-col items-center justify-center space-y-2 p-4 text-center">
                    <Store size="2em" />
                    <div class="text-lg font-bold">{exhibit_obj.name}</div>
                    <div class="badge preset-filled-surface-500">
                        Booth #{exhibit_obj.code}
                    </div>
                </a>
            {/each}
        </div>
    {:else}
        <p class="mt-10 opacity-50">No exhibits found matching your search.</p>
    {/if}
</section>
