<script lang="ts">
	/** @type {import('./$types').LayoutData} */
	// /** @type {import('./$types').LayoutProps} */

	let log_lvl: number = 1;

	// *** Import Svelte specific
	// import { tick } from 'svelte';
	import { goto, invalidateAll } from '$app/navigation';

	import '../app.css';

	// *** Import other supporting libraries
	import {
		ArrowBigRight,
		CircleX,
		// Eye, EyeOff,
		// Key,
		// LogIn, LogOut, LockKeyhole,
		// Mail, MailCheck,
		// Menu,
		RefreshCw,
		RefreshCcw,
		RefreshCcwDot
		// ShieldEllipsis, ShieldMinus, ShieldPlus, ShieldUser,
		// User, UserCheck
	} from '@lucide/svelte';

	// Highlight JS
	import hljs from 'highlight.js/lib/core';
	import 'highlight.js/styles/github-dark.css';

	import { browser } from '$app/environment';
	// import { storeHighlightJs } from '@skeletonlabs/skeleton';
	import xml from 'highlight.js/lib/languages/xml'; // for HTML
	import css from 'highlight.js/lib/languages/css';
	import javascript from 'highlight.js/lib/languages/javascript';
	import typescript from 'highlight.js/lib/languages/typescript';

	hljs.registerLanguage('xml', xml); // for HTML
	hljs.registerLanguage('css', css);
	hljs.registerLanguage('javascript', javascript);
	hljs.registerLanguage('typescript', typescript);
	// storeHighlightJs.set(hljs);

	// *** Import Aether specific variables and functions
	import Analytics from '$lib/app_components/analytics.svelte';
	// import { api } from '$lib/api';
	import { ae_loc, ae_sess, ae_api, slct, slct_trigger } from '$lib/stores/ae_stores';
	import { events_loc, events_slct } from '$lib/stores/ae_events_stores';
	// import type { key_val } from '$lib/ae_stores';

	import MyClipboard from '$lib/app_components/e_app_clipboard.svelte';
	import E_app_debug_menu from '$lib/app_components/e_app_debug_menu.svelte';
	import E_app_sys_menu from '$lib/app_components/e_app_sys_menu.svelte';
	// import Element_access_type from '$lib/element_access_type.svelte';
	// import Element_app_cfg from '$lib/element_app_cfg.svelte';
	// import Element_sign_in_out from '$lib/element_sign_in_out.svelte';

	// import Element_data_store from '$lib/element_data_store_v2.svelte';

	interface Props {
		data: any;
		children?: import('svelte').Snippet;
	}

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

	if (log_lvl > 1) {
		console.log(`ae_root +layout.svelte data:`, data);
	}

	// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other. This should catch anything that is a child of this layout.svelte file.
	$slct.account_id = data.account_id;
	if (log_lvl) {
		console.log(`*ae_root +layout.svelte* $slct.account_id = ${$slct.account_id}`);
	}
	let ae_acct = data[$slct.account_id];

	$ae_api = {
		...$ae_api,
		...ae_acct.api
	};
	if (log_lvl > 1) {
		console.log(`$ae_api = `, $ae_api);
	}

	$ae_loc = {
		...$ae_loc,
		...ae_acct.loc
	};
	if (log_lvl > 1) {
		console.log(`$ae_loc = `, $ae_loc);
	}

	$slct = {
		...$slct,
		...ae_acct.slct
	};
	if (log_lvl > 1) {
		console.log(`$slct = `, $slct);
	}

	let flag_clear_idb: boolean = $state(false);
	let flag_clear_local: boolean = $state(false);
	let flag_clear_sess: boolean = $state(false);
	let flag_reload: boolean = $state(false); // Reload page required

	let flag_new_ver: boolean = $state(false); // New version of the app
	let flag_expired: boolean = $state(false); // Expired Cache
	let flag_denied: boolean = $state(false); // Access Denied
	// let flag_reason: string = $state(''); // Reason: New version, Expired Cache, Access Denied

	// BEGIN: Sanity Checks:
	// Added 2025-07-15
	if (!$ae_loc?.sys_menu) {
		$ae_loc.sys_menu = {
			hide: false,
			// expand: false,
			hide_access_type: false,
			expand_access_type: false,
			hide_edit_mode: false,
			expand_edit_mode: false,
			hide_user: false,
			expand_user: false,
			hide_theme: false,
			expand_theme: false,
			hide_cfg: false,
			expand_cfg: false
		};
	}
	// Added 2025-07-15
	if (!$ae_loc?.debug_menu) {
		$ae_loc.debug_menu = {
			hide: false,
			expand: false
		};
	}

	if (!$ae_loc?.app_cfg) {
		flag_reload = true;
		flag_expired = true;

		$ae_loc.cache_expired = true;

		// $ae_loc.app_cfg = {};
		// $ae_loc.app_cfg.show_element__menu_btn = true;
		// $ae_loc.app_cfg.show_element__menu = false;
	}

	if (!$ae_loc?.ver) {
		flag_reload = true;
		flag_expired = true;

		$ae_loc.cache_expired = true;

		// $ae_loc.ver = false;
	}
	if (!$ae_loc?.site_cfg_json) {
		flag_reload = true;
		flag_expired = true;
		$ae_loc.cache_expired = true;

		// $ae_loc.site_cfg_json = {};
	}
	// END: Sanity Checks:

	// BEGIN: New Version Check:
	if ($ae_loc && $ae_sess && $ae_loc?.ver != $ae_sess?.ver) {
		if (log_lvl) {
			console.log('ROOT: New version of the ae_loc (core local storage) available!!!');
			console.log(`$ae_loc.ver: ${$ae_loc.ver} != $ae_sess.ver: ${$ae_sess.ver}`);
		}

		flag_clear_idb = true;
		flag_clear_local = true;
		flag_clear_sess = true;
		flag_reload = true;
		flag_new_ver = true;
		flag_expired = true; // If new version then expire the cache

		$ae_loc.cache_expired = true;

		// localStorage.clear();
		// sessionStorage.clear();

		$ae_loc.allow_access = false;
	}

	// BEGIN: Expired Cache Check:
	// localStorage caches - Check if the last refresh timestamp for $ae_loc.last_refresh is no more than 48 hours ago.

	// Minutes reference:
	// 240 = 4 hours; 720 = 12 hours; 2880 = 48 hours; 7200 = 5 days;
	// 10080 = 1 week; 20160 = 2 weeks; 43200 = 1 month;
	let default_refresh_minutes: number = 20160; // 7200; // default was 4 hours
	let authenticated_refresh_minutes: number = 20160; // 10080; // default was 12 hours
	let trusted_refresh_minutes: number = 20160; // default was 1 week
	let manager_refresh_minutes: number = 20160; // default was 2 weeks
	if ($ae_loc?.site_cfg_json?.default_refresh_minutes) {
		default_refresh_minutes = $ae_loc.site_cfg_json.default_refresh_minutes;
	}
	if ($ae_loc?.site_cfg_json?.authenticated_refresh_minutes) {
		authenticated_refresh_minutes = $ae_loc.site_cfg_json.authenticated_refresh_minutes;
	}
	if ($ae_loc?.site_cfg_json?.trusted_refresh_minutes) {
		trusted_refresh_minutes = $ae_loc.site_cfg_json.trusted_refresh_minutes;
	}
	if ($ae_loc?.site_cfg_json?.manager_refresh_minutes) {
		manager_refresh_minutes = $ae_loc.site_cfg_json.manager_refresh_minutes;
	}

	let default_refresh_time = default_refresh_minutes * 60 * 1000;
	let authenticated_refresh_time = authenticated_refresh_minutes * 60 * 1000;
	let trusted_refresh_time = trusted_refresh_minutes * 60 * 1000;
	let manager_refresh_time = manager_refresh_minutes * 60 * 1000;

	// IDB caches - Check if the last refresh timestamp for $ae_loc.last_cache_refresh is no more than 15 minutes ago.
	let default_idb_refresh_time = 4 * 60 * 60 * 1000; // 15 minutes?
	let trusted_idb_refresh_time = 8 * 60 * 60 * 1000; // 4 hours or 120 minutes? 8 hours or 480 minutes?

	if (!$ae_loc?.last_cache_refresh) {
		// Default is null, currently...
		console.log(`ROOT: Last reload not found. Need to set!`);
		// $ae_loc.last_cache_refresh = Date.now();

		flag_clear_idb = true;
		flag_clear_local = true;
		flag_clear_sess = true;
		flag_reload = true;
		flag_expired = true;

		$ae_loc.cache_expired = true;
		$ae_loc.allow_access = false;
	} else {
		if (log_lvl) {
			console.log(
				`Trusted: ${$ae_loc?.trusted_access}`,
				Date.now() - $ae_loc?.last_cache_refresh,
				trusted_refresh_time
			);

			console.log(
				`ROOT: Checking expired cache based on last_cache_refresh UNIX timestamp: ${new Date($ae_loc.last_cache_refresh).toISOString()} (${Math.floor((Date.now() - $ae_loc.last_cache_refresh) / 60000)} minutes ago)`
			);

			console.log(`ROOT: Last diff: ${Date.now() - $ae_loc?.last_cache_refresh}`);
		}

		if ($ae_loc?.manager_access) {
			if (Date.now() - $ae_loc?.last_cache_refresh > manager_refresh_time) {
				console.log(
					`ROOT: Last (manager) local config reload too old for all caches: ${$ae_loc.last_cache_refresh}`
				);

				flag_clear_idb = true;
				flag_clear_local = true;
				flag_clear_sess = true;
				flag_reload = true;
				flag_expired = true;

				$ae_loc.cache_expired = true;
				$ae_loc.allow_access = false;
			}
		} else if ($ae_loc?.trusted_access) {
			if (Date.now() - $ae_loc?.last_cache_refresh > trusted_refresh_time) {
				console.log(
					`ROOT: Last (trusted) local config reload too old for all caches: ${$ae_loc.last_cache_refresh}`
				);

				flag_clear_idb = true;
				flag_clear_local = true;
				flag_clear_sess = true;
				flag_reload = true;
				flag_expired = true;

				$ae_loc.cache_expired = true;
				$ae_loc.allow_access = false;
			}
		} else if ($ae_loc?.authenticated_access) {
			if (Date.now() - $ae_loc?.last_cache_refresh > authenticated_refresh_time) {
				console.log(
					`ROOT: Last (authenticated) local config reload too old for all caches: ${$ae_loc.last_cache_refresh}`
				);

				flag_clear_idb = true;
				flag_clear_local = true;
				flag_clear_sess = true;
				flag_reload = true;
				flag_expired = true;

				$ae_loc.cache_expired = true;
				$ae_loc.allow_access = false;
			}
		} else if (Date.now() - $ae_loc?.last_cache_refresh > default_refresh_time) {
			console.log(
				`ROOT: Last (default) local config reload too old for all caches: ${$ae_loc.last_cache_refresh}`
			);

			flag_clear_idb = true;
			flag_clear_local = true;
			flag_clear_sess = true;
			flag_reload = true;
			flag_expired = true;

			$ae_loc.cache_expired = true;
			$ae_loc.allow_access = false;
		} else {
			if (log_lvl > 1) {
				console.log(`ROOT: Last local config reload is recent: ${$ae_loc.last_cache_refresh}`);
			}
		}

		// Only clear IDB, not the local or session storage.
		if (
			$ae_loc?.trusted_access &&
			Date.now() - $ae_loc?.last_cache_refresh > trusted_idb_refresh_time
		) {
			console.log(`ROOT: Last (trusted) IDB reload too old for IDB: ${$ae_loc.last_cache_refresh}`);

			flag_clear_idb = true;
			// flag_clear_local = false;
			// flag_clear_sess = false;
			// flag_reload = true;
			// flag_expired = true;

			// $ae_loc.cache_expired = true;
			// $ae_loc.allow_access = false;
		} else if (
			!$ae_loc?.trusted_access &&
			Date.now() - $ae_loc.last_cache_refresh > default_idb_refresh_time
		) {
			console.log(`ROOT: Last (default) IDB reload too old for IDB: ${$ae_loc.last_cache_refresh}`);

			flag_clear_idb = true;
			// flag_clear_local = false;
			// flag_clear_sess = false;
			// flag_reload = true;
			// flag_expired = true;

			// $ae_loc.cache_expired = true;
			// $ae_loc.allow_access = false;
		} else {
			if (log_lvl > 1) {
				console.log(`ROOT: Last IDB reload is recent: ${$ae_loc.last_cache_refresh}`);
			}

			flag_expired = false;
			$ae_loc.cache_expired = false;
		}
	}
	// END: Expired Cache Check:

	// $effect(() => {
	if (browser && flag_clear_idb) {
		if (log_lvl) {
			console.log(`ROOT: Clear IDB...`);
		}
		flag_clear_idb = false;
		$ae_loc.last_cache_refresh = Date.now();

		clear_idb();

		if (log_lvl) {
			console.log(`ROOT: IDB cleared. Reload!`);
		}
		window.location.reload();
	}

	// BEGIN: Access Checks:
	// Updated 2024-11-21
	if ($ae_loc?.site_access_key || $ae_loc?.site_domain_access_key) {
		// log_lvl = 2;
		if (log_lvl > 1) {
			console.log(
				`We need to do a current check against the allow_access value. site key: ${$ae_loc.site_access_key}, domain key: ${$ae_loc.site_domain_access_key}`
			);
		}

		// $ae_loc.allow_access is set to they key if passed in the URL. It is set to true if they are just "trusted".
		if (
			$ae_loc.site_access_key === $ae_loc.allow_access ||
			$ae_loc.site_domain_access_key === $ae_loc.allow_access
		) {
			if (log_lvl > 1) {
				console.log(
					`PASS: The allow_access was checked earlier and just now checked against the site or domain key.`
				);
			}
		} else {
			// console.log(`FAIL: The access key was checked earlier, but just now failed. Checking if they are trusted...`);
			if ($ae_loc.trusted_access) {
				if (log_lvl > 1) {
					console.log(`PASS: The access key was checked and failed, but we have trusted access.`);
				}
				$ae_loc.allow_access = true;
			} else {
				if (log_lvl) {
					console.log(
						`FAIL: The site and domain access key was checked and failed, and we do not have trusted access.`
					);
				}
				$ae_loc.allow_access = false;
				flag_denied = true;
			}
		}
	} else {
		// This means this site and domain do not require an access key.
		$ae_loc.allow_access = true;
	}

	if ($ae_loc?.site_cfg_json?.theme_name) {
		$ae_loc.theme_name = $ae_loc.site_cfg_json.theme_name;
	}
	if ($ae_loc?.site_cfg_json?.theme_mode) {
		$ae_loc.theme_mode = $ae_loc.site_cfg_json.theme_mode;

		// $ae_loc.theme_mode = 'dark';
	}

	if (browser && window.matchMedia('(prefers-color-scheme: dark)').matches) {
		$ae_loc.theme_mode = 'dark';
	} else {
		$ae_loc.theme_mode = 'light';
	}

	// BEGIN: Special Checks for Events, Sponsorships, IDAA, CHOW, LCI, etc.:
	// // END: Special Checks

	// Root Svelte Layout Specific:
	// let trigger_clear_access: null|boolean = $state(null);

	if (browser) {
		document.documentElement.setAttribute('data-theme', $ae_loc?.theme_name ?? 'nouveau');
		// cerberus
	}

	// $effect(() => {
	if (browser && flag_reload) {
		if (log_lvl) {
			console.log(`ROOT: Reloading page after other flags checked...`);
		}

		// // Clear Indexed DB as well
		// if (flag_clear_idb) {
		//     if (log_lvl) {
		//         console.log(`ROOT: Clearing IndexedDB databases...`);
		//     }

		//     clear_idb();
		// }

		// Clear localStorage and sessionStorage
		if (flag_clear_local) {
			if (log_lvl) {
				console.log(`ROOT: Clearing localStorage...`);
			}

			clear_local();
		}
		if (flag_clear_sess) {
			if (log_lvl) {
				console.log('ROOT: Clearing sessionStorage...');
			}

			clear_sess();
		}
		// tick();

		// try {
		//     goto(data.route.id, {replaceState: true, invalidateAll: true});
		// } catch (e) {
		//     console.log('Error going to root page:', e);
		//     goto('/', {replaceState: true, invalidateAll: true});
		// }

		// This does not seem to work fast enough or something?
		// goto('/', {replaceState: true, invalidateAll: true});

		// The page does usually seem to reload correctly?
		// window.location.reload(true); // true only works with Firefox
		// window.location.reload({forceGet: true});

		// location.reload();
		// tick();

		invalidateAll();

		// alert('Local and Session Storage cleared and Indexed DBs deleted. You will probably want to refresh the page.');
	}

	function clear_idb() {
		indexedDB.deleteDatabase('ae_archives_db'); // Archives module
		indexedDB.deleteDatabase('ae_core_db');
		indexedDB.deleteDatabase('ae_events_db'); // Events module
		indexedDB.deleteDatabase('ae_journals_db'); // Journals module
		indexedDB.deleteDatabase('ae_posts_db'); // Posts module
		indexedDB.deleteDatabase('ae_sponsorships_db'); // Sponsorships module
	}

	function clear_local() {
		// localStorage.removeItem('ae_loc');
		// localStorage.removeItem('ae_idaa_loc');
		// localStorage.removeItem('ae_journals_loc');
		// localStorage.removeItem('ae_events_loc');

		$ae_loc.allow_access = false;
		$ae_loc.authenticated_access = false;
		$ae_loc.edit_mode = false;

		localStorage.clear();
	}

	function clear_sess() {
		// sessionStorage.removeItem('ae_sess');
		// sessionStorage.removeItem('ae_idaa_sess');
		// sessionStorage.removeItem('ae_journals_sess');
		// sessionStorage.removeItem('ae_events_sess');

		sessionStorage.clear();
	}

	if (browser) {
		// save_ds_to_local(ae_acct.ds);
		let ae_ds = ae_acct.ds;
		if (log_lvl) {
			console.log(`ae_ds__ data:`, ae_ds);
		}
		for (let [key, value] of Object.entries(ae_ds)) {
			console.log(`ae_ds__ key: ${key}, value:`, value);
			localStorage.setItem(`ae_ds__${key}`, JSON.stringify(value));
		}

		// This is how the download and upload progress is tracked.
		window.addEventListener('message', function (event) {
			if (log_lvl) {
				console.log('Message received in root +layout.svelte:', event);
			}

			if (event.data.type == 'api_download_blob') {
				if (log_lvl) {
					console.log('Download blob (file) message received:', event.data);
				}

				let task_id = event.data.task_id;

				$ae_sess.api_download_kv[task_id] = {
					status: event.data.status,
					task_id: task_id,
					endpoint: event.data.endpoint,
					filename: event.data.filename,
					size_total: event.data.size_total,
					size_loaded: event.data.size_loaded,
					percent_completed: event.data.percent_completed
				};
			} else if (event.data.type == 'api_post_json_form') {
				if (log_lvl) {
					console.log('Post JSON form message received:', event.data);
				}

				let task_id = event.data.task_id;

				$ae_sess.api_upload_kv[task_id] = {
					status: event.data.status,
					task_id: task_id,
					endpoint: event.data.endpoint,
					filename: event.data.filename,
					size_total: event.data.size_total,
					size_loaded: event.data.size_loaded,
					percent_completed: event.data.percent_completed,
					progress: event.data.progress,
					rate: event.data.rate
				};
			}
		});

		let iframe = data.url.searchParams.get('iframe');
		if (iframe == 'true') {
			console.log('Use iframe layout!');
			$ae_loc.iframe = true;

			document.getElementsByTagName('html')[0].classList.add('iframe');
			// document.getElementsByTagName('html')[0].classList.remove('dark');
			// document.getElementsByTagName('html')[0].classList.remove('light');

			$ae_loc.app_cfg.show_element__access_type = false;
			$ae_loc.app_cfg.show_element__cfg = false;
		} else if (iframe == 'false') {
			$ae_loc.iframe = false;

			document.getElementsByTagName('html')[0].classList.remove('iframe');
			// document.getElementsByTagName('html')[0].classList.add('dark');
			// document.getElementsByTagName('html')[0].classList.add('light');
		}

		if (!$ae_loc.iframe && $ae_loc.trusted_access) {
			$ae_loc.app_cfg.show_element__access_type = true;
			$ae_loc.app_cfg.show_element__cfg = true;
		} else if ($ae_loc.iframe && $ae_loc.manager_access) {
			$ae_loc.app_cfg.show_element__access_type = true;
			$ae_loc.app_cfg.show_element__cfg = true;
		} else {
			$ae_loc.app_cfg.show_element__access_type = true;
			$ae_loc.app_cfg.show_element__cfg = false;
		}

		// This is mainly for Precon CHOW
		if (data.url.searchParams.get('event_id')) {
			$events_slct.event_id = data.url.searchParams.get('event_id');
			$events_loc.event_id = data.url.searchParams.get('event_id');
		}

		if (data.url.searchParams.get('sponsorship_cfg_id')) {
			$slct.sponsorship_cfg_id = data.url.searchParams.get('sponsorship_cfg_id');
			$ae_loc.mod.sponsorships.cfg_id = data.url.searchParams.get('sponsorship_cfg_id');
		}
	}

	// We want to loop through all of the data store (ds) key value pairs and set them to localStorage
	// $: if (ae_acct.ds) {
	//     console.log(`ae_ds__ data:`, ae_acct.ds)
	//     for (let [key, value] of Object.entries(ae_acct.ds)) {
	//         console.log(`ae_ds__ key: ${key}, value:`, value);
	//         localStorageStore(`ae_ds__${key}`, value);
	//     }
	// }

	// Check if in the array of: super > manager > administrator > trusted > public > authenticated > anonymous
	const access_type_li = [
		'super',
		'manager',
		'administrator',
		'trusted',
		'public',
		'authenticated',
		'anonymous'
	];
	$effect(() => {
		if (browser && $ae_loc.access_type && access_type_li.includes($ae_loc.access_type)) {
			document
				.getElementsByTagName('html')[0]
				.classList.remove(
					'super_access',
					'manager_access',
					'administrator_access',
					'trusted_access',
					'public_access',
					'authenticated_access',
					'anonymous_access'
				);
			document.getElementsByTagName('html')[0].classList.add(`${$ae_loc.access_type}_access`);
		} else if (browser) {
			document
				.getElementsByTagName('html')[0]
				.classList.remove(
					'super_access',
					'manager_access',
					'administrator_access',
					'trusted_access',
					'public_access',
					'authenticated_access',
					'anonymous_access'
				);
		}
	});

	$effect(() => {
		if (browser) {
			const interval = setInterval(() => {
				if (log_lvl) {
					// Show the UNIX timestamp in current ISO time format
					console.log(
						`ROOT LOOP: Checking expired cache based on last_cache_refresh UNIX timestamp: ${new Date($ae_loc.last_cache_refresh).toISOString()} (${Math.floor((Date.now() - $ae_loc.last_cache_refresh) / 60000)} minutes ago)`
					);

					console.log(
						`ROOT: Last diff: ${Date.now() - $ae_loc?.last_cache_refresh} | trusted: ${$ae_loc?.trusted_access} | trusted_refresh_time: ${trusted_refresh_time} | default_refresh_time: ${default_refresh_time}`
					);
				}

				// invalidateAll();
				if (
					$ae_loc?.trusted_access &&
					Date.now() - $ae_loc?.last_cache_refresh > trusted_refresh_time
				) {
					if (log_lvl) {
						console.log(
							`ROOT LOOP: Last (trusted) local config reload too old for all caches: ${$ae_loc.last_cache_refresh}`
						);
					}

					// flag_clear_idb = true;
					// flag_clear_local = true;
					// flag_clear_sess = true;
					// flag_reload = true;
					// flag_expired = true;

					$ae_loc.allow_access = false;
					$ae_loc.cache_expired = true;

					// location.reload();

					clearInterval(interval);
				} else if (
					!$ae_loc?.trusted_access &&
					Date.now() - $ae_loc?.last_cache_refresh > default_refresh_time
				) {
					if (log_lvl) {
						console.log(
							`ROOT LOOP: Last (default) local config reload too old for all caches: ${$ae_loc.last_cache_refresh}`
						);
					}

					// clear_idb();
					// clear_local();
					// clear_sess();

					// flag_clear_idb = true;
					// flag_clear_local = true;
					// flag_clear_sess = true;
					// flag_reload = true;
					// flag_expired = true;

					$ae_loc.allow_access = false;
					$ae_loc.cache_expired = true;

					// location.reload();

					clearInterval(interval);
				} else if (
					$ae_loc?.manager_access &&
					Date.now() - $ae_loc?.last_cache_refresh > manager_refresh_time
				) {
					if (log_lvl) {
						console.log(
							`ROOT LOOP: Last (manager) local config reload too old for all caches: ${$ae_loc.last_cache_refresh}`
						);
					}

					// flag_clear_idb = true;
					// flag_clear_local = true;
					// flag_clear_sess = true;
					// flag_reload = true;
					// flag_expired = true;

					$ae_loc.allow_access = false;
					$ae_loc.cache_expired = true;

					// location.reload();

					clearInterval(interval);
				} else {
					if (log_lvl > 1) {
						console.log(
							`ROOT LOOP: Last local config reload is recent: ${$ae_loc.last_cache_refresh}`
						);
					}
				}
			}, 45000);
		}
	});
</script>

<svelte:head>
	<link rel="stylesheet" href={ae_acct.loc.site_style_href} />
	<!-- <link rel="manifest" href="/manifest.json"> -->
</svelte:head>

{#if $ae_loc?.site_google_tracking_id && $ae_loc?.site_google_tracking_id.length > 0}
	<Analytics bind:site_google_tracking_id={$ae_loc.site_google_tracking_id} />
{/if}

<!-- class:z-index-50={$ae_loc?.debug_mode} -->
<!-- hover:bg-neutral-500/75 -->
<!-- focus:bg-neutral-500/75 -->
<!-- active:bg-neutral-500/75 -->
<div
	class:hidden={browser && $ae_sess?.debug_menu?.hide_quick_info}
	class="
        fixed top-0 bottom-0 w-full
        flex flex-col
        gap-1 items-center justify-start
        p-2
        bg-neutral-500/50
        z-40
        transition-all
        "
>
	<!-- WARNING: Generally this debug status popover should disapear very quickly when the page is loading correctly. If the page load fails, there is a good chance that JS no longer works as expected. Specifically, changing classes does not seem to work. -->
	<!-- class:hover:opacity-70={$ae_sess?.debug_menu?.hide_quick_info} -->
	<!-- class:opacity-30={$ae_sess.debug_menu.hide_quick_info} -->
	<div
		class:opacity-90={!$ae_sess.debug_menu.hide_quick_info}
		class:md:opacity-90={!$ae_sess.debug_menu.hide_quick_info}
		class="
            top-0
            w-full max-w-lg
            flex flex-col
            gap-1 items-center justify-center
            rounded-lg p-2
            preset-outlined-surface-600-400
            preset-filled-surface-200-800

            shadow-lg

            opacity-40 md:opacity-20 hover:opacity-100 focus:opacity-100 active:opacity-100
            transition-delay-500 transition-duration-1000 transition-timing-function-ease-out

            transition-all
            "
	>
		<div class:hidden={browser} class="flex flex-row items-center justify-between w-full">
			<span class="fas fa-cog fa-spin m-1"></span>
			<span class="text-center">App Loading</span>
			<span class="fas fa-cog fa-spin m-1"></span>
		</div>

		<div class="w-full flex flex-row flex-wrap gap-1 items-center justify-between">
			<button
				type="button"
				onclick={() => {
					if ($ae_sess?.debug_menu?.hide_quick_info) {
						$ae_sess.debug_menu.hide_quick_info = false;
						console.log('Showing quick info/debug menu.');
					} else {
						$ae_sess.debug_menu.hide_quick_info = true;
						console.log('Hiding quick info/debug menu.');
					}
					// if (log_lvl) {
					//     console.log('Toggling quick info/debug menu:', $ae_sess.debug_menu.hide_quick_info);
					// }
				}}
			>
				<span class="font-bold text-lg"> Quick Debug Info </span>
			</button>

			<button
				type="button"
				onclick={() => {
					$ae_sess.debug_menu.hide_quick_info = true;
					if (log_lvl) {
						console.log('Hiding quick info/debug menu.');
					}
				}}
				class:hidden={$ae_sess?.debug_menu?.hide_quick_info}
				class="
                btn btn-sm
                preset-outlined-surface-400-600 preset-filled-suface-200-800
                hover:preset-tonal-warning
                transition-all
                "
				title="Close Quick Info"
			>
				<!-- <span class="fas fa-times-circle mx-1"></span> -->
				<CircleX class="inline-block mx-1" />
				Close Quick Info
			</button>
		</div>

		<div class="flex flex-row flex-wrap gap-1 items-center justify-center">
			<button
				class="
                btn btn-sm
                preset-outlined-warning-800-200 preset-filled-warning-100-900
                hover:preset-tonal-success
                "
				title="Reload and clear the page cache"
				onclick={() => {
					clear_idb();
					window.location.reload(true);
				}}
			>
				<!-- <span class="fas fa-sync mx-1"></span> -->
				<RefreshCcw class="inline-block mx-1" />
				Quick Page Reload
				<!-- & -->
				<!-- <span class="fas fa-trash mx-1"></span> -->
				<!-- Clear Cache -->
			</button>

			<button
				type="button"
				onclick={() => {
					if (!confirm('Are you sure you want to clear the local and session storage?')) {
						return false;
					}
					// Clear the IndexedDB
					clear_idb();

					// Clear localStorage and sessionStorage
					clear_local();
					// clear_sess();

					// alert('IDB, Local, and Session Storage cleared. The page should now refresh on its own.');

					window.location.reload();
				}}
				class="
                btn btn-sm
                m-1
                preset-outlined-error-800-200 preset-filled-error-100-900
                hover:preset-tonal-success
                transition-all text-wrap
                "
				title="Reload and clear the page cache"
			>
				<!-- <span class="fas fa-sync mx-1"></span> -->
				<RefreshCcwDot class="inline-block mx-1" />
				<span> Clear Cache and Reload </span>
			</button>

			<MyClipboard
				value={`
Datetime = ${new Date().toISOString()}
URL = ${data.url.href}
Browser = ${navigator.userAgent}
account_id = ${$slct.account_id}
iframe = ${$ae_loc?.iframe}
access_type = ${$ae_loc?.access_type}
person_id = ${$ae_loc?.person_id}
full_name = ${$ae_loc?.full_name}
user_id = ${$ae_loc?.user_id}
username = ${$ae_loc?.username}
email = ${$ae_loc?.email}
                `}
				btn_text="Copy Quick Info"
				btn_title="Copy quick debug info to clipboard"
				btn_class="
                novi_btn
                btn btn-sm
                preset-outlined-tertiary-800-200
                preset-filled-tertiary-200-800
                hover:preset-filled-tertiary-600-400
                transition
                "
			></MyClipboard>
		</div>

		<table class="table-auto w-full text-sm">
			<thead>
				<tr class=""><th>Key</th><th>Value</th></tr>
			</thead>
			<tbody class="[&>tr]:hover:preset-tonal-primary [&>tr>td]:px-1">
				<tr class=""><td class="text-right">Datetime =</td><td>{new Date().toISOString()}</td></tr>
				<tr class=""
					><td class="text-right">URL =</td><td><span class="text-xs">{data.url.href}</span></td
					></tr
				>
				<tr class=""
					><td class="text-right">Browser</td><td
						><span class="text-xs">{navigator.userAgent}</span></td
					></tr
				>
				<tr class=""><td class="text-right">account_id =</td><td>{$slct.account_id}</td></tr>
				<tr class=""><td class="text-right">iframe =</td><td>{$ae_loc?.iframe}</td></tr>
				<tr class=""><td class="text-right">access_type =</td><td>{$ae_loc?.access_type}</td></tr>
				<tr class=""><td class="text-right">person_id =</td><td>{$ae_loc?.person_id}</td></tr>
				<tr class=""
					><td class="text-right">full_name =</td><td>{$ae_loc?.person?.full_name}</td></tr
				>
				<tr class=""><td class="text-right">user_id =</td><td>{$ae_loc?.user_id}</td></tr>
				<tr class=""><td class="text-right">username</td><td>{$ae_loc?.user?.username}</td></tr>
				<tr class=""><td class="text-right">email =</td><td>{$ae_loc?.user?.email}</td></tr>
			</tbody>
		</table>
	</div>
</div>

{#if browser && flag_new_ver}
	<div
		class="flex flex-col items-center justify-center max-w-lg mx-auto space-y-6 border border-red-500 rounded-lg p-4 bg-green-50 dark:bg-green-900 m-8"
	>
		<h1 class="text-4xl text-center font-bold text-green-600 dark:text-green-400">
			New Version Available
		</h1>
		<p class="text-lg text-center text-gray-800 dark:text-gray-200">
			A new version of the site is available. Please use the Clear Cache and Reload button below to
			update.
		</p>

		<button
			type="button"
			onclick={() => {
				// Clear the IndexedDB
				clear_idb();

				// Clear localStorage and sessionStorage
				clear_local();

				// alert('IDB, Local, and Session Storage cleared. The page should now refresh on its own.');

				// invalidateAll();

				window.location.reload();
			}}
			class="btn btn-lg m-1 preset-tonal-error border border-error-500 hover:preset-filled-success-500 text-error-1000 hover:text-error-800 transition-all text-wrap"
			title="Reload and clear the page cache to update"
		>
			<!-- <span class="fas fa-sync mx-1"></span> -->
			<RefreshCcwDot class="mx-1" />
			<span>
				Clear Cache and<br /> Reload to Update
			</span>
		</button>

		<!-- This is mainly for IDAA using iframes in the Novi site. -->
		<div class="text-center text-sm text-gray-500" class:hidden={!$ae_loc.iframe}>
			<p>
				If you have tried the "Clear Cache and Reload" button, you may need to manually reload the
				page using your browser's reload button or by pressing <kbd>Ctrl</kbd> + <kbd>R</kbd> or
				<kbd>Cmd</kbd>
				+ <kbd>R</kbd>.
			</p>
			<p>This sometimes happens with new versions of the app or when in an iframe.</p>
		</div>

		<div class="text-sm text-center text-gray-500 dark:text-gray-200">
			<span class="">Æther:</span>
			<span class=""> {$ae_loc?.ver} <ArrowBigRight class="inline-block" /> {$ae_sess?.ver}</span>
		</div>

		<button
			type="button"
			onclick={() => {
				window.location.reload();
			}}
			class="
                btn btn-sm m-1
                preset-tonal-surface border-surface-500
                hover:preset-tonal-warning hover:border-warning-500 hover:preset-outlined-warning
                text-warning-800 hover:text-warning-900
                transition-all
                "
		>
			<!-- <span class="fas fa-sync mx-1"></span> -->
			<RefreshCw class="mx-1" />
			Reload
		</button>
	</div>
{:else if browser && $ae_loc?.cache_expired}
	<div
		class="flex flex-col items-center justify-center max-w-lg mx-auto space-y-6 border border-red-500 rounded-lg p-4 bg-orange-50 dark:bg-orange-900 m-8"
	>
		<h1 class="text-4xl text-center font-bold text-red-500 dark:text-red-400">Expired Cache</h1>
		<p class="text-lg text-center text-gray-800 dark:text-gray-200">
			The cache for this site has expired. Please reload the page. You may need to sign in again.
		</p>

		<button
			type="button"
			onclick={() => {
				// Clear the IndexedDB
				clear_idb();

				// Clear localStorage and sessionStorage
				clear_local();

				alert('IDB, Local, and Session Storage cleared. The page should now refresh on its own.');

				window.location.reload();
			}}
			class="btn btn-lg m-1 preset-tonal-warning border border-warning-500 hover:preset-filled-success-500 text-error-1000 hover:text-error-800 transition-all text-wrap"
			title="Reload and clear the page cache"
		>
			<!-- <span class="fas fa-sync mx-1"></span> -->
			<RefreshCcwDot class="mx-1" />
			<span> Clear Cache and Reload </span>
		</button>

		<!-- This is mainly for IDAA using iframes in the Novi site. -->
		<div class="text-center text-sm text-gray-700 italic" class:hidden={!$ae_loc.iframe}>
			<p>
				If you have tried the "Clear Cache and Reload" button, you may need to manually reload the
				page using your browser's reload button or by pressing <kbd>Ctrl</kbd> + <kbd>R</kbd> or
				<kbd>Cmd</kbd>
				+ <kbd>R</kbd>.
			</p>
			<p>This sometimes happens with new versions of the app or when in an iframe.</p>
		</div>

		<div>
			<div class="text-sm text-center text-gray-500 dark:text-gray-200">
				<span class="">Expired:</span>
				<span class="">
					{Math.floor((Date.now() - $ae_loc.last_cache_refresh) / 60000)} minutes ago</span
				>

				<span class="">
					(max age: {Math.floor(default_refresh_time / 60000)} minutes)
				</span>
			</div>
			<div class="text-sm text-center text-gray-500 dark:text-gray-200">
				<span class="">Last Refresh:</span>
				<span class=""> {new Date($ae_loc.last_cache_refresh).toLocaleString()}</span>
			</div>
			<div class="text-sm text-center text-gray-500 dark:text-gray-200">
				<span class="">Access Level:</span>
				<span class=""> {$ae_loc.access_level ?? '-- not set --'}</span>
			</div>
			<div class="text-sm text-center text-gray-500 dark:text-gray-200">
				<span class="">Username:</span>
				<span class=""> {$ae_loc.user?.username ?? '-- not set --'}</span>
			</div>
		</div>

		<button
			type="button"
			onclick={() => {
				window.location.reload();
			}}
			class="btn btn-sm m-1 preset-tonal-surface hover:preset-tonal-warning border border-warning-500 hover:variant-outline-warning text-warning-800 hover:text-warning-900 transition-all"
			title="Reload page to clear some caches and check for updates"
		>
			<!-- <span class="fas fa-sync mx-1"></span> -->
			<RefreshCw class="mx-1" />
			Reload
		</button>
	</div>
{:else if browser && !$ae_loc?.allow_access}
	<!-- flag_denied -->
	<!-- !$ae_loc?.allow_access -->
	<div
		data-sveltekit-preload-data="false"
		class="flex flex-col items-center justify-center max-w-lg mx-auto space-y-6 border border-red-500 rounded-lg p-4 bg-red-50 dark:bg-red-900 m-8"
	>
		<h1 class="text-4xl text-center font-bold text-red-500 dark:text-red-400">Access Denied</h1>
		<p class="text-lg text-center text-gray-800 dark:text-gray-200">
			You do not have access to this site. You may need a <strong>passcode</strong>,
			<strong>sign in link</strong>, and or <strong>URL site key</strong>.
		</p>
		<!-- xx {JSON.stringify(data.route)} xx -->

		<div>
			<!-- access level/type -->
			<div class="text-sm text-center text-gray-500 dark:text-gray-200">
				<span class="">Access Level:</span>
				<span class=""> {$ae_loc.access_level ?? '-- not set --'}</span>
			</div>

			<!-- username and email -->
			<div class="text-sm text-center text-gray-500 dark:text-gray-200">
				<span class="">Username:</span>
				<span class=""> {$ae_loc.user?.username ?? '-- not set --'}</span>
			</div>
		</div>

		<button
			type="button"
			onclick={() => {
				window.location.reload();
			}}
			class="btn btn-sm m-1 preset-tonal-secondary hover:preset-tonal-warning border border-warning-500 hover:variant-outline-warning text-warning-800 hover:text-warning-900 transition-all"
			title="Reload page to clear some caches and check for updates"
		>
			<!-- <span class="fas fa-sync mx-1"></span> -->
			<RefreshCw class="mx-1" />
			<span> Reload </span>
		</button>

		<button
			type="button"
			onclick={() => {
				console.log('Reloading page...');
				// Clear the IndexedDB
				clear_idb();

				// Clear localStorage and sessionStorage
				clear_local();
				// clear_sess();

				alert('IDB, Local, and Session Storage cleared. The page should now refresh on its own.');

				window.location.reload();
			}}
			class="btn btn-sm m-1 preset-tonal-secondary hover:preset-tonal-warning border border-warning-500 hover:variant-outline-warning text-error-700 hover:text-error-900 transition-all text-wrap"
			title="Reload and clear the page cache"
		>
			<!-- <span class="fas fa-sync mx-1"></span> -->
			<RefreshCcwDot class="mx-1" />
			<span> Clear Cache and Reload </span>
		</button>

		<!-- This is mainly for IDAA using iframes in the Novi site. -->
		<div class="text-center text-sm text-gray-500" class:hidden={!$ae_loc?.iframe}>
			<p>
				If you have tried the "Clear Cache and Reload" button, you may need to manually reload the
				page using your browser's reload button or by pressing <kbd>Ctrl</kbd> + <kbd>R</kbd> or
				<kbd>Cmd</kbd>
				+ <kbd>R</kbd>.
			</p>
			<p>This sometimes happens with new versions of the app or when in an iframe.</p>
		</div>
	</div>
{:else if browser && $ae_loc?.allow_access}
	<!-- Should we check for "browser" here as well? This may hide some status information as a page is loading. -->

	<!-- The children will contain top level (directly under body tag) div tag(s) or similar. Modal and AppShell should also be set there. The AppShell gives access to a header, footer, AppBar (usually under header),  -->
	{@render children?.()}
{:else if browser || flag_reload}
	<div
		class="flex flex-col items-center justify-center max-w-lg mx-auto space-y-6 border border-red-500 rounded-lg p-4 bg-green-50 dark:bg-green-900 m-8"
	>
		<div>
			<span class="fas fa-spinner fa-spin mx-1"></span>
			Page data is loading...
		</div>
	</div>
{/if}

{#if browser}
	<!-- Always show if Trusted access or higher. Do not show if in iframe mode. -->
	{#if !$ae_loc?.iframe || $ae_loc?.trusted_access}
		<E_app_sys_menu
			{data}
			bind:hide={$ae_loc.sys_menu.hide}
			bind:expand={$ae_sess.sys_menu.expand}
		/>

		<!-- The app debug menu -->
		<E_app_debug_menu bind:hide={$ae_loc.debug_menu.hide} bind:expand={$ae_loc.debug_menu.expand} />
	{:else}
		<!-- Nothing to show -->
	{/if}
{:else}
	<!-- <div class="flex flex-col items-center justify-center max-w-lg mx-auto space-y-6 border border-red-500 rounded-lg p-4 bg-green-50 dark:bg-green-900 m-8">
    <div>
        <span class="fas fa-spinner fa-spin mx-1"></span>
        Layout loading...
    </div>

    <button
        type="button"
        onclick={() => {
            window.location.reload();
        }}
        class="btn btn-sm m-1 preset-tonal-secondary border-secondary-500 hover:preset-tonal-warning border-warning-500 hover:variant-outline-warning text-warning-800 hover:text-warning-900 transition-all"
        title="Reload page to clear some caches and check for updates"
        >
        <RefreshCw class="mx-1" />
        <span>
        Reload
        </span>
    </button>

    <button
        type="button"
        onclick={() => {
            console.log('Reloading page...');
            // Clear the IndexedDB
            clear_idb();

            // Clear localStorage and sessionStorage
            clear_local();
            // clear_sess();

            alert('IDB, Local, and Session Storage cleared. The page should now refresh on its own.');

            window.location.reload();
        }}
        class="btn btn-sm m-1 preset-tonal-secondary border-secondary-500 hover:preset-tonal-warning border-warning-500 hover:variant-outline-warning text-error-700 hover:text-error-900 transition-all text-wrap"
        title="Reload and clear the page cache"
        >
        <RefreshCcwDot class="mx-1" />
        <span>
        Clear Cache and Reload
        </span>
    </button>
</div> -->
{/if}

<style lang="postcss">
</style>
