<script lang="ts">
	interface Props {
		// Exports
		log_lvl?: number;
		container_class_li?: string | Array<string>;
		// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'
		// link_to_type?: null|string;
		// link_to_id?: null|string;
		lq__event_session_obj_li: any;
		hide__session_location?: boolean;
		hide__session_poc?: boolean;
		hide__admin?: boolean;
		hide__launcher_link_legacy?: boolean;
		hide__launcher_link?: boolean;
		hide__location_link?: boolean;
		show__session_files?: boolean;
		show__session_presentations?: boolean;
	}

	let {
		log_lvl = 0,
		container_class_li = [],
		// link_to_type,
		// link_to_id,
		lq__event_session_obj_li,
		hide__session_location = $bindable(false), // The field in the column or list
		hide__session_poc = $bindable(false), // The field in the column or list
		hide__admin = $bindable(false),
		hide__launcher_link_legacy = $bindable(false),
		hide__launcher_link = $bindable(false),
		hide__location_link = $bindable(false),
		show__session_files = $bindable(false),
		show__session_presentations = $bindable(false)
	}: Props = $props();

	// *** Import Svelte specific

	// *** 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 Element_ae_crud_v2 from '$lib/elements/element_ae_crud_v2.svelte';
	// import Element_data_store from '$lib/element_data_store_v2.svelte';
	import Comp_event_presenter_obj_li from '../events/[event_id]/presenter/ae_comp__event_presenter_obj_li_wrapper.svelte';
	import Element_manage_event_file_li from '$lib/elements/element_manage_event_file_li_direct.svelte';

	import Comp_event_session_alert from '../events/[event_id]/session/ae_comp__event_session_alert.svelte';

	import { core_func } from '$lib/ae_core/ae_core_functions';
	// 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,
		events_trig_kv
	} from '$lib/stores/ae_events_stores';
	import { events_func } from '$lib/ae_events_functions';

	// export let allow_basic: boolean = false;
	// export let allow_moderator: boolean = false;

	// 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 = $state({});
	let ae_triggers: key_val = $state({});
	let trigger_reload_session_id: string = $state('');

	// *** Functions and Logic
</script>

<!-- xs:max-w-sm lg:max-w-100 -->
<!-- sm:border-red-200 md:border-yellow-200 lg:border-gray-100 -->
<section
	class="
        ae_comp event_session_obj_li
        border-x-2 border-dashed border-x-red-500
        sm:border-x-red-400 md:border-x-yellow-400 lg:border-x-transparent
        px-0.5 py-2 space-y-2
        min-w-full
        w-full
        container overflow-x-scroll {container_class_li}
        "
>
	{#if $lq__event_session_obj_li && $lq__event_session_obj_li?.length}
		<h2 class="h3 text-success-800-400">
			<span class="text-sm"> Sessions: </span>

			{#if $lq__event_session_obj_li?.length}
				<span
					class="text-3xl font-bold preset-filled-success-100-900 px-4 rounded-lg"
					title="Count {$lq__event_session_obj_li.length ?? 'None'}"
				>
					<span class="fas fa-list-ol mx-4"></span>
					{$lq__event_session_obj_li.length ?? 'None'}&times;
				</span>
			{/if}
		</h2>

		<table class="table table-auto table-striped">
			<thead>
				<tr>
					<th>Session</th>
					<th>Date</th>
					<th>
						<span class="md:hidden"> Times </span>
						<span class="hidden md:inline"> Start–End </span>
					</th>
					<th class:hidden={hide__session_location}> Location </th>
					<th class:hidden={hide__session_poc}> POC </th>
					<th class:hidden={!$ae_loc.edit_mode || !$ae_loc.adv_mode || hide__admin}> Admin </th>
				</tr>
			</thead>
			<tbody>
				<!-- {#each $events_slct?.event_session_obj_li as session_obj} -->
				{#each $lq__event_session_obj_li as session_obj, index}
					<tr
						class:dim={session_obj?.hide}
						class:bg-warning-100={!session_obj?.enable}
						class:text-warning-900={!session_obj?.enable}
						class:alert={session_obj?.alert}
						class="relative"
					>
						<td>
							{#if session_obj?.alert && $ae_loc.trusted_access}
								<Comp_event_session_alert lq__event_session_obj={session_obj} {log_lvl} />
							{/if}

							<a
								href="/events/{session_obj?.event_id}/session/{session_obj?.event_session_id}"
								class="
                btn
                ae_btn_secondary_filled
                min-w-full max-w-md
                sm:w-80
                text-xs/3 sm:text-xs/4 md:text-xs/4 lg:text-sm/4 xl:text-base/5
                md:max-w-xs
                sm:btn-sm
                md:btn-md
                "
								title={`Code = ${session_obj?.code}\n${session_obj?.name}\nID = ${session_obj?.event_session_id}\nDay = ${ae_util.iso_datetime_formatter(session_obj?.start_datetime, 'dddd')}\nStart = ${ae_util.iso_datetime_formatter(session_obj?.start_datetime, 'time_12_short')}\nEnd = ${ae_util.iso_datetime_formatter(session_obj?.end_datetime, 'time_12_short')}\nLocation = ${session_obj?.event_location_name}`}
							>
								<!-- <span class="fas fa-eye m-0.25 text-xs text-surface-800-200"></span> -->
								<span class="fas fa-chalkboard-teacher m-0.25 text-xs text-neutral-800/50"></span>
								<!-- overflow-x-scroll -->
								<span
									class="
                    grow overflow-hidden text-wrap text-left
                    max-h-12 sm:max-h-12 md:max-h-9 lg:max-h-12 xl:max-h-16
                    "
								>
									<!-- <div> -->
									<strong>{session_obj?.name}</strong>
									<!-- </div> -->
								</span>
								{#if session_obj?.file_count_all}
									<span
										class="badge preset-tonal-success hover:preset-filled-success-500"
										title="{session_obj?.file_count_all}× files under session"
									>
										<span class="fas fa-file-alt mx-1"></span>
										{session_obj?.file_count_all}×
									</span>
								{:else}
									<!-- Nothing -->
								{/if}
							</a>

							{#if show__session_presentations && $ae_loc.manager_access}
								<Comp_event_presenter_obj_li
									link_to_type={'event_session'}
									link_to_id={session_obj?.event_session_id_random}
									display_mode={'minimal'}
									{log_lvl}
								></Comp_event_presenter_obj_li>
							{/if}

							{#if show__session_files && $ae_loc.manager_access}
								<Element_manage_event_file_li
									link_to_type={'event_session'}
									link_to_id={session_obj?.event_session_id_random}
									allow_basic={$events_loc.auth__kv.session[$events_slct.event_session_id] ||
										$events_loc.auth__kv.presenter[$events_slct.event_presenter_id]}
									allow_moderator={$events_loc.auth__kv.session[$events_slct.event_session_id]}
									container_class_li={''}
									display_mode={'minimal'}
								/>
							{/if}
						</td>
						<td>
							<span class="flex flex-col text-xs lg:text-sm">
								<span>
									{ae_util.iso_datetime_formatter(session_obj?.start_datetime, 'dddd')}
								</span>
								<span style="break-inside: avoid;">
									{ae_util.iso_datetime_formatter(
										session_obj?.start_datetime,
										'date_long_month_day'
									)}
								</span>
							</span>
						</td>
						<td>
							<span
								class="flex flex-col items-center md:flex-row md:items-start md:text-center max-w-36 text-xs lg:text-sm"
							>
								{#if session_obj?.start_datetime}
									<span style="break-inside: avoid;">
										{ae_util.iso_datetime_formatter(session_obj?.start_datetime, 'time_12_short')}
									</span>
									<span class="grow"> – </span>
									<span style="break-inside: avoid;">
										{ae_util.iso_datetime_formatter(session_obj?.end_datetime, 'time_12_short')}
									</span>
								{:else}
									{@html ae_snip.html__not_set}
								{/if}
							</span>
						</td>

						<td class:hidden={hide__session_location}>
							<span class="w-full flex flex-row flex-wrap gap-1 items-center justify-between">
								<!-- Minimum level access to see the link here is "trusted". -->
								<!-- {#if hide__launcher_link_legacy && hide__launcher_link && !$ae_loc.edit_mode} -->
								<span>
									{session_obj?.event_location_name ?? '-- not set --'}
								</span>
								<!-- {/if} -->

								<!-- Legacy link (Flask) -->
								<span class="flex flex-row gap-0.5 items-center justify-center">
									<a
										data-sveltekit-preload-data="false"
										href="/event/{session_obj?.event_id}/launcher/{session_obj?.event_location_id}"
										class:hidden={hide__launcher_link_legacy &&
											!($ae_loc.trusted_access && $ae_loc.edit_mode)}
										class="btn btn-sm preset-tonal-secondary hover:preset-filled-secondary-500 transition-all group"
										title={`Legacy Launcher (Flask): ${session_obj?.event_location_name}\n${session_obj?.event_location_id_random}`}
									>
										<span class="fas fa-paper-plane m-1"></span>
										<span class="hidden">
											{@html session_obj?.event_location_name
												? session_obj?.event_location_name
												: ae_snip.html__not_set}
										</span>
									</a>

									<!-- New link (Svelte) -->
									<a
										data-sveltekit-preload-data="false"
										data-sveltekit-reload="true"
										href="/events/{session_obj?.event_id}/launcher/{session_obj?.event_location_id}?session_id={session_obj?.event_session_id}"
										class:hidden={hide__launcher_link &&
											!($ae_loc.trusted_access && $ae_loc.edit_mode)}
										class="btn btn-sm preset-tonal-tertiary hover:preset-filled-secondary-500 group transition-all"
										title={`Launcher (Svelte): ${session_obj?.event_location_name}\n${session_obj?.event_location_id_random}`}
									>
										<span class="fas fa-plane"></span>
										<span class="hidden">
											{@html session_obj.event_location_name
												? session_obj.event_location_name
												: ae_snip.html__not_set}
										</span>
									</a>

									<!-- Location details link -->
									<a
										href="/events/{session_obj?.event_id}/location/{session_obj?.event_location_id}"
										class:hidden={hide__location_link &&
											!($ae_loc.trusted_access && $ae_loc.edit_mode)}
										class="btn btn-sm preset-tonal-surface hover:preset-filled-tertiary-500 group transition-all"
										title={`Location Details: ${session_obj?.event_location_name}\n${session_obj?.event_location_id_random}`}
									>
										<span class="fas fa-map-marker-alt m-1"></span>
										<span class="hidden group-hover:inline">
											{@html session_obj?.event_location_name
												? session_obj?.event_location_name
												: ae_snip.html__not_set}
										</span>
									</a>
								</span>

								{#if $ae_loc.edit_mode && $ae_loc.trusted_access}
									<Element_ae_crud_v2
										api_cfg={$ae_api}
										trigger_patch={ae_triggers.update_location}
										object_type={'event_session'}
										object_id={session_obj?.event_session_id_random}
										object_reload={true}
										field_name={'event_location_id_random'}
										field_type={'select'}
										current_field_value={session_obj?.event_location_id_random}
										allow_null={true}
										select_option_kv={$slct.event_location_obj_kv}
										hide_element={!$ae_loc.edit_mode}
										hide_edit_btn={true}
										bind:show_edit_form={
											$events_sess.pres_mgmt.show__edit_location[
												session_obj?.event_session_id_random
											]
										}
										outline_element={false}
										display_block={false}
										display_absolute_edit={true}
										class_li={'m-1'}
									></Element_ae_crud_v2>
								{/if}

								{#if $events_sess.pres_mgmt.show__edit_location[session_obj?.event_session_id_random]}
									<!-- Nothing here -->
								{:else if $ae_loc.edit_mode}
									<button
										type="button"
										ondblclick={() => {
											console.log(
												'Edit the location for the session. Get the list of locations first.'
											);

											$slct.event_location_obj_li = events_func
												.load_ae_obj_li__event_location({
													api_cfg: $ae_api,
													for_obj_type: 'event',
													for_obj_id: session_obj?.event_id_random,
													limit: 50,
													log_lvl: log_lvl
												})
												.then(function (load_results) {
													console.log(`Loaded event_location_obj_li:`, load_results);

													// We need to make this ready for the select option list. Convert the list to a key value pair with the event_location_id_random as the key. We also need to set the option text value to: name (room)
													if (load_results) {
														let event_location_obj_li = load_results;
														let event_location_obj_kv: key_val = {};
														event_location_obj_kv[''] = '-- Select a location --';
														event_location_obj_li.forEach((event_location_obj) => {
															let option_text = `${event_location_obj.name} (${event_location_obj.code})`;
															event_location_obj_kv[event_location_obj.event_location_id_random] =
																option_text;
														});
														$slct.event_location_obj_kv = event_location_obj_kv;
													}

													console.log(
														`$slct.event_location_obj_kv = `,
														$slct.event_location_obj_kv
													);
													return load_results;
												})
												.finally(function () {
													console.log(`Finally...`);
													ae_tmp.event_location_id = session_obj?.event_location_id_random;
													ae_tmp.show__edit_event_location = true;

													$events_sess.pres_mgmt.show__edit_location[
														session_obj?.event_session_id_random
													] = true;
												});
										}}
										class="
                    btn btn-icon
                    text-xs
                    m-0 px-0.5
                    preset-tonal-warning hover:preset-tonal-error
                    preset-outlined-warning-100-900 hover:preset-outlined-warning-600-400
                    opacity-50 hover:opacity-100
                    transition-all

                    "
									>
										<span class="fas fa-edit m-0.75"></span>
										<!-- group-hover:inline -->
										<span class="hidden">Edit</span>
									</button>
								{/if}
							</span>
						</td>

						<td class:hidden={hide__session_poc}>
							<span
								class="flex flex-col items-start lg:flex-row lg:items-center lg:justify-between text-xs lg:text-sm"
							>
								{#if session_obj?.poc_person_full_name}
									<span style="break-inside: avoid;" class="">
										<span class="fas fa-user m-0.25 text-xs text-surface-800-200"></span>
										{session_obj?.poc_person_full_name}
									</span>
									<!-- <br> -->
									{#if $ae_loc.trusted_access && session_obj?.poc_person_primary_email}
										<span style="break-inside: avoid;" class="text-xs">
											<a
												href="mailto:{session_obj?.poc_person_primary_email}"
												class="hover:underline"
											>
												<span class="fas fa-envelope m-0.25 text-xs text-surface-800-200"></span>
												{session_obj?.poc_person_primary_email}
											</a>
										</span>
									{/if}
								{:else}
									{@html ae_snip.html__not_set}
								{/if}

								{#if $ae_loc.edit_mode && $ae_loc.administrator_access}
									<Element_ae_crud_v2
										api_cfg={$ae_api}
										trigger_patch={ae_triggers.update_person_poc}
										object_type={'event_session'}
										object_id={session_obj?.event_session_id_random}
										object_reload={true}
										field_name={'poc_person_id_random'}
										field_type={'select'}
										current_field_value={session_obj?.poc_person_id_random}
										allow_null={true}
										select_option_kv={$slct.person_obj_kv}
										hide_element={!$ae_loc.edit_mode}
										hide_edit_btn={true}
										bind:show_edit_form={
											$events_sess.pres_mgmt.show__edit_poc_person[
												session_obj?.event_session_id_random
											]
										}
										outline_element={false}
										display_block={false}
										display_absolute_edit={true}
										class_li={'m-1'}
									></Element_ae_crud_v2>

									<button
										type="button"
										ondblclick={() => {
											console.log(
												'Edit the POC person for the session. Get the list of people first.'
											);

											$slct.person_obj_li = core_func
												.load_ae_obj_li__person({
													api_cfg: $ae_api,
													for_obj_type: 'account',
													for_obj_id: $slct.account_id,
													limit: 500,
													log_lvl: log_lvl
												})
												.then(function (load_results) {
													console.log(`Loaded person_obj_li:`, load_results);

													// We need to make this ready for the select option list. Convert the list to a key value pair with the person_id_random as the key. We also need to set the option text value to: full_name (primary_email)
													if (load_results) {
														let person_obj_li = load_results;
														let person_obj_kv: key_val = {};
														person_obj_kv[''] = '-- Select a person --';
														person_obj_li.forEach((person_obj) => {
															let option_text = `${person_obj.full_name} (${person_obj.primary_email})`;
															person_obj_kv[person_obj.person_id_random] = option_text;
														});
														$slct.person_obj_kv = person_obj_kv;
													}

													console.log(`$slct.person_obj_kv = `, $slct.person_obj_kv);
													return load_results;
												})
												.finally(function () {
													console.log(`Finally...`);
													ae_tmp.poc_person_id = session_obj?.poc_person_id_random;
													ae_tmp.show__edit_event_poc_person = true;

													$events_sess.pres_mgmt.show__edit_poc_person[
														session_obj?.event_session_id_random
													] = true;
												});
										}}
										class="
                btn btn-icon
                text-xs
                m-0 px-0.5
                preset-tonal-warning hover:preset-tonal-error
                preset-outlined-warning-100-900 hover:preset-outlined-warning-600-400
                opacity-50 hover:opacity-100
                transition-all

                "
									>
										<span class="fas fa-edit m-0.75"></span>
										<!-- group-hover:inline -->
										<span class="hidden">Edit</span>
									</button>
								{/if}
							</span>
							<!-- flex flex-col items-center md:flex-row md:items-start -->
						</td>

						<td class:hidden={!$ae_loc.edit_mode || !$ae_loc.adv_mode || hide__admin}>
							<!-- Hide session from all lists: session_obj.hide -->
							<!-- <Element_ae_crud_v2
            api_cfg={$ae_api}

            trigger_patch={ae_triggers.update_session_hide}

            object_type={'event_session'}
            object_id={session_obj?.event_session_id_random}
            object_reload={true}

            field_name={'hide'}
            field_type={'select'}

            current_field_value={session_obj?.hide}

            allow_null={true}
            select_option_kv={{null:'NULL', false:'Show', true:'Hide'}}

            hide_element={!$ae_loc.edit_mode}
            hide_edit_btn={false}

            outline_element={false}
            display_block={false}
            display_absolute_edit={true}

            class_li={'m-1'}
            >
            {#if session_obj?.hide}
                <span class="" title="This session is hidden from all lists.">
                    <span class="fas fa-eye-slash mx-1"></span>
                    Hidden
                </span>
            {:else}
                <span class="" title="This session is visible in all lists.">
                    <span class="fas fa-eye mx-1"></span>
                    Visible
                </span>
            {/if}
        </Element_ae_crud_v2> -->
							<button
								type="button"
								onclick={() => {
									console.log('Toggle hide from all lists for the session.');

									let new_hide_value = !session_obj?.hide;
									console.log('New hide value:', new_hide_value);

									ae_promises.api_update__ae_obj = core_func
										.update_ae_obj_id_crud_v2({
											api_cfg: $ae_api,
											object_type: 'event_session',
											object_id: session_obj?.event_session_id_random,
											object_reload: true,
											field_name: 'hide',
											new_field_value: new_hide_value,
											log_lvl: 1
										})
										.then(function (results) {})
										.finally(function () {});
								}}
								class="
                btn btn-icon
                text-xs
                m-0 px-0.5
                preset-tonal-secondary hover:preset-filled-secondary-500
                preset-outlined-secondary-100-900 hover:preset-outlined-secondary-600-400
                opacity-50 hover:opacity-100
                transition-all
                "
								title={session_obj?.hide ? 'Show in all lists' : 'Hide from all lists'}
							>
								{#if session_obj?.hide}
									<span class="fas fa-eye-slash m-0.75"></span>
								{:else}
									<span class="fas fa-eye m-0.75"></span>
								{/if}

								<span class="hidden">Toggle Hide</span>
							</button>
							<!-- group-hover:inline -->

							<!-- Hide from Event Launcher: session_obj.hide_event_launcher -->
							<button
								type="button"
								onclick={() => {
									console.log('Toggle hide from event launcher for the session.');

									let new_hide_event_launcher_value = !session_obj?.hide_event_launcher;
									console.log('New hide_event_launcher value:', new_hide_event_launcher_value);

									ae_promises.api_update__ae_obj = core_func
										.update_ae_obj_id_crud_v2({
											api_cfg: $ae_api,
											object_type: 'event_session',
											object_id: session_obj?.event_session_id_random,
											object_reload: true,
											field_name: 'hide_event_launcher',
											new_field_value: new_hide_event_launcher_value,
											log_lvl: 1
										})
										.then(function (results) {})
										.finally(function () {});
								}}
								class="
                btn btn-icon
                text-xs
                m-0 px-0.5
                preset-tonal-secondary hover:preset-filled-secondary-500
                preset-outlined-secondary-100-900 hover:preset-outlined-secondary-600-400
                opacity-50 hover:opacity-100
                transition-all
                "
								title={session_obj?.hide_event_launcher
									? 'Show in event launcher'
									: 'Hide from event launcher'}
							>
								<!-- <Rocket /> -->
								{#if session_obj?.hide_event_launcher}
									<span class="fas fa-ban m-0.75"></span>
								{:else}
									<span class="fas fa-paper-plane m-0.75"></span>
									<!-- <span class="fas fa-rocket m-0.75"></span> -->
								{/if}
							</button>

							<!-- Toggle alert status -->
							<button
								type="button"
								onclick={() => {
									console.log('Toggle alert status for the session.');

									let new_alert_value = !session_obj?.alert;
									console.log('New alert value:', new_alert_value);

									ae_promises.api_update__ae_obj = core_func
										.update_ae_obj_id_crud_v2({
											api_cfg: $ae_api,
											object_type: 'event_session',
											object_id: session_obj?.event_session_id_random,
											object_reload: true,
											field_name: 'alert',
											new_field_value: new_alert_value,
											log_lvl: 1
										})
										.then(function (results) {})
										.finally(function () {});
								}}
								class:opacity-100={session_obj?.alert}
								class:opacity-50={!session_obj?.alert}
								class="
                btn btn-icon
                text-xs
                m-0 px-0.5
                preset-tonal-warning hover:preset-tonal-error
                preset-outlined-warning-100-900 hover:preset-outlined-warning-600-400
                hover:opacity-100
                transition-all
                "
								title={session_obj?.alert ? 'Remove alert status' : 'Mark as alert'}
							>
								{#if session_obj?.alert}
									<!-- <span class="fas fa-exclamation-triangle m-0.75 text-warning-600" title="This session is marked as an alert."></span> -->
									<span
										class="fas fa-bell-slash m-0.75 text-warning-600"
										title="This session is marked as an alert."
									></span>
								{:else}
									<span
										class="fas fa-bell m-0.75 text-gray-400"
										title="This session is not marked as an alert."
									></span>
								{/if}
								<span class="hidden">Toggle Alert</span>
							</button>
						</td>
					</tr>
				{/each}
			</tbody>
		</table>
		<!-- </section> -->
	{:else}
		<p class="text-center text-2xl bg-gray-100 p-4 rounded-md">
			<span class="fas fa-exclamation-triangle text-2xl text-yellow-500"></span>
			No results to show. Please use the search above to find your session.
			<span class="fas fa-exclamation-triangle text-2xl text-yellow-500"></span>
		</p>
		<!-- <div class="text-sm text-gray-500 text-center"> -->
		<!-- Query results length: {$events_slct.event_session_obj_li?.length}; -->
		<!-- ID list length: {event_session_id_random_li?.length}; -->
		<!-- LQ results length: {$lq__event_session_obj_li?.length} -->
		<!-- LQ KV results length: {$lq_kv__event_session_obj_li?.length} -->
		<!-- </div> -->
	{/if}
</section>
