<script lang="ts">
interface Props {
    container_class_li?: string | Array<string>;
    event_id_li?: Array<string>;
    link_to_type: string;
    link_to_id: string;
    order_by?: string;
    hide?: string;
    enable?: string;
    limit?: number;
    offset?: number;
    log_lvl?: number;
}

let {
    container_class_li = '',
    event_id_li = [],
    link_to_type = 'account',
    link_to_id,
    order_by = 'updated_on',
    hide = 'not_hidden', // all, hidden, not_hidden
    enable = 'enabled', // all, disabled, enabled
    limit = 0,
    offset = 0,
    log_lvl = $bindable(0)
}: Props = $props();

// *** Import other supporting libraries
import { liveQuery } from 'dexie';
import { db_events } from '$lib/ae_events/db_events';

// *** Import Aether specific variables and functions
import Comp__event_obj_li from './ae_idaa_comp__event_obj_li.svelte';

$effect(() => {
    if (log_lvl) {
        console.log(
            `Wrapper: link_to_type: ${link_to_type}; link_to_id: ${link_to_id}`
        );
    }
});

let dq__where_type_id_val = $derived(`${link_to_type}_id`);
let dq__where_eq_id_val = $derived(link_to_id);

/**
 * Stable LiveQuery Pattern (Aether UI V3)
 *
 * WHY: We use $derived.by to synchronously track the 'event_id_li' prop.
 * This ensures that whenever the parent search logic updates the ID list,
 * Svelte recreates this Dexie observable and triggers a fresh UI render.
 */
let lq__event_obj_li = $derived.by(() => {
    // SVELTE 5 REACTIVITY: Track IDs synchronously
    const ids = event_id_li;

    return liveQuery(async () => {
        // SCENARIO 1: Specific IDs provided (from Search Fast Path or API)
        if (Array.isArray(ids)) {
            if (ids.length > 0) {
                if (log_lvl)
                    console.log(`Wrapper LQ: bulkGet ${ids.length} IDs`);
                const results = await db_events.event.bulkGet(ids);
                // bulkGet returns undefined for missing keys; we filter those out.
                return results.filter((item) => item !== undefined);
            } else {
                if (log_lvl) console.log('Wrapper LQ: Explicitly empty list');
                return [];
            }
        }

        // SCENARIO 2: Fallback broad search
        else if (link_to_id) {
            if (log_lvl)
                console.log(
                    `Wrapper LQ: Fallback search for ${link_to_type}: ${link_to_id}`
                );
            const base_query = db_events.event
                .where(dq__where_type_id_val)
                .equals(link_to_id);

            const results = await base_query
                .and((ev) => !ev.hide && !!ev.enable)
                .limit(limit > 0 ? limit : 500)
                .toArray();

            if (order_by === 'name_asc' || order_by === 'name') {
                results.sort((a, b) =>
                    (a.name ?? '').localeCompare(b.name ?? '')
                );
            } else if (order_by === 'name_desc') {
                results.sort((a, b) =>
                    (b.name ?? '').localeCompare(a.name ?? '')
                );
            } else {
                // Events use legacy tmp_sort_1 encoding (ae_events__event.ts: priority ? 1 : 0),
                // NOT build_tmp_sort's inverted encoding. priority=true→'1' > priority=false→'0',
                // so DESCENDING sort puts priority items first.
                results.sort((a, b) =>
                    (b.tmp_sort_1 ?? '').localeCompare(a.tmp_sort_1 ?? '')
                );
            }
            return results;
        }
        return null;
    });
});
</script>

{#if $lq__event_obj_li}
    <Comp__event_obj_li
        {container_class_li}
        {link_to_type}
        {link_to_id}
        {lq__event_obj_li}
        {log_lvl}></Comp__event_obj_li>
{:else}
    <div class="space-y-2">
        <div class="ae_highlight ae_padding_md ae_row ae_flex_justify_center">
            <span class="fas fa-spinner fa-spin m-1"></span>
            Loading...
        </div>
    </div>
{/if}
