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

    let { data }: Props = $props();
    let log_lvl: number = $state(1);

    // Imports
    import { Modal } from 'flowbite-svelte';
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import { liveQuery } from 'dexie';
    import { db_events } from '$lib/ae_events/db_events';
    import { ae_snip, ae_loc, ae_api, slct } from '$lib/stores/ae_stores';
    import { events_loc, events_sess, events_slct } from '$lib/stores/ae_events_stores';
    import { events_func } from '$lib/ae_events_functions';

    import Session_view from './session_view.svelte';
    import Session_page_menu from './session_page_menu.svelte';
    import Comp_event_presentation_obj_li from '../../../../ae_comp__event_presentation_obj_li.svelte';

    // STABILITY FIX: Capture URL params as plain constants for the liveQuery
    // closures so the observable sees a stable identifier value. Capturing
    // the raw `data.params` or a reactive store reference here can lead to
    // the liveQuery being recreated or seeing transient values on cold-start.
    const url_session_id = data.params.session_id;
    const url_event_id = data.params.event_id;

    // KNOWN ISSUE (TODO): This page currently depends on related records
    // (presentations, hosted files, presenters) already existing in IndexedDB.
    // On a cold start (empty IDB) the dependent LQs may not re-run in the
    // expected order and the UI can require manual refreshes. Do NOT copy
    // this pattern for critical views until the refactor is implemented.

    // Sync stores in the background
    let ae_acct = $derived(data[data.account_id]);
    $effect(() => {
        if (!ae_acct) return;
        untrack(() => {
            $ae_loc.url_origin = data.url.origin;
            $events_slct.event_id = url_event_id;
            $events_slct.event_session_id = url_session_id;
        });
    });

    // 1. Session Observable
    let lq__event_session_obj = $derived(
        liveQuery(async () => {
            if (log_lvl) console.log(`[LQ] Querying Session: ${url_session_id}`);
            return await db_events.session.get(url_session_id);
        })
    );

    // 2. Presentation List Observable
    let lq__event_presentation_obj_li = $derived(
        liveQuery(async () => {
            if (log_lvl) console.log(`[LQ] Querying Presentations for Session: ${url_session_id}`);
            return await db_events.presentation
                .where('event_session_id')
                .equals(url_session_id)
                .sortBy('name');
        })
    );

    // 3. Other Observables
    let lq__event_obj = $derived(
        liveQuery(async () => await db_events.event.get(url_event_id))
    );

    let lq__event_presenter_obj = $derived(
        liveQuery(async () => {
            if (!$events_slct.event_presenter_id) return null;
            return await db_events.presenter.get($events_slct.event_presenter_id);
        })
    );

    let lq__auth__event_presenter_obj = $derived(
        liveQuery(async () => {
            const pid = $events_loc.auth__person?.presenter_id;
            if (!pid) return null;
            return await db_events.presenter.get(pid);
        })
    );

    if (!$events_loc.pres_mgmt) $events_loc.pres_mgmt = {};
    if (!$events_sess.pres_mgmt) $events_sess.pres_mgmt = {};
</script>

<svelte:head>
    <title>
        Session: {ae_util.shorten_string({
            string: $lq__event_session_obj?.name ?? 'Loading...',
            max_length: 12
        })} - Pres Mgmt
    </title>
</svelte:head>

<section class="ae_events_pres_mgmt_event_session container mx-auto py-1 px-2 pb-16 space-y-6">

    <!-- Pass observable STORES to child components (they use $) -->
    <Session_page_menu {data} {lq__event_session_obj} {lq__auth__event_presenter_obj} />

    <!-- Metadata Section -->
    <div class="bg-surface-50-950 p-4 rounded-container-token shadow-sm border border-surface-200-800">
        <Session_view
            {lq__event_presenter_obj}
            {lq__event_session_obj}
            lq__auth__event_presenter_obj={lq__auth__event_presenter_obj}
            {lq__event_presentation_obj_li}
        />
    </div>

    <!-- Presentation List Section -->
    <div class="w-full">
        <!--
                CRITICAL FIX: Use the pre-loaded data (data.initial_session_obj) as a fallback
                until the `liveQuery` store ($lq...) emits its first value. This avoids
                a blank first-draw when IndexedDB is empty on a cold start — the LQ
                will take over once the DB write completes. Prefer blocking loads
                where possible; use this fallback when you must load asynchronously.
            -->
        <Comp_event_presentation_obj_li
            lq__event_presentation_obj_li={$lq__event_presentation_obj_li ?? data.initial_session_obj?.event_presentation_li ?? []}
            {log_lvl}
        />
    </div>

    <!-- Background Connection Status (Non-blocking) -->
    {#if !$lq__event_session_obj}
        <div class="flex items-center justify-center gap-2 text-surface-400 italic py-4">
            <span class="fas fa-spinner fa-spin"></span>
            <span>Synchronizing with session data...</span>
        </div>
    {/if}
</section>

<!-- Modals -->
<Modal
    title="{$lq__event_presenter_obj?.full_name} Presenter Consent"
    bind:open={$events_sess.pres_mgmt.show_modal__presenter_agree}
    autoclose={false}
>
    <Comp_event_presenter_form_agree {lq__event_presenter_obj} />
    {#snippet footer()}
        <button onclick={() => $events_sess.pres_mgmt.show_modal__presenter_agree = false} class="btn preset-tonal-warning">Close</button>
    {/snippet}
</Modal>
