<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 event [session_id] +page.svelte data:`, data);

	// Imports
	import { Modal } from 'flowbite-svelte';

	import type { key_val } from '$lib/stores/ae_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	import Element_data_store from '$lib/elements/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/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_presenter_form_agree from '../../presenter/[presenter_id]/ae_comp__event_presenter_form_agree.svelte';
	import Element_manage_event_file_li_wrap from '$lib/elements/element_manage_event_file_li_direct.svelte';
	import Session_view from './session_view.svelte';
	import Session_page_menu from './session_page_menu.svelte';
	import Comp_event_session_alert from '../ae_comp__event_session_alert.svelte';
	// import Sign_in_out from './../../sign_in_out.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_session_id = ae_acct.slct.event_session_id;
	// $events_slct.event_session_obj = ae_acct.slct.event_session_obj;
	$events_slct.event_presentation_id = null;
	// $events_slct.event_presentation_obj = null;
	$events_slct.event_presentation_obj_li = ae_acct.slct.event_presentation_obj_li;
	// $events_slct.event_file_obj_li = ae_acct.slct.event_file_obj_li;

	if (!$events_loc.auth__person) {
		$events_loc.auth__person = {
			id: null,
			email: null,
			full_name: null,
			entered_key: null,
			entered_passcode: null
		};
	}

	if (!$events_loc.auth__kv) {
		$events_loc.auth__kv = {
			session: {},
			presentation: {},
			presenter: {},
			person: {}
		};
	}

	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($events_slct.event_id);
			return results;
		})
	);

	let lq__event_session_obj = $derived(
		liveQuery(async () => {
			let results = await db_events.session.get(ae_acct.slct.event_session_id);
			return results;
		})
	);

	let lq__event_presentation_obj_li = $derived(
		liveQuery(async () => {
			if (!$lq__event_session_obj?.event_session_id) return [];
			let results = await db_events.presentation
				.where('event_session_id') // This field contains the random ID
				.equals($lq__event_session_obj.event_session_id) // Compare against the random ID
				.sortBy('name');
			return results;
		})
	);

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

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

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

	// JSON formatted configuration options for an event, and specifically for the presentation management module.
	$effect(() => {
		if ($lq__event_obj?.mod_pres_mgmt_json) {
			// if (log_lvl) {
			//     console.log(`*** Event Pres Mgmt JSON *** pres_mgmt_cfg_local`, $events_loc.pres_mgmt);
			// }
			// $events_loc.pres_mgmt =
			events_func.sync_config__event_pres_mgmt({
				pres_mgmt_cfg_remote: $lq__event_obj?.mod_pres_mgmt_json,
				pres_mgmt_cfg_local: $events_loc?.pres_mgmt,
				log_lvl: log_lvl
			});
			// if (log_lvl) {
			//     console.log(`*** Event Pres Mgmt JSON *** pres_mgmt_cfg_local`, $events_loc.pres_mgmt);
			// }
		}
	});

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

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

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

<section
	class="
        ae_events_pres_mgmt_event_session
        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
        "
>
	<Session_page_menu {data} {lq__event_session_obj} {lq__auth__event_presenter_obj} />

	{#if !$lq__event_session_obj}
		<div>
			<span class="fas fa-spinner fa-spin m-1"></span>
			<span>Loading session information...</span>
		</div>
	{:else if $lq__event_session_obj?.enable || $ae_loc.trusted_access}
		<header class="ae_module_header relative">
			{#if $lq__event_session_obj?.alert && $ae_loc.trusted_access}
				<Comp_event_session_alert
					lq__event_session_obj={$lq__event_session_obj}
					position="top"
					{log_lvl}
				/>
			{/if}

			<span class="flex flex-row flex-wrap gap-1 items-center justify-center">
				<!-- <span class="fas fa-calendar-day m-1"></span> -->
				<span class="fas fa-chalkboard-teacher m-1 text-neutral-800/80"></span>
				<!-- Button to toggle between the regular session view and managing session files -->
				<button
					type="button"
					onclick={() => {
						if ($events_loc.pres_mgmt.show_content__session_view == 'manage_files') {
							$events_loc.pres_mgmt.show_content__session_view = null;
						} else {
							$events_loc.pres_mgmt.show_content__session_view = 'manage_files';
						}
					}}
					class="btn btn-md hover:preset-filled-primary-500"
					class:preset-tonal-tertiary={$events_loc.pres_mgmt.show_content__session_view ==
						'manage_files'}
					class:preset-filled-tertiary-500={$events_loc.pres_mgmt.show_content__session_view !=
						'manage_files'}
					class:hidden={!$ae_loc.public_access}
					title="View session information or manage files for the session"
				>
					{#if $events_loc.pres_mgmt.show_content__session_view == 'manage_files'}
						<span class="fas fa-users m-1"></span>
						<!-- View Details -->
						Session Presenters?
					{:else}
						<span class="fas fa-file-archive m-1"></span>
						Session Files?
						<span
							class="badge preset-tonal-success"
							class:hidden={!$lq__event_session_obj?.file_count}
						>
							<span class="fas fa-file-alt m-1"></span>
							{$lq__event_session_obj?.file_count}×
						</span>
					{/if}
				</button>
			</span>

			<span class="grow flex flex-row flex-wrap gap-2 items-center justify-end">
				<h2 class="text-xl font-bold text-center max-w-xs sm:max-w-lg md:max-w-2xl">
					<!-- <span class="max-w-xs sm:max-w-lg md:max-w-2xl"> -->
					{@html $lq__event_session_obj?.name ?? ae_snip.html__not_set}
					<!-- </span> -->
				</h2>

				{#if (!$events_loc.pres_mgmt?.hide__session_code && $lq__event_session_obj.code) || $ae_loc.edit_mode}
					<span
						class="badge text-sm preset-tonal-surface flex flex-col gap-0.25 max-w-fit shrink justify-self-end"
						title="Session code {$lq__event_session_obj.code}"
					>
						<span class="text-xs text-surface-800-200">
							<span class="fas fa-barcode m-1"></span>
							code
						</span>
						{$lq__event_session_obj.code}
					</span>
				{/if}
			</span>
		</header>

		<Element_data_store
			ds_code="events__pres_mgmt__session_msg"
			ds_name="Default: Events - Pres Mgmt Session Message"
			ds_type="html"
			for_type="event"
			for_id={$lq__event_session_obj?.event_id}
			class_li="w-full max-w-(--breakpoint-lg) text-lg text-blue-500 font-bold text-center p-1 m-auto border border-blue-200 rounded-md bg-blue-100 space-y-2"
			hide={!$ae_loc.manager_access || $events_loc.pres_mgmt.hide__session_msg}
			show_edit={false}
			show_edit_btn={true}
		/>

		<div class="m-1 flex flex-col flex-wrap gap-1 items-center">
			{#if $ae_loc.trusted_access || ($events_loc.auth__person?.id && $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id])}
				{#if $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id] === true}
					<h3 class="h3">
						Welcome {$lq__event_session_obj?.poc_person_full_name ?? 'Session POC'}
					</h3>
				{:else if $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id] == 'read'}
					<h3 class="h3">Welcome {$lq__auth__event_presenter_obj?.full_name ?? 'Presenter'}</h3>
				{/if}

				{#if $ae_loc.trusted_access || $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id] === true || ($events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id] == 'read' && $lq__auth__event_presenter_obj?.agree)}
					<!-- Message if they have agreed -->
					<Element_data_store
						ds_code="events__pres_mgmt__session_page_authorized_info"
						ds_name="Default: Events - Pres Mgmt Session Authorized Info"
						ds_type="html"
						for_type="event"
						for_id={$lq__event_session_obj?.event_id}
						class_li="w-fit max-w-(--breakpoint-lg) flex flex-col sm:flex-row gap-1"
						show_edit={false}
						show_edit_btn={true}
						mount_reload_sec={1}
					/>
				{:else if $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id] == 'read' && !$lq__event_presenter_obj?.agree}
					<!-- Message if they have not yet agreed -->
					<Element_data_store
						ds_code="events__pres_mgmt__presenter_agree_read_consent"
						ds_name="Default: Events - Pres Mgmt Session Restricted Access"
						ds_type="html"
						for_type="event"
						for_id={$lq__event_session_obj?.event_id}
						class_li="w-fit max-w-(--breakpoint-lg) text-lg text-red-500 font-bold text-center p-1 m-1 border border-red-200 rounded-md bg-red-100 space-y-2"
						show_edit={false}
						show_edit_btn={true}
					/>
				{/if}
			{/if}

			{#if (!$events_loc.auth__person?.id && !$ae_loc.trusted_access) || ($ae_loc.trusted_access && $ae_loc.edit_mode)}
				<Element_data_store
					ds_code="events__pres_mgmt__session_page_restricted_access"
					ds_name="Default: Events - Pres Mgmt Session Restricted Access"
					ds_type="html"
					for_type="event"
					for_id={$lq__event_presenter_obj?.event_id}
					class_li="w-fit max-w-(--breakpoint-lg) text-xl text-red-500 font-bold text-center p-1 m-1 border border-red-200 rounded-md bg-red-100"
					show_edit={false}
					show_edit_btn={true}
				/>
			{/if}
		</div>

		{#if !$events_loc.pres_mgmt.show_content__session_view || $events_loc.pres_mgmt.show_content__session_view == 'default'}
			<Session_view
				{lq__event_presenter_obj}
				{lq__event_session_obj}
				{lq__auth__event_presenter_obj}
				{lq__event_presentation_obj_li}
			/>
		{:else if $events_loc.pres_mgmt.show_content__session_view == 'manage_files' && $ae_loc.public_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 Session Files:
					<span
						class="badge preset-tonal-success"
						class:hidden={!$lq__event_session_obj?.file_count}
					>
						<span class="fas fa-file-alt m-1"></span>
						{$lq__event_session_obj?.file_count}×
					</span>
				</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_session"
					link_to_id={$lq__event_session_obj.event_session_id}
				>
					{#snippet label()}
						<span>
							<div class="text-lg">
								<span class="fas fa-upload"></span>
								<strong class="">Upload session (breakout) specific files only!</strong>
							</div>
							<div class="text-sm text-gray-600 dark:text-gray-400 italic">
								<strong>Session (breakout) 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_session'}
						link_to_id={$lq__event_session_obj?.event_session_id}
						allow_basic={$events_loc.auth__kv.session[$lq__event_session_obj.event_session_id] ||
							$events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id]}
						allow_moderator={$events_loc.auth__kv.session[$lq__event_session_obj.event_session_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>
				Session Disabled
			</h2>
			<p>
				This session is currently disabled. Please contact the event organizer for more information.
			</p>
		</div>
	{/if}
</section>

<!-- Main modal -->
<Modal
	title="{$lq__event_presenter_obj?.full_name} Presenter Consent and Release and Terms and Conditions"
	bind:open={$events_sess.pres_mgmt.show_modal__presenter_agree}
	autoclose={false}
	placement="top-center"
	class="bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded-lg border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md relative flex flex-col mx-auto w-full divide-y"
>
	<Comp_event_presenter_form_agree {lq__event_presenter_obj} />

	{#snippet footer()}
		<div class="text-center w-full">
			<button
				onclick={() => {
					$events_sess.pres_mgmt.show_modal__presenter_agree = false;
				}}
				class="btn btn-sm preset-tonal-warning hover:preset-tonal-warning border border-warning-500"
			>
				<span class="fas fa-times m-1"></span>
				Close
			</button>
		</div>
	{/snippet}
</Modal>
