<script lang="ts">
	/** @type {import('./$types').PageData} */
	let log_lvl: number = $state(1);

	// *** Import Svelte specific
	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 type { key_val } from '$lib/ae_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	// import { core_func } from '$lib/ae_core/ae_core_functions';
	import { db_journals } from '$lib/ae_journals/db_journals';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';
	import {
		journals_loc,
		journals_sess,
		journals_slct,
		journals_prom,
		journals_trig
	} from '$lib/ae_journals/ae_journals_stores';
	// import { journals_func } from '$lib/ae_journals/ae_journals_functions';

	// import Journal_entry_obj_id_edit from './ae_journals_comp__journal_entry_obj_id_edit.svelte';
	import Journal_entry_view from './../../../ae_comp__journal_entry_obj_id_view.svelte';
	// import Journal_page_menu from './session_page_menu.svelte';
	// import Element_data_store from '$lib/element_data_store_v2.svelte';

	interface Props {
		data: any;
	}

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

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

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

	$journals_slct.journal_id = ae_acct.slct.journal_id;
	let lq__journal_obj = $derived(
		liveQuery(async () => {
			let results = await db_journals.journal.get($journals_slct?.journal_id ?? ''); // null or undefined does not reset things like '' does

			// Check if results are different than the current session version stored under $journals_slct
			if ($journals_slct.journal_obj && results) {
				if (JSON.stringify($journals_slct.journal_obj) !== JSON.stringify(results)) {
					$journals_slct.journal_obj = { ...results };
				}
			}

			return results;
		})
	);

	$effect(() => {
		if (log_lvl) {
			console.log(`lq__journal_obj: journal_id = ${$journals_slct?.journal_id}`);
			console.log(`lq__journal_obj: results = `, lq__journal_obj);
			if ($journals_slct.journal_obj && lq__journal_obj) {
				if (JSON.stringify($journals_slct.journal_obj) !== JSON.stringify(lq__journal_obj)) {
					console.log(
						`Session slct stored version has changed for ID = ${$journals_slct.journal_id}`,
						$journals_slct.journal_obj
					);
				} else {
					console.log(
						`Session slct stored version has not changed for ID = ${$journals_slct.journal_id}`
					);
				}
			}
		}
	});

	let lq__journal_obj_li = $derived(
		liveQuery(async () => {
			let results = await db_journals.journal
				.where('person_id')
				.equals($ae_loc.person_id)
				.reverse()
				.sortBy('tmp_sort_2');

			// Check if results are different than the current session version stored under $journals_slct
			if (
				$journals_slct.journal_obj_li &&
				JSON.stringify($journals_slct.journal_obj_li) !== JSON.stringify(results)
			) {
				$journals_slct.journal_obj_li = [...results];
			}

			return results;
		})
	);

	$effect(() => {
		if (log_lvl) {
			console.log(`lq__journal_obj_li: person_id = ${$ae_loc.person_id}`);
			console.log(`lq__journal_obj_li: results = `, lq__journal_obj_li);
			if (
				$journals_slct.journal_obj_li &&
				JSON.stringify($journals_slct.journal_obj_li) !== JSON.stringify(lq__journal_obj_li)
			) {
				console.log(
					`Session slct li stored version has changed for ID = ${$ae_loc.person_id}`,
					$journals_slct.journal_obj_li
				);
			} else {
				if (log_lvl > 1) {
					console.log(
						`Session slct li stored version has not changed for ID = ${$ae_loc.person_id}`
					);
				}
			}
		}
	});

	// For some reason data.params.journal_entry_id (or whatever param) is not being passed to this page when loaded by a link from another page. This seems to be a bug with Svelte or SvelteKit. Hopefully fixed in a future version 5? 2024-11-06
	$journals_slct.journal_entry_id = ae_acct.slct.journal_entry_id;
	// $journals_slct.journal_entry_obj = ae_acct.slct.journal_entry_obj;

	let lq__journal_entry_obj = $derived(
		liveQuery(async () => {
			let results = await db_journals.journal_entry.get($journals_slct.journal_entry_id ?? ''); // null or undefined does not reset things like '' does

			// Check if results are different than the current session version stored under $journals_slct
			if ($journals_slct.journal_entry_obj && results) {
				if (JSON.stringify($journals_slct.journal_entry_obj) !== JSON.stringify(results)) {
					$journals_slct.journal_entry_obj = { ...results };
				}
			}

			return results;
		})
	);

	$effect(() => {
		if (log_lvl) {
			console.log(`lq__journal_entry_obj: journal_entry_id = ${$journals_slct?.journal_entry_id}`);
			console.log(`lq__journal_entry_obj: results = `, lq__journal_entry_obj);
			if ($journals_slct.journal_entry_obj && lq__journal_entry_obj) {
				if (
					JSON.stringify($journals_slct.journal_entry_obj) !== JSON.stringify(lq__journal_entry_obj)
				) {
					console.log(
						`Session slct stored version has changed for ID = ${$journals_slct.journal_entry_id}`,
						$journals_slct.journal_entry_obj
					);
				} else {
					console.log(
						`Session slct stored version has not changed for ID = ${$journals_slct.journal_entry_id}`
					);
				}
			}
		}
	});

	// $effect(() => {
	//     if (browser && $lq__journal_entry_obj?.journal_entry_id) {

	//         // $journals_loc.entry_view_history_li = [...new Set($journals_loc.entry_view_history_li)]

	//         let tmp_history_li = [
	//             ...new Set($journals_loc?.entry_view_history_li ?? [])
	//             ];

	//         // Limit to last 15 entries
	//         if (tmp_history_li.length > 15) {
	//             tmp_history_li = tmp_history_li.slice(tmp_history_li.length - 15);
	//         }

	//         // let chk_history_li = tmp_history_li?.filter(item => item.id === $lq__journal_entry_obj?.journal_entry_id);

	//         // if (chk_history_li?.length) {
	//         //     // Already in history, do not add again
	//         //     console.log(`Entry ID = ${$lq__journal_entry_obj?.journal_entry_id} already in history, not adding again.`, tmp_history_li);

	//         //     // if (tmp_history_li !== $journals_loc.entry_view_history_li) {
	//         //     if (JSON.stringify(tmp_history_li) !== JSON.stringify($journals_loc.entry_view_history_li)) {
	//         //         $journals_loc.entry_view_history_li = tmp_history_li;

	//         //         console.log(`$journals_loc.entry_view_history_li = `, $journals_loc.entry_view_history_li);
	//         //     }

	//         //     return;
	//         // }

	//         tmp_history_li.push({
	//             id: $lq__journal_entry_obj?.journal_entry_id ?? 'NONE',
	//             name: $lq__journal_entry_obj?.name ?? ae_util.iso_datetime_formatter($lq__journal_entry_obj?.created_on, 'datetime_iso_12_no_seconds'),
	//             url: `/journals/${$lq__journal_entry_obj?.journal_id ?? 'NONE'}/entry/${$lq__journal_entry_obj?.journal_entry_id ?? 'NONE'}`,
	//         });

	//         // Remove duplicates and keep most recent
	//         tmp_history_li = [...new Set(tmp_history_li.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));

	//         // Limit to last 15 entries
	//         if (tmp_history_li.length > 15) {
	//             tmp_history_li = tmp_history_li.slice(tmp_history_li.length - 15);
	//         }

	//         if (JSON.stringify(tmp_history_li) !== JSON.stringify($journals_loc?.entry_view_history_li)) {
	//             $journals_loc.entry_view_history_li = tmp_history_li;

	//             console.log(`$journals_loc.entry_view_history_li = `, $journals_loc?.entry_view_history_li);
	//         }

	//         console.log(`$journals_loc.entry_view_history_li = `, $journals_loc?.entry_view_history_li);
	//     }
	// });

	$effect(() => {
		if (browser && $lq__journal_entry_obj?.journal_entry_id) {
			// log_lvl = 2;
			// Start with the current KV or convert the LI to a KV if needed
			let history_kv = { ...($journals_loc?.entry_view_history_kv ?? {}) };

			// Add or update the current entry
			const entry_id = $lq__journal_entry_obj?.journal_entry_id ?? 'NONE';
			history_kv[entry_id] = {
				id: entry_id,
				name:
					$lq__journal_entry_obj?.name ??
					ae_util.iso_datetime_formatter(
						$lq__journal_entry_obj?.created_on,
						'datetime_iso_12_no_seconds'
					),
				url: `/journals/${$lq__journal_entry_obj?.journal_id ?? 'NONE'}/entry/${entry_id}`
			};

			console.log(`history_kv (before limiting) = `, history_kv);

			// // Convert KV to array, sort by most recent (last updated), and limit to 15
			// let history_li = Object.values(history_kv);

			// console.log(`history_li (before limiting) = `, history_li);

			// // If you want to keep the most recent 15, you can use the order of insertion.
			// // To do this, remove the oldest if over 15.
			// if (history_li.length > 15) {
			//     // Remove the oldest entries (by insertion order)
			//     // Get the keys in insertion order
			//     const keys = Object.keys(history_kv);
			//     const keys_to_remove = keys.slice(0, history_li.length - 15);
			//     for (const key of keys_to_remove) {
			//         delete history_kv[key];
			//     }
			// }

			// Only update if changed
			if (JSON.stringify(history_kv) !== JSON.stringify($journals_loc?.entry_view_history_kv)) {
				$journals_loc.entry_view_history_kv = history_kv;
				console.log(`$journals_loc.entry_view_history_kv = `, $journals_loc.entry_view_history_kv);
			} else {
				if (log_lvl > 1) {
					console.log(`$journals_loc.entry_view_history_kv has not changed.`);
				}
			}

			// log_lvl = 1;
		}
	});
</script>

<!-- <svelte:head>
	<title>
        &AElig; Journals:
        {$lq__journal_entry_obj?.name ? ae_util.shorten_string({ string: $lq__journal_entry_obj?.name, max_length: 20, begin_length: 10, end_length: 4 }) : ''}
        - {$ae_loc?.title}
    </title>
</svelte:head> -->

{#if $ae_loc.person_id == $lq__journal_obj?.person_id || $lq__journal_entry_obj?.public}
	<section
		class="
        ae_journals__journal_entry
        mx-auto
        flex flex-col grow gap-1
        items-center
        min-h-full
        max-h-max
        min-w-full
        max-w-max
        space-y-2
        "
	>
		<!-- {#if $lq__journal_entry_obj} -->
		<Journal_entry_view {lq__journal_obj} {lq__journal_obj_li} {lq__journal_entry_obj} />
		<!-- {/if} -->
	</section>
{:else}
	<section class="main_content grow px-1 md:px-2 pb-28 flex flex-col gap-1 items-center">
		<p class="text-center">You must be logged in as the owner to view this Journal Entry.</p>
	</section>
{/if}
