<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_posts } from '$lib/ae_posts/db_posts';
	// import { posts_func } from '$lib/ae_posts/ae_posts_functions';
	import { idaa_loc, idaa_sess, idaa_slct, idaa_trig, idaa_prom } from '$lib/stores/ae_idaa_stores';

	import Comp__post_obj_id_edit from '.././ae_idaa_comp__post_obj_id_edit.svelte';
	import Comp__post_obj_id_view from '.././ae_idaa_comp__post_obj_id_view.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.bb.edit__post_obj = null;
	$idaa_slct.post_id = ae_acct.slct.post_id;
	$idaa_trig.post_id = ae_acct.slct.post_id;
	// $idaa_slct.post_obj = ae_acct.slct.post_obj;

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

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

			return results;
		})
	);

	let lq__post_comment_obj_li = $derived(
		liveQuery(async () => {
			let results = await db_posts.comment
				.where('post_id')
				.equals($idaa_slct.post_id ?? '') // null or undefined does not reset things like '' does
				.reverse()
				.limit($idaa_loc.bb.qry__limit)
				.sortBy('tmp_sort_1');
			// .sortBy('created_on');
			// .sortBy('updated_on');
			// .sortBy('title');

			if (
				$idaa_slct.post_comment_obj_li &&
				JSON.stringify($idaa_slct.post_comment_obj_li) !== JSON.stringify(results)
			) {
				$idaa_slct.post_comment_obj_li = [...results];
				if (log_lvl) {
					console.log(`$idaa_slct.post_comment_obj_li = `, $idaa_slct.post_comment_obj_li);
				}
			} else {
				if (log_lvl) {
					console.log(
						`Post comment object list has not changed for post_id: ${$idaa_slct.post_id}`
					);
				}
			}

			return results;
		})
	);

	let lq__post_comment_obj = $derived(
		liveQuery(async () => {
			let results = await db_posts.comment.get($idaa_slct.post_comment_id ?? ''); // null or undefined does not reset things like '' does

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

			return results;
		})
	);

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

		let message = { post_id: $idaa_slct?.post_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(() => {
		log_lvl = 1;
		if (log_lvl) {
			console.log(`Destroying bb page for post_id: ${$idaa_slct?.post_id}`);
		}

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

		// $idaa_slct.post_id = null;
		// $idaa_slct.post_obj = null;
	});
</script>

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

<header class="ae_header flex flex-row flex-wrap gap-2 items-center justify-evenly w-full">
	<h2
		class="
            ae_name post__name
            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 text-neutral-800/80"></span>
		{$lq__post_obj?.name ? $lq__post_obj?.name : 'BB Post'}
	</h2>

	<div
		class="
            flex flex-row gap-2 items-center justify-evenly
            min-w-1/4
            max-w-full
        "
	>
		<!-- {#if $lq__post_obj?.topic_id}<span class="badge badge-info preset-tonal-secondary"><span class="fas fa-user-md m-1"></span> {$lq__post_obj?.topic_name}</span>{/if} -->

		<span class="float-right flex flex-row flex-wrap gap-1 items-center justify-end">
			{#if $lq__post_obj?.topic_name}
				<span class="badge badge-info preset-tonal-secondary"
					><span class="fas fa-tag"></span> {$lq__post_obj?.topic_name}</span
				>
			{/if}
			{#if $ae_loc.trusted_access && $lq__post_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__post_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>
</header>

<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/bb"
		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 Posts List
		<!-- <span class="fas fa-times m-1"></span> View Other Meetings -->
	</a>

	<!-- View (default)/Edit post_id toggle -->
	{#if $idaa_sess.bb.edit__post_obj}
		<button
			type="button"
			class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-success-200-800
                transition
                "
			onclick={() => {
				if ($idaa_sess.bb.obj_changed) {
					if (confirm('You have unsaved changes. Are you sure you want to cancel?')) {
						$idaa_sess.bb.edit__post_obj = false;
					}
				} else {
					$idaa_sess.bb.edit__post_obj = false;
				}
				// if (log_lvl) {
				//     console.log(`Toggle edit__post_obj: ${$idaa_sess.bb.edit__post_obj}`);
				// }
			}}
			title="View this BB Post"
		>
			<!-- <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__post_obj?.external_person_id === $idaa_loc.novi_uuid || $lq__post_obj?.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_slct.post_obj = {
					//     ...$lq__post_obj,
					// }
					$idaa_sess.bb.edit__post_obj = $idaa_slct.post_id;
					// if (log_lvl) {
					//     console.log(`Toggle edit__post_obj: ${$idaa_sess.bb.edit__post_obj}`);
					// }
				}}
				title="Edit this BB Post"
			>
				<span class="fas fa-edit m-1"></span>
				Edit Post
			</button>
		{/if}
	{/if}
</div>

{#if $idaa_sess.bb.edit__post_obj || $idaa_loc.bb.edit__post_obj}
	<!-- lq__post_comment_obj_li={lq__post_comment_obj_li} -->
	<!-- lq__post_comment_obj={lq__post_comment_obj} -->
	<Comp__post_obj_id_edit {lq__post_obj} bind:obj_changed={$idaa_sess.bb.obj_changed} />
{:else}
	<Comp__post_obj_id_view {lq__post_obj} {lq__post_comment_obj_li} {lq__post_comment_obj} />
{/if}
