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

	let { data }: Props = $props();

	let log_lvl: number = $state(0);
	// console.log(`ae_events_pres_mgmt location [slug] +page.svelte data:`, data);

	// Imports
	// import type { key_val } from '$lib/ae_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	// import Element_data_store from '$lib/element_data_store_v2.svelte';

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

	import { liveQuery } from 'dexie';
	// import { core_func } from '$lib/ae_core_functions';
	import { db_events } from '$lib/ae_events/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';

	import Comp_event_files_upload from '../../../ae_comp__event_files_upload.svelte';
	import Comp_event_session_obj_li from '../../../ae_comp__event_session_obj_li.svelte';
	import Element_manage_event_file_li_wrap from '$lib/elements/element_manage_event_file_li_direct.svelte';
	import Location_view from './location_view.svelte';
	import Location_page_menu from './location_page_menu.svelte';

	import { browser } from '$app/environment';

	// Variables
	if (browser) {
		console.log('Browser environment detected.');
	}

	// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
	// $slct.account_id = data.account_id;
	// console.log(`$slct.account_id = `, $slct.account_id);
	let ae_acct = data[$slct.account_id];
	// console.log(`ae_acct = `, ae_acct);

	$ae_loc.url_origin = data.url.origin;

	$events_slct.event_id = ae_acct.slct.event_id;
	// $events_slct.event_obj = ae_acct.slct.event_obj;
	$events_slct.event_location_id = ae_acct.slct.event_location_id;
	// $events_slct.event_location_obj = ae_acct.slct.event_location_obj;
	$events_slct.event_session_id = null;
	// $events_slct.event_session_obj = null;
	$events_slct.event_session_obj_li = ae_acct.slct.event_session_obj_li;
	// $events_slct.event_file_obj_li = ae_acct.slct.event_file_obj_li;

	if (!$events_loc.pres_mgmt) {
		$events_loc.pres_mgmt = {};
	}

	if (!$events_sess.pres_mgmt) {
		$events_sess.pres_mgmt = {};
		// $events_sess.pres_mgmt.show_content__agree_text = null;
		// $events_sess.pres_mgmt.show_content__presenter_start = null;
	}

	// $events_sess.pres_mgmt.show_content__agree_text = false;
	// $events_sess.pres_mgmt.show_content__presenter_start = false;

	let lq__event_obj = $derived(
		liveQuery(async () => {
			let results = await db_events.event.get(ae_acct.slct.event_id);
			return results;
		})
	);

	let lq__event_location_obj = $derived(
		liveQuery(async () => {
			let results = await db_events.location.get(ae_acct.slct.event_location_id);
			return results;
		})
	);

	let lq__event_session_obj_li = $derived(
		liveQuery(async () => {
			let results = await db_events.session
				.where('event_location_id')
				.equals(ae_acct.slct.event_location_id)
				.sortBy('start_datetime');
			return results;
		})
	);

	$slct.person_obj_kv = {}; // This is intended for the POC lookup list when generated.

	if (!$ae_loc.authenticated_access && $events_loc.pres_mgmt.show_content__location_view) {
		$events_loc.pres_mgmt.show_content__location_view = null;
	}

	let event_session_id_random_li: Array<string> = $state([]);
	$effect(() => {
		if ($lq__event_session_obj_li) {
			if (log_lvl) {
				console.log('Session list updated? Pulling out the event_session_id_random values.');
			}

			event_session_id_random_li = [];

			// We need to loop through the array of objects and get the event_session_id_random from each object a new list of event_session_id_randoms. Then we can use this list to get the full objects from the database.
			let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.
			if ($lq__event_session_obj_li) {
				for (let i = 0; i < $lq__event_session_obj_li.length; i++) {
					tmp_li.push($lq__event_session_obj_li[i].event_session_id);
				}
			}
			event_session_id_random_li = tmp_li;

			// event_session_id_random_li = $events_slct.event_session_obj_li.map(session_obj => session_obj.event_session_id_random);

			// Finally done with the search.
			$events_sess.pres_mgmt.status_qry__search = 'done';
			// $events_sess.pres_mgmt.status_rpt[$events_sess.pres_mgmt.show_report] = 'done';

			if (log_lvl > 1) {
				console.log(`TEST SEARCH - event_session_id_random_li:`, event_session_id_random_li);
				// console.log(`TEST SEARCH - search live query: ${$lq_kv__event_session_obj_li}`);
			}
		}
	});

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

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

<section
	class="
        ae_events_pres_mgmt_event_location
        md:container
        flex flex-col gap-1
        items-center
        justify-start
        mx-auto
        py-1 px-2 pb-16
        h-full
        min-w-full
        max-w-max
        "
>
	<Location_page_menu {lq__event_obj} {lq__event_location_obj} />

	{#if !$lq__event_location_obj}
		<div>
			<span class="fas fa-spinner fa-spin m-1"></span>
			<span>Loading location information...</span>
		</div>
	{:else if $lq__event_location_obj?.enable || $ae_loc.trusted_access}
		<header class="ae_module_header">
			<h2
				class="
            text-2xl font-bold text-center
            flex flex-row gap-0.25 items-center justify-between w-full
            "
			>
				<span class="flex flex-row gap-1 items-center">
					<span class="fas fa-calendar-day m-1 text-neutral-800/80"></span>
					<!-- Button to toggle between the regular location view and managing location files -->
					<button
						type="button"
						onclick={() => {
							if ($events_loc.pres_mgmt.show_content__location_view == 'manage_files') {
								$events_loc.pres_mgmt.show_content__location_view = null;
							} else {
								$events_loc.pres_mgmt.show_content__location_view = 'manage_files';
							}
						}}
						class="btn btn-md hover:preset-filled-secondary-500"
						class:preset-filled-secondary-500={$events_loc.pres_mgmt.show_content__location_view ==
							'manage_files'}
						class:preset-filled-tertiary-500={$events_loc.pres_mgmt.show_content__location_view !=
							'manage_files'}
						class:hidden={!$ae_loc.administrator_access}
						title="View location information or manage files for the location"
					>
						{#if $events_loc.pres_mgmt.show_content__location_view == 'manage_files'}
							<span class="fas fa-info m-1"></span>
							<!-- View Details -->
							Location Info?
						{:else}
							<span class="fas fa-file-archive m-1"></span>
							Location Files?
							<span class="badge preset-tonal-success" class:hidden={!$lq__event_obj?.file_count}>
								<!-- absolute -top-1.5 -right-1.5 z-10 -->
								<span class="fas fa-file-alt m-1"></span>
								{$lq__event_obj?.file_count}×
							</span>
						{/if}
					</button>
				</span>

				{@html $lq__event_location_obj?.name ?? ae_snip.html__not_set}
			</h2>
		</header>

		{#if !$events_loc.pres_mgmt.show_content__location_view || $events_loc.pres_mgmt.show_content__location_view == 'default'}
			<!-- General information about the location -->
			<Location_view
				hide__launcher_link={$events_loc.pres_mgmt.hide__launcher_link}
				hide__launcher_link_legacy={$events_loc.pres_mgmt.hide__launcher_link_legacy}
				{lq__event_location_obj}
			/>

			<!-- Sessions in the location -->
			<section>
				{#if $lq__event_session_obj_li && $lq__event_session_obj_li?.length > 0 && event_session_id_random_li && event_session_id_random_li?.length > 0}
					<Comp_event_session_obj_li
						{lq__event_session_obj_li}
						hide__session_poc={$events_loc.pres_mgmt.hide__session_poc}
						hide__session_location={true}
						show__session_files={$events_loc.pres_mgmt.show_content__session_files}
						show__session_presentations={$events_loc.pres_mgmt.show_content__session_presentations}
						hide__launcher_link={$ae_loc.administrator_access &&
							$events_loc.pres_mgmt.hide__launcher_link}
						hide__launcher_link_legacy={$events_loc.pres_mgmt.hide__launcher_link_legacy}
						hide__location_link={$events_loc.pres_mgmt.hide__location_link}
						{log_lvl}
					></Comp_event_session_obj_li>
				{:else if $lq__event_session_obj_li && $lq__event_session_obj_li?.length == 0}
					<div class="bg-red-100 p-4 border border-red-200 rounded-md">
						<h2 class="h3">
							<span class="fas fa-exclamation-triangle text-red-500 m-1"></span>
							No Sessions Found
						</h2>
						<p>There are no sessions found for this location.</p>
					</div>
				{:else if event_session_id_random_li?.length > 0}
					<div class="text-center">
						<span class="fas fa-spinner fa-spin m-1"></span>
						<span>Loading session list...</span>
					</div>
				{/if}
			</section>
		{:else if $events_loc.pres_mgmt.show_content__location_view == 'manage_files' && $ae_loc.trusted_access}
			<div>
				<h3 class="h5 text-center">
					<span class="fas fa-tasks m-1 text-neutral-800/80"></span>
					<span class="fas fa-mail-bulk m-1 text-neutral-800/80"></span>
					Manage and Upload Location Files:
				</h3>

				<Comp_event_files_upload
					class_li="border border-gray-300 rounded-md p-2 bg-gray-100 hover:bg-gray-200"
					link_to_type="event_location"
					link_to_id={$lq__event_location_obj.event_location_id}
				>
					{#snippet label()}
						<span>
							<div class="text-lg">
								<span class="fas fa-upload"></span>
								<strong class="">Upload location (room) specific files only!</strong>
							</div>
							<div class="text-sm text-gray-600 dark:text-gray-400 italic">
								<strong>Location (room) files only</strong><br />
								Recommended: PowerPoint (pptx) or Keynote (key)<br />
								Media: Audio and videos files should be directly embedded in PowerPoint (PPTX) files<br
								/>
								Supplemental files: mp4, PDF, Word Doc, Excel, txt, etc
							</div>
						</span>
					{/snippet}
				</Comp_event_files_upload>

				<div class="overflow-x-auto w-max max-w-full">
					<Element_manage_event_file_li_wrap
						link_to_type={'event_location'}
						link_to_id={$lq__event_location_obj?.event_location_id}
						allow_basic={$events_loc.auth__kv.location[$lq__event_location_obj.event_location_id] ||
							$events_loc.auth__kv.location[$lq__event_location_obj?.event_location_id]}
						allow_moderator={$events_loc.auth__kv.location[
							$lq__event_location_obj.event_location_id
						]}
						container_class_li={''}
					/>
				</div>
			</div>
		{/if}
	{:else}
		<div class="bg-red-100 p-4 border border-red-200 rounded-md">
			<h2 class="h3">
				<span class="fas fa-exclamation-triangle text-red-500 m-1"></span>
				Location Disabled
			</h2>
			<p>
				This location is currently disabled. Please contact the event organizer for more
				information.
			</p>
		</div>
	{/if}
</section>
