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

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

	let log_lvl: number = 0;

	// *** Import Svelte specific
	import { onDestroy } from 'svelte';
	import { browser } from '$app/environment';

	// *** Import other supporting libraries
	// import { Modal } from 'flowbite-svelte';
	import { liveQuery } from 'dexie';

	// *** Import Aether specific variables and functions
	import { ae_util } from '$lib/ae_utils/ae_utils';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';
	import { db_events } from '$lib/ae_events/db_events';
	// import { events_func } from '$lib/ae_events_functions';
	import { idaa_loc, idaa_sess, idaa_slct, idaa_trig, idaa_prom } from '$lib/stores/ae_idaa_stores';

	import Event_obj_id_edit from '.././ae_idaa_comp__event_obj_id_edit.svelte';
	import Event_obj_id_view from '.././ae_idaa_comp__event_obj_id_view.svelte';
	import Help_tech from '$lib/app_components/e_app_help_tech.svelte';

	// *** Quickly pull out data from parent(s)
	let ae_acct = data[$slct.account_id];
	if (log_lvl) {
		console.log(`ae_acct = `, ae_acct);
	}

	$idaa_sess.recovery_meetings.edit__event_obj = null;
	$idaa_slct.event_id = ae_acct.slct.event_id;
	// $idaa_trig.event_id = ae_acct.slct.event_id;
	// $idaa_slct.event_obj = ae_acct.slct.event_obj;

	// *** Functions and Logic
	let lq__event_obj = $derived(
		liveQuery(async () => {
			if (log_lvl) {
				console.log(`lq__event_obj: event_id = ${$idaa_slct?.event_id}`);
			}
			let results = await db_events.event.get($idaa_slct?.event_id ?? ''); // null or undefined does not reset things like '' does

			// Check if results are different than the current $idaa_slct.event_obj
			if ($idaa_slct.event_obj && results) {
				if (JSON.stringify($idaa_slct.event_obj) !== JSON.stringify(results)) {
					$idaa_slct.event_obj = { ...results };
					if (log_lvl) {
						console.log(`$idaa_slct.event_obj = `, $idaa_slct.event_obj);
					}
				} else {
					if (log_lvl) {
						console.log(`Event object has not changed for event_id: ${$idaa_slct.event_id}`);
					}
				}
			}

			return results;
		})
	);

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

		let message = { event_id: $idaa_slct?.event_id ?? null };
		window.parent.postMessage(message, '*');

		if ($ae_loc?.iframe) {
			console.log('In iframe, sending message to parent window to scroll to top as well');
			window.parent.postMessage({ scroll_to: 0 }, '*'); // This should be in pixels
		}
	}

	onDestroy(() => {
		if (log_lvl) {
			console.log(`Destroying recovery meetings page for event_id: ${$idaa_slct?.event_id}`);
		}

		let message = { event_id: null };
		window.parent.postMessage(message, '*');

		// $idaa_slct.event_id = null;
		// $idaa_slct.event_obj = null;
	});
</script>

<svelte:head>
	<title>
		IDAA Recovery Mtgs:
		{$lq__event_obj?.name
			? ae_util.shorten_string({
					string: $lq__event_obj?.name,
					max_length: 20,
					begin_length: 10,
					end_length: 4
				})
			: ''}
		- Novi - {$ae_loc?.title}
	</title>
</svelte:head>

<div class="ae_header flex flex-row flex-wrap gap-2 items-center justify-evenly w-full">
	<h2
		class="
            ae_title event__title
            h3
            text-2xl font-bold
            flex flex-row gap-2 items-center justify-center
            min-w-1/2
            max-w-full
            "
	>
		<!-- <span class="ae_icon fas fa-calendar-alt"></span> -->
		<span class="ae_icon fas fa-calendar-day"></span>
		{$lq__event_obj?.name ? $lq__event_obj?.name : 'Recovery Meeting'}
	</h2>

	<div
		class="
            flex flex-row gap-2 items-center justify-evenly
            min-w-1/4
            max-w-full
        "
	>
		{#if $lq__event_obj?.status == 'unknown'}
			<span
				class="badge badge-warning preset-tonal-error"
				title="This meeting has not been confirmed by IDAA Central Office. Please reach out to the chair for current meeting list info. Meeting attendees can reach out to info@idaa.org if they know this is information is accurate and this meeting is still taking place."
			>
				<span class="fas fa-exclamation-triangle m-1"></span>
				Not Confirmed by IDAA
				<!-- Unknown Status -->
				<span class="fas fa-exclamation-triangle m-1"></span>
			</span>
		{/if}

		<span class="float-right flex flex-row flex-wrap gap-1 items-center justify-end">
			<span class="badge badge-info preset-tonal-tertiary">
				{#if $lq__event_obj?.physical && $lq__event_obj?.virtual}
					<span class="fas fa-home m-1"></span> F2F and <span class="fas fa-laptop m-1"></span> Virtual
				{:else if $lq__event_obj?.physical}
					<span class="fas fa-home m-1"></span> F2F
				{:else if $lq__event_obj?.virtual}
					<span class="fas fa-laptop m-1"></span> Virtual
				{/if}
			</span>
			{#if $lq__event_obj?.type}
				<span class="badge badge-info preset-tonal-secondary"
					><span class="fas fa-user-md m-1"></span> {$lq__event_obj?.type}</span
				>
			{/if}
			{#if $ae_loc.trusted_access && $lq__event_obj?.hide}
				<span class="badge badge-warning"
					><span class="fas fa-exclamation-triangle m-1"></span> Hidden</span
				>
			{/if}
			{#if $ae_loc.administrator_access && !$lq__event_obj?.enable}
				<span class="badge badge-warning preset-tonal-warning"
					><span class="fas fa-exclamation-triangle m-1"></span> Not enabled</span
				>
			{/if}
		</span>
	</div>

	<Help_tech
		e_class=""
		e_class_h1="novi_m0"
		e_class_h2="novi_m0"
		btn_class="novi_btn"
		show_btn_class="absolute top-0 right-0 float-right z-10"
		additional_kv={{
			novi_uuid: $idaa_loc.novi_uuid,
			novi_email: $idaa_loc.novi_email,
			novi_full_name: $idaa_loc.novi_full_name
		}}
	></Help_tech>
</div>

<div
	class="
        flex flex-row gap-2 items-center justify-evenly
        w-full
        p-1 pb-2 mb-2
        border-b border-b-surface-300-700
        "
>
	<a
		href="/idaa/recovery_meetings"
		class="
            novi_btn btn btn-secondary btn-sm
            preset-tonal-tertiary border border-tertiary-500
            hover:preset-filled-tertiary-500
            transition
            "
	>
		<span class="fas fa-arrow-left m-1 text-neutral-800/80"></span> Back to Meeting List
		<!-- <span class="fas fa-times m-1"></span> View Other Meetings -->
	</a>

	<!-- View (default)/Edit event_id toggle -->
	{#if $idaa_sess.recovery_meetings.edit__event_obj}
		<button
			type="button"
			class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-success-200-800
                transition
                "
			onclick={() => {
				$idaa_sess.recovery_meetings.edit__event_obj = false;
				if (log_lvl) {
					console.log(`Toggle edit__event_obj: ${$idaa_sess.recovery_meetings.edit__event_obj}`);
				}
			}}
			title="View this Recovery Meeting"
		>
			<!-- <span class="far fa-window-close m-1"></span> -->
			<span class="fas fa-times m-1 text-neutral-800/80"></span>
			Cancel Edit
		</button>
	{:else}
		<!-- This checks if the currently logged in Novi user has a matching UUID or email address. -->
		{#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || $lq__event_obj?.external_person_id === $idaa_loc.novi_uuid || $lq__event_obj?.contact_li_json[0].email === $idaa_loc.novi_email}
			<button
				type="button"
				class="
                    novi_btn
                    btn btn-sm preset-tonal-warning
                    hover:preset-filled-warning-500 transition
                    "
				onclick={() => {
					$idaa_sess.recovery_meetings.edit__event_obj = $idaa_slct.event_id;
					if (log_lvl) {
						console.log(`Toggle edit__event_obj: ${$idaa_sess.recovery_meetings.edit__event_obj}`);
					}
				}}
				title="Edit this Recovery Meeting"
			>
				<span class="fas fa-edit m-1 text-neutral-800/80"></span>
				Edit Meeting
			</button>
		{/if}
	{/if}
</div>

{#if $idaa_sess.recovery_meetings.edit__event_obj || $idaa_loc.recovery_meetings.edit__event_obj}
	<Event_obj_id_edit {lq__event_obj} bind:obj_changed={$idaa_sess.recovery_meetings.obj_changed} />
{:else}
	<Event_obj_id_view {lq__event_obj} />
{/if}
