<script lang="ts">
/**
 * menu_location_list.svelte — Aether Launcher: Room / Location Selector
 *
 * PURPOSE:
 *   Provides a dropdown for operators to switch between venue rooms (event_location
 *   objects). Selecting a room triggers a session list reload for that room and
 *   navigates the URL to /launcher/{location_id} so the back button works correctly.
 *
 * VISIBILITY:
 *   Rendered only when $ae_loc.edit_mode is true (operator-level access). Regular
 *   attendees and kiosk displays do not see the room selector — they are taken
 *   directly to a URL-encoded room and session without UI controls.
 *
 * DATA FLOW:
 *   lq__event_location_obj_li (Dexie liveQuery, passed from launcher_menu.svelte)
 *   → rendered as <select> options
 *   → onchange writes to $events_slct.event_location_id and launcher_loc.current.slct
 *   → calls handle_load_ae_obj_li__event_session() to fetch sessions for the new room
 *   → navigates to /launcher/{location_id} via goto()
 *
 * NOTE — slct_event_location_id binding:
 *   Declared $bindable() so the parent can pass the initial selected value via bind:.
 *   The onchange handler also writes directly to the canonical stores
 *   ($events_slct.event_location_id) to keep other parts of the launcher in sync.
 */
interface Props {
    loading__session_li_status?: null | boolean | string;
    lq__event_location_obj_li: any;
    slct_event_location_id?: string | null;

    trigger_reload__event_session_obj_li?: boolean;
    trigger_reload__event_location_obj_li?: boolean;

    log_lvl?: number;
}

let {
    loading__session_li_status = $bindable(null),
    lq__event_location_obj_li,
    slct_event_location_id = $bindable(null),

    trigger_reload__event_session_obj_li = $bindable(false),
    trigger_reload__event_location_obj_li = $bindable(false),

    log_lvl = $bindable(0)
}: Props = $props();

// *** Import Svelte specific
import { page } from '$app/state';
import { goto } from '$app/navigation';
// import { liveQuery } from "dexie";
// import { tick } from 'svelte';

// *** Import other supporting libraries

// *** Import Aether specific variables and functions
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
// import { db_events } from "$lib/db_events";
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import {
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { launcher_loc } from '$lib/stores/ae_events_stores__launcher.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';
import { Check, LoaderCircle } from '@lucide/svelte';
// export let slct_event_session_id: any;

// *** Functions and Logic

let ae_promises: key_val = $state({
    slct_event_location_id: null
});

// let hover_timer_wait = 1000;
// let hover_timer: any = $state(null);

function handle_load_ae_obj_li__event_session(event_location_id: string) {
    if (log_lvl) {
        console.log(
            `handle_load_ae_obj_li__event_session: event_location_id = ${event_location_id}`
        );
    }
    if (!event_location_id) {
        console.warn(
            `handle_load_ae_obj_li__event_session: No event_location_id provided.`
        );
        return;
    }

    loading__session_li_status = true;

    ae_promises[event_location_id] = events_func
        .load_ae_obj_li__event_session({
            api_cfg: $ae_api,
            for_obj_type: 'event_location',
            for_obj_id: event_location_id,
            inc_file_li: true, // Only include files directly under the session?
            inc_all_file_li: false, // Also include files under presentations and presenters as well?
            inc_presentation_li: true,
            inc_presenter_li: true,
            enabled: launcher_loc.current.show_content__enabled_sessions
                ? 'all'
                : 'enabled',
            hidden: launcher_loc.current.show_content__hidden_sessions
                ? 'all'
                : 'not_hidden',
            limit: 49,
            try_cache: true,
            log_lvl: 1
        })
        .then(async function (load_results) {
            console.log(`load_results = `, load_results);

            let event_session_id_li = [];

            let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

            for (let i = 0; i < load_results.length; i++) {
                let event_session_obj = load_results[i];
                let event_session_id = event_session_obj.event_session_id;
                tmp_li.push(event_session_id);
            }
            event_session_id_li = tmp_li;
            console.log(`event_session_id_li:`, event_session_id_li);
            // $events_slct.id_li__event_session = event_session_id_li;

            loading__session_li_status = false;

            return load_results;
        });

    return ae_promises[event_location_id];
}
</script>

<!-- text-neutral-800/80 -->
<div
    class="
        flex w-full
        max-w-full flex-col flex-wrap items-center justify-center gap-1 md:flex-row
        ">
    {#if $lq__event_location_obj_li && $lq__event_location_obj_li.length > 0}
        <div class="text-surface-600-400 text-xs">
            <strong>
                Location:
                <span
                    class:hidden={!$ae_loc.trusted_access ||
                        !$ae_loc.edit_mode}>
                    ({$lq__event_location_obj_li?.length}&times;)
                </span>

                <!-- This should fade out once the data is loaded. -->
                {#await ae_promises[slct_event_location_id ?? '']}
                    <LoaderCircle
                        size="0.85em"
                        class="inline animate-spin text-blue-500" />
                {:then result}
                    <Check size="0.85em" class="inline text-green-500/80" />
                {/await}
            </strong>
        </div>

        <select
            class="select max-w-42 p-1 text-xs"
            bind:value={slct_event_location_id}
            onchange={async () => {
                // console.log(`slct_event_location_id:`, slct_event_location_id);

                loading__session_li_status = true;

                console.log('Remove fields from the URL.');
                let new_url_obj = new URL(page.url);
                // new_url_obj.searchParams.delete('location_id');
                new_url_obj.searchParams.delete('presentation_id');
                new_url_obj.searchParams.delete('presenter_id');
                new_url_obj.searchParams.delete('session_id');

                // let url_location_id = slct_event_location_id;
                // new_url_obj.searchParams.set('location_id', url_location_id);

                let new_url = `/events/${$events_slct.event_id}/launcher`;

                if (slct_event_location_id) {
                    loading__session_li_status = 'loading';

                    launcher_loc.current.slct.event_location_id =
                        slct_event_location_id;
                    $events_slct.event_location_id = slct_event_location_id;

                    // Load the sessions for this location
                    await handle_load_ae_obj_li__event_session(
                        slct_event_location_id
                    );

                    new_url = `/events/${$events_slct.event_id}/launcher/${slct_event_location_id}`;

                    loading__session_li_status = 'finished';
                } else {
                    // This will hide the selected session if the location is changed to false.
                    // WARNING: This may need to be commented out later.
                    // slct_event_session_id = null;
                    launcher_loc.current.slct.event_location_id = null;
                    $events_slct.event_location_id = null;
                    launcher_loc.current.slct.event_session_id = null;
                    $events_slct.event_session_id = null;

                    loading__session_li_status = 'finished';
                    // WARNING: This may need to be commented out later.
                }

                loading__session_li_status = null;
                // goto(new_url, {replaceState: true}); // Updates the URL without reloading the page
                goto(new_url, { replaceState: false }); // Updates the URL history without reloading the page
            }}>
            <option value="" class="text-surface-800-200 italic">
                -- select --
            </option>
            {#each $lq__event_location_obj_li as event_location_obj (event_location_obj.event_location_id)}
                <option value={event_location_obj?.id}>
                    {event_location_obj?.name}
                </option>
            {/each}
        </select>
    {:else}
        <div class="text-sm">
            No locations found.
            <!-- (Event ID: {$lq__event_obj?.id}) -->
        </div>
    {/if}
</div>
