<script lang="ts">
interface Props {
    // Exports
    container_class_li?: string | Array<string>;
    // export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'
    // event_session_id_random_li: Array<string>;
    event_session_obj_li?: Array<any>;
    link_to_type: string;
    link_to_id: string;
    // export let lq__event_presentation_obj
    log_lvl?: number;
    show_location_fields?: boolean;
    hide_session_code?: boolean;
}

let {
    container_class_li = [],
    // event_session_id_random_li,
    event_session_obj_li = $bindable(),
    link_to_type,
    link_to_id,
    log_lvl = $bindable(0),
    show_location_fields = true,
    hide_session_code = false
}: Props = $props();

// Imports
import Comp_event_session_obj_tbl from './ae_comp__event_session_obj_tbl.svelte';

import { liveQuery } from 'dexie';
import {
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { db_events } from '$lib/ae_events/db_events';

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

// Variables
// let ae_promises: key_val = {};
// let ae_tmp: key_val = {};
// let ae_triggers: key_val = {};

let event_session_id_random_li: Array<string> = $state([]);

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

// *** Functions and Logic

// OPTIMIZATION: If event_session_obj_li is provided (from API/reports),
// use it directly instead of fetching from IDB. The API returns fully
// enriched data with all joined fields (location names, file counts, etc.)
// that aren't available in the base IDB session table.
let lq__event_session_obj_li = $derived(
    liveQuery(async () => {
        let results: any;

        // If data is already provided (from API reports with joins), use it directly
        if (event_session_obj_li?.length) {
            if (log_lvl) {
                console.log(
                    `LQ - Using provided event_session_obj_li (${event_session_obj_li.length} sessions with API joins)`
                );
            }
            return event_session_obj_li;
        }

        // Otherwise fetch from IDB for link_to_type/link_to_id lookups
        if (link_to_type && link_to_id) {
            if (log_lvl) {
                console.log(
                    `LQ - Fetching from IDB where: ${dq__where_type_id_val} = ${dq__where_eq_id_val}`
                );
            }
            event_session_id_random_li = [];
            results = await db_events.session
                .where(dq__where_type_id_val)
                .equals(dq__where_eq_id_val)
                .sortBy('name');
        } else {
            event_session_id_random_li = [];
            results = [];
        }

        // Check if results are different than the current session version stored under $events_slct
        if (
            $events_slct.event_session_obj_li &&
            JSON.stringify($events_slct.event_session_obj_li) !==
                JSON.stringify(results)
        ) {
            $events_slct.event_session_obj_li = [...results];
            if (log_lvl) {
                console.log(
                    `Session slct li stored version has changed for ID = ${$events_slct.journal_id}`,
                    $events_slct.event_session_obj_li
                );
            }
        } else {
            if (log_lvl > 1) {
                console.log(
                    `Session slct li stored version has not changed for ID = ${$events_slct.journal_id}`
                );
            }
        }

        return results;

        // if (event_session_id_random_li.length) {
        //     let results = await db_events.session
        //         .bulkGet(event_session_id_random_li);

        //     return results;
        // } else if (link_to_type && link_to_id) {
        //     console.log(`Trying where: ${dq__where_type_id_val}; equals: ${dq__where_eq_id_val}`);
        //     let results = await db_events.session
        //         .where(dq__where_type_id_val)
        //         .equals(dq__where_eq_id_val)
        //         .sortBy('name')

        //     return results;
        // } else {
        //     return null;
        // }
    })
);
</script>

{#if event_session_obj_li && event_session_obj_li?.length}
    <Comp_event_session_obj_tbl
        {container_class_li}
        {lq__event_session_obj_li}
        {show_location_fields}
        {hide_session_code}
        {log_lvl}></Comp_event_session_obj_tbl>
{:else}
    <section class="flex grow flex-col items-center gap-1 px-1 pb-28 md:px-2">
        <p>No sessions available to show in table.</p>
    </section>
{/if}
