<script lang="ts">
	interface Props {
		data_url: any;
		slct__event_session_id?: null | boolean | string;
		loading__session_id_status?: null | boolean | string;
		// export let lq__event_session_obj: any;
		lq__event_session_obj_li: any;

		trigger_reload__event_session_obj_id?: boolean | null | string;
		// trigger_reload__event_session_obj_li?: boolean;

		log_lvl?: number;
	}

	let {
		data_url,
		slct__event_session_id = $bindable(null),
		loading__session_id_status = $bindable(null),
		lq__event_session_obj_li,

		trigger_reload__event_session_obj_id = $bindable(false),
		// trigger_reload__event_session_obj_li = $bindable(false),

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

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

	// *** 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_loc,
		events_sess,
		events_slct,
		events_trigger
	} from '$lib/stores/ae_events_stores';
	import { events_func } from '$lib/ae_events_functions';

	// export let slct__event_session_id: any;

	// *** Functions and Logic

	let ae_promises: key_val = $state({
		slct__event_session_id: null,
		slct__event_presentation_li: null
	});

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

	$effect(() => {
		if (trigger_reload__event_session_obj_id) {
			if (log_lvl) {
				console.log(
					`trigger_reload__event_session_obj_id changed: ${trigger_reload__event_session_obj_id}`
				);
			}
			let event_session_id = trigger_reload__event_session_obj_id;
			trigger_reload__event_session_obj_id = false;
			slct__event_session_id = event_session_id;
			console.log(`slct__event_session_id = `, slct__event_session_id);

			handle_load_ae_obj_id__event_session(event_session_id);

			if ($events_loc.launcher.controller == 'local_push') {
				console.log(`Local Push Controller Command: ae_load:event_session=${event_session_id}`);
				$events_sess.launcher.controller_cmd = `ae_load:event_session=${event_session_id}`;
				$events_sess.launcher.controller_trigger_send = true;
			}

			data_url.searchParams.set('session_id', event_session_id);

			let new_url = data_url.toString();
			console.log(new_url);
			// goto(new_url, {replaceState: true}); // Updates the URL without adding a new entry to the history
			goto(new_url, { replaceState: false }); // Updates the URL history without reloading the page
		}
	});

	function handle_load_ae_obj_id__event_session(event_session_id: any) {
		if (log_lvl) {
			console.log(`handle_load_ae_obj_id__event_session: event_session_id = `, event_session_id);
		}

		loading__session_id_status = true;

		// slct__event_session_id = null;

		// slct__event_session_id = event_session_id;
		// $events_slct.event_session_id = event_session_id;
		// data_url.searchParams.set('session_id', event_session_id);

		// let new_url = data_url.toString();
		// console.log(new_url);
		// loading__session_id_status = false;
		// 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
		loading__session_id_status = 'loading';

		// $events_slct.event_session_obj = event_session_obj;

		ae_promises.slct__event_session_id = events_func
			.load_ae_obj_id__event_session({
				api_cfg: $ae_api,
				event_session_id: event_session_id,
				inc_file_li: true,
				inc_presentation_li: true,
				inc_presenter_li: true,
				log_lvl: log_lvl
			})
			.then(async (load_results) => {
				console.log(`load_results = `, load_results);

				$events_slct.event_session_obj = load_results;
				$events_slct.event_file_obj_li = load_results.event_file_li;
				$events_slct.event_presentation_obj_li = load_results.event_presentation_li;
				// $events_slct.event_presenter_obj_li = load_results.event_presenter_obj_li;

				// let new_url = data_url.toString();
				// console.log(new_url);
				// loading__session_id_status = false;
				// // 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
			})
			.finally(() => {
				loading__session_id_status = false;
			});
	}
</script>

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

				<!-- This should fade out once the data is loaded. -->
				{#await ae_promises.slct__event_session_id}
					<span class="fas fa-spinner fa-spin text-blue-500"></span>
				{:then result}
					<span class="fas fa-check text-green-500/80"></span>
				{/await}
			</strong>
		</div>

		<ul
			class="
        space-y-1
        w-full max-w-full
        p-0 m-0
        flex flex-col gap-0.5 items-start justify-start
        transition-all
        "
		>
			{#each $lq__event_session_obj_li as event_session_obj}
				<li
					class="
                p-0 m-0
                w-full max-w-full
                z-0 hover:z-20
                hover:scale-120
                transition-all
                "
				>
					<button
						type="button"
						onmouseenter={() => {
							// Start a 750 ms timer to prevent changing the session too quickly.
							hover_timer = setTimeout(async () => {
								// Only run if the session ID has changed
								if (slct__event_session_id === event_session_obj?.id) {
									return;
								}
								trigger_reload__event_session_obj_id = event_session_obj?.id;
								// handle_load_ae_obj_id__event_session(event_session_obj?.id);

								// loading__session_id_status = true;

								// slct__event_session_id = null;

								// slct__event_session_id = event_session_obj?.id;
								// // $events_slct.event_session_id = event_session_obj?.id;
								// data_url.searchParams.set('session_id', event_session_obj?.id);

								// let new_url = data_url.toString();
								// console.log(new_url);
								// loading__session_id_status = false;
								// // 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
								// loading__session_id_status = 'loading';

								// $events_slct.event_session_obj = event_session_obj;

								// ae_promises.slct__event_session_id = events_func.load_ae_obj_id__event_session({
								//     api_cfg: $ae_api,
								//     event_session_id: event_session_obj?.id,
								//     inc_file_li: true,
								//     inc_presentation_li: true,
								//     inc_presenter_li: true,
								//     log_lvl: log_lvl
								// })
								// .then(async (load_results) => {
								//     console.log(`load_results = `, load_results);

								//     // let new_url = data_url.toString();
								//     // console.log(new_url);
								//     loading__session_id_status = false;
								//     // // 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
								// });
							}, hover_timer_wait);
						}}
						onmouseleave={() => {
							clearTimeout(hover_timer);
						}}
						onclick={async () => {
							trigger_reload__event_session_obj_id = event_session_obj?.id;

							$events_slct.event_file_id = null;
							$events_slct.event_file_obj = null;

							// handle_load_ae_obj_id__event_session(event_session_obj?.id);

							// loading__session_id_status = true;

							// slct__event_session_id = null;
							// // await tick();

							// slct__event_session_id = event_session_obj?.id;
							// // $events_slct.event_session_id = event_session_obj?.id;
							// data_url.searchParams.set('session_id', event_session_obj?.id);

							// let new_url = data_url.toString();
							// console.log(new_url);
							// // 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
							// loading__session_id_status = 'loading';

							// // $events_slct.event_session_id = event_session_obj?.id;
							// $events_slct.event_session_obj = event_session_obj;

							// ae_promises.slct__event_session_id = events_func.load_ae_obj_id__event_session({
							//     api_cfg: $ae_api,
							//     event_session_id: event_session_obj?.id,
							//     inc_file_li: true,
							//     inc_presentation_li: true,
							//     inc_presenter_li: true,
							//     log_lvl: log_lvl
							// })
							// .then(async (load_results) => {
							//     console.log(`load_results = `, load_results);

							//     // let new_url = data_url.toString();
							//     // console.log(new_url);
							//     loading__session_id_status = false;
							//     // // goto(new_url, {replaceState: true}); // Updates the URL history without reloading the page
							//     // goto(new_url, {replaceState: false});
							// });

							// if ($events_loc.launcher.controller == 'local_push') {
							//     console.log(`Local Push Controller Command: ae_load:event_session=${event_session_obj?.id}`);
							//     $events_sess.launcher.controller_cmd = `ae_load:event_session=${event_session_obj?.id}`;
							//     $events_sess.launcher.controller_trigger_send = true;
							// }
						}}
						class="
                btn btn-sm hover:preset-filled-primary-500

                text-sm
                w-full max-w-full
                hover:min-w-fit
                hover:max-w-2xl
                text-left
                m-0
                p-0

                rounded-md
                flex flex-row items-center justify-start
                transition-all
                "
						class:preset-filled-primary-500={slct__event_session_id === event_session_obj?.id}
						class:preset-tonal-secondary={slct__event_session_id != event_session_obj?.id}
						class:border-secondary-500={slct__event_session_id != event_session_obj?.id}
						class:font-bold={slct__event_session_id === event_session_obj?.id}
						class:hidden={!$events_loc.launcher.show_content__hidden_sessions &&
							event_session_obj?.hide}
						class:dim={event_session_obj?.hide}
						title={`Session: ${event_session_obj?.name}\nID: ${event_session_obj?.id} | ${ae_util.iso_datetime_formatter(event_session_obj?.start_datetime, $events_loc.launcher.time_format)}`}
					>
						<!-- hover:scale-115 -->
						<!-- hover:z-index-10     -->

						<span class="border-r border-surface-400-600 pr-1 min-w-28">
							{#if slct__event_session_id === event_session_obj?.id}
								<span class="fas fa-calendar-check"></span>
							{:else}
								<span class="fas fa-calendar-alt"></span>
							{/if}
							<span class="text-xs" class:hidden={slct__event_session_id === event_session_obj?.id}>
								{ae_util.iso_datetime_formatter(event_session_obj?.start_datetime, 'week_medium')}
							</span>
							<span class="text-xs">
								{ae_util.iso_datetime_formatter(
									event_session_obj?.start_datetime,
									$events_loc.launcher.time_format
								)}
							</span>
						</span>

						<span
							class="
                    grow text-xs
                    min-w-32 hover:min-w-fit
                    overflow-hidden hover:overflow-visible
                    trasnition-all
                    "
						>
							{event_session_obj?.name}
						</span>
					</button>
				</li>
			{/each}
		</ul>
	{:else}
		<div class="text-sm">No sessions found.</div>
	{/if}
</div>
