<script lang="ts">
    interface Props {
        /** @type {import('./$types').PageData} */
        data: any;
        log_lvl?: number;
    }

    let { data, log_lvl = $bindable(1) }: Props = $props();

    // *** Import Svelte specific
    import { untrack } from 'svelte';

    // *** Import other supporting libraries
    import { liveQuery } from 'dexie';

    // *** Import Aether specific variables and functions
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import {
        ae_loc,
        ae_api
    } from '$lib/stores/ae_stores';

    import { db_events } from '$lib/ae_events/db_events';
    import {
        events_loc,
        events_sess,
        events_slct,
        events_trigger
    } from '$lib/stores/ae_events_stores';
    import { events_func } from '$lib/ae_events_functions';

    import Comp_badge_search from './ae_comp__badge_search.svelte';
    import Comp_badge_obj_li from './ae_comp__badge_obj_li.svelte';
    import { Modal } from 'flowbite-svelte';
    import Comp_badge_create_form from './ae_comp__badge_create_form.svelte';
    import Comp_badge_upload_form from './ae_comp__badge_upload_form.svelte';
    import { LoaderCircle } from 'lucide-svelte';

    // *** Initialization & Store Guard ***
    // Ensure all search fields are initialized to prevent circular undefined triggers
    if ($events_loc.badges) {
        if (typeof $events_loc.badges.search_version === 'undefined') $events_loc.badges.search_version = 0;
        if (typeof $events_loc.badges.qry__remote_first === 'undefined') $events_loc.badges.qry__remote_first = false;
        if (typeof $events_loc.badges.fulltext_search_qry_str === 'undefined') $events_loc.badges.fulltext_search_qry_str = '';
        if (typeof $events_loc.badges.search_badge_type_code === 'undefined') $events_loc.badges.search_badge_type_code = '';
        if (typeof $events_loc.badges.qry_printed_status === 'undefined') $events_loc.badges.qry_printed_status = 'all';
        if (typeof $events_loc.badges.qry_affiliations === 'undefined') $events_loc.badges.qry_affiliations = '';
        if (typeof $events_loc.badges.qry_sort_order === 'undefined') $events_loc.badges.qry_sort_order = '';
    }

    // Variables
    let show_create_badge_modal: boolean = $state(false);
    let show_upload_badge_modal: boolean = $state(false);

    let event_badge_id_li: Array<string> = $state([]);
    let search_debounce_timer: any = null;
    let last_search_id = 0;
    let last_executed_key = ''; // Search Guard Key

    // Stable LiveQuery Pattern (Aether UI V3)
    let lq__event_badge_obj_li = $derived.by(() => {
        const ids = event_badge_id_li;
        const event_id = $events_slct?.event_id;
        
        return liveQuery(async () => {
            // SCENARIO 1: Specific IDs provided (Search Results)
            if (Array.isArray(ids) && ids.length > 0) {
                if (log_lvl) console.log(`Badge Page LQ: bulkGet ${ids.length} IDs`);
                const results = await db_events.badge.bulkGet(ids);
                return results.filter(item => item !== undefined);
            }
            
            // SCENARIO 2: Fallback broad search (Only if no active filters)
            if (event_id && !$events_loc.badges.fulltext_search_qry_str && $events_loc.badges.qry_printed_status === 'all' && !$events_loc.badges.qry_affiliations && !$events_loc.badges.search_badge_type_code) {
                if (log_lvl) console.log(`Badge Page LQ: Fallback search for event: ${event_id}`);
                return await db_events.badge
                    .where('event_id_random')
                    .equals(event_id)
                    .limit(50)
                    .sortBy('given_name');
            }

            return [];
        });
    });

    // Standardized Reactive Search Pattern (Aether UI V3)
    // 1. Isolate dependencies into a stable derived object
    let search_params = $derived({
        v: $events_loc.badges.search_version,
        str: ($events_loc.badges.fulltext_search_qry_str ?? '').toLowerCase().trim(),
        type: $events_loc.badges.search_badge_type_code,
        printed: $events_loc.badges.qry_printed_status,
        aff: ($events_loc.badges.qry_affiliations ?? '').toLowerCase().trim(),
        sort: $events_loc.badges.qry_sort_order,
        event_id: $events_slct?.event_id,
        remote_first: $events_loc.badges.qry__remote_first
    });

    // 2. Controlled effect for triggering searches
    $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) {
        // 1. Guard
        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;
        
        if (log_lvl) console.log(`[Badge Search #${current_search_id}] Refreshing (remote=${remote_first}, event=${event_id}, str=${params.str})...`);
        
        untrack(() => {
            $events_sess.badges.search_status = 'loading';
            $events_sess.badges.search_complete = false;
        });

        const qry_str = params.str;
        const type_code = params.type;
        const printed_status = params.printed;
        const aff_str = params.aff;

        // 2. FAST PATH: Local IDB Search
        if (!remote_first) {
            try {
                if (event_id) {
                    let local_results = await db_events.badge
                        .where('event_id_random')
                        .equals(event_id)
                        .filter(badge => {
                            if (type_code && badge.badge_type_code !== type_code) return false;
                            
                            if (printed_status !== 'all') {
                                const is_printed = (badge.print_count ?? 0) > 0;
                                if (printed_status === 'printed' && !is_printed) return false;
                                if (printed_status === 'not_printed' && is_printed) return false;
                            }
                            
                            if (qry_str) {
                                const given_name = (badge.given_name ?? '').toLowerCase();
                                const family_name = (badge.family_name ?? '').toLowerCase();
                                const full_name = `${given_name} ${family_name}`.toLowerCase();
                                const email = (badge.email ?? '').toLowerCase();
                                const qry_string = (badge.default_qry_str ?? '').toLowerCase();
                                
                                const match = full_name.includes(qry_str) || 
                                              given_name.includes(qry_str) || 
                                              family_name.includes(qry_str) || 
                                              email.includes(qry_str) ||
                                              qry_string.includes(qry_str);
                                              
                                if (!match) return false;
                            }
                            
                            if (aff_str) {
                                const affiliations = (badge.affiliations ?? '').toLowerCase();
                                if (!affiliations.includes(aff_str)) return false;
                            }
                            
                            return true;
                        })
                        .toArray();

                    // Complex Sort Logic
                    local_results.sort((a, b) => {
                        switch (params.sort) {
                            case 'name_asc':
                                return (a.given_name ?? '').localeCompare(b.given_name ?? '') || (a.family_name ?? '').localeCompare(b.family_name ?? '');
                            case 'name_desc':
                                return (b.given_name ?? '').localeCompare(a.given_name ?? '') || (b.family_name ?? '').localeCompare(a.family_name ?? '');
                            case 'updated_desc':
                                return new Date(b.updated_on || 0).getTime() - new Date(a.updated_on || 0).getTime();
                            case 'updated_asc':
                                return new Date(a.updated_on || 0).getTime() - new Date(b.updated_on || 0).getTime();
                            case 'print_count_desc':
                                return (b.print_count ?? 0) - (a.print_count ?? 0);
                            default:
                                return (a.given_name ?? '').localeCompare(b.given_name ?? '');
                        }
                    });

                    const local_ids = local_results.map(b => b.id || b.event_badge_id_random).filter(Boolean);

                    if (current_search_id === last_search_id) {
                        if (log_lvl) console.log(`[Badge Search #${current_search_id}] Fast Path found ${local_ids.length} items locally.`);
                        untrack(() => {
                            event_badge_id_li = local_ids;
                            if (local_ids.length > 0) $events_sess.badges.search_status = 'done';
                        });
                    }
                }
            } catch (e) {
                if (log_lvl) console.warn('Badge Fast Path failed.', e);
            }
        } else {
            untrack(() => {
                event_badge_id_li = [];
            });
        }

        // 3. REVALIDATE: API Request
        try {
            // Map sort param to API order_by_li
            let order_by_li: any = {};
            switch (params.sort) {
                case 'name_asc': order_by_li = { given_name: 'ASC', family_name: 'ASC' }; break;
                case 'name_desc': order_by_li = { given_name: 'DESC', family_name: 'DESC' }; break;
                case 'updated_desc': order_by_li = { updated_on: 'DESC' }; break;
                case 'updated_asc': order_by_li = { updated_on: 'ASC' }; break;
                case 'print_count_desc': order_by_li = { print_count: 'DESC' }; break;
                default: order_by_li = { given_name: 'ASC' };
            }

            const results = await events_func.search__event_badge({
                api_cfg: $ae_api,
                event_id: event_id,
                fulltext_search_qry_str: qry_str || null,
                type_code: type_code || null,
                printed_status: printed_status,
                affiliations_qry_str: aff_str || null,
                order_by_li: order_by_li,
                limit: 150,
                log_lvl: 0
            });

            if (current_search_id === last_search_id) {
                const api_results = results || [];
                const api_ids = api_results.map((b: any) => b.id || b.event_badge_id_random).filter(Boolean);
                
                untrack(() => {
                    $events_sess.badge_li = api_results;
                    event_badge_id_li = api_ids;
                    $events_sess.badges.search_status = 'done';
                    $events_sess.badges.search_complete = true;
                });
                if (log_lvl) console.log(`[Badge Search #${current_search_id}] Revalidation Complete. Found ${api_ids.length} items.`);
            }
        } catch (error) {
            if (current_search_id === last_search_id) {
                console.error('Badge revalidation failed:', error);
                untrack(() => {
                    $events_sess.badges.search_status = 'error';
                    $events_sess.badges.search_complete = true;
                });
            }
        }
    }
</script>

{#if show_create_badge_modal}
    <Modal bind:open={show_create_badge_modal}>
        <div class="card p-4">
            <h3 class="h3">Create New Badge</h3>
            <Comp_badge_create_form
                event_id={$events_slct?.event_id ?? ''}
                on:success={() => {
                    show_create_badge_modal = false;
                    $events_loc.badges.search_version++;
                }}
                on:cancel={() => (show_create_badge_modal = false)}
            />
        </div>
    </Modal>
{/if}

{#if show_upload_badge_modal}
    <Modal bind:open={show_upload_badge_modal}>
        <div class="card p-4">
            <h3 class="h3">Upload Badges (CSV)</h3>
            <Comp_badge_upload_form
                event_id={$events_slct?.event_id ?? ''}
                on:success={() => {
                    show_upload_badge_modal = false;
                    $events_loc.badges.search_version++;
                }}
                on:cancel={() => (show_upload_badge_modal = false)}
            />
        </div>
    </Modal>
{/if}

<svelte:head>
    <title>
        Badges -
        {ae_util.shorten_string({ string: $events_slct?.event_obj?.name ?? '-- not set --', max_length: 12 })}
        - OSIT's &AElig; Events
    </title>
</svelte:head>

<Comp_badge_search
    event_id={$events_slct?.event_id ?? ''}
    log_lvl={1}
></Comp_badge_search>

{#if $ae_loc.trusted_access}
    <div class="mt-4 text-center">
        <button type="button" class="btn btn-primary" onclick={() => (show_create_badge_modal = true)}>
            <span class="fas fa-plus mr-2"></span> Add New Badge
        </button>
        <button type="button" class="btn btn-primary ml-2" onclick={() => (show_upload_badge_modal = true)}>
            <span class="fas fa-upload mr-2"></span> Upload Badge List
        </button>
    </div>

    <div class="mt-4 text-center p-4 border rounded-md">
        <h4 class="h4">Mass Print Options</h4>
        <div class="flex flex-wrap justify-center gap-2">
            <a
                href={`/events/${$events_slct?.event_id ?? ''}/badges/print_list?printed_status=not_printed`}
                class="btn variant-filled-secondary"
            >
                <span class="fas fa-print mr-2"></span> Print All Unprinted
            </a>
            <a
                href={`/events/${$events_slct?.event_id ?? ''}/badges/print_list?badge_type_code=guest&printed_status=not_printed`}
                class="btn variant-filled-secondary"
            >
                <span class="fas fa-print mr-2"></span> Print Unprinted Guests
            </a>
            <a
                href={`/events/${$events_slct?.event_id ?? ''}/badges/print_list`}
                class="btn variant-filled-secondary"
            >
                <span class="fas fa-print mr-2"></span> Print All
            </a>
        </div>
    </div>

    <div class="mt-4 text-center">
        <a
            href={`/events/${$events_slct?.event_id ?? ''}/badges/templates`}
            class="btn btn-tertiary"
        >
            <span class="fas fa-file-alt mr-2"></span> Manage Badge Templates
        </a>
    </div>
{/if}

{#if $events_sess?.badges?.search_status === 'loading' && event_badge_id_li.length === 0}
    <div class="flex flex-col items-center justify-center p-10 opacity-50 text-center">
        <LoaderCircle size="3em" class="animate-spin mb-4 mx-auto" />
        <p class="text-xl">Loading badges...</p>
    </div>
{:else}
    <Comp_badge_obj_li
        lq__event_badge_obj_li={lq__event_badge_obj_li}
        log_lvl={1}
    ></Comp_badge_obj_li>
{/if}