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

	let log_lvl: number = $state(1);

	// *** Import Svelte specific
	import { page } from '$app/state';
	import { browser } from '$app/environment';
	// import { goto, invalidate, pushState, replaceState } from '$app/navigation';

	// *** 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 { idaa_loc, idaa_sess, idaa_slct, idaa_trig, idaa_prom } from '$lib/stores/ae_idaa_stores';

	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_func } from '$lib/ae_events_functions';

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

	import Comp__event_obj_qry from './ae_idaa_comp__event_obj_qry.svelte';
	import Comp__event_obj_li_wrapper from './ae_idaa_comp__event_obj_li_wrapper.svelte';
	// import Comp__event_obj_id_edit from './ae_idaa_comp__event_obj_id_edit.svelte';
	// import Comp__event_obj_id_view from './ae_idaa_comp__event_obj_id_view.svelte';

	// let event_id = page.url.searchParams.get('event_id') ?? null;
	// if (!event_id) {
	//     $idaa_slct.event_id = null;
	// } else {
	//     console.log(`ae Recovery Meetings - [event_id] +page.ts: event_id = `, event_id);
	//     $idaa_slct.event_id = event_id;
	//     $idaa_trig.event_id = event_id;
	// }

	if (browser) {
		$idaa_slct.event_id = null; // Just in case
		let message = { event_id: null };
		window.parent.postMessage(message, '*');

		$idaa_trig.event_li_qry = true;
		// $idaa_trig = 'load__event_obj_li';
	}

	let event_id_random_li: Array<string> = $state([]);

	// *** Functions and Logic
	// let lq_new__event_obj_li = $derived(liveQuery(async () => {
	//     let link_to_type: string = 'account';
	//     let link_to_id: string = $ae_lock.account_id;
	//     if (log_lvl > 1) {
	//         console.log(`link_to_type: ${link_to_type}; link_to_id: ${link_to_id}; event_id_random_li:`, event_id_random_li);
	//     }

	//     // Check if event_id_random_li is an array and not undefined
	//     if (event_id_random_li) {
	//         if (log_lvl) {
	//             console.log(`Trying bulkGet:`, event_id_random_li);
	//         }
	//         let results = await db_events.event
	//             .bulkGet(event_id_random_li);

	//         return results;
	//     } else if (link_to_type && link_to_id) {
	//         if (log_lvl) {
	//             console.log(`Trying where: ${link_to_type}; equals: ${link_to_id}`);
	//         }
	//         let results: any = null;
	//         if ($idaa_loc.recovery_meetings.qry__order_by == 'name') {
	//             results = await db_events.event
	//                 .where(`${link_to_type}_id`)
	//                 .equals(link_to_id)
	//                 .and((event) => {
	//                     return event.hide == false;
	//                 })
	//                 .and((event) => {
	//                     return event.enable == true;
	//                 })
	//                 .sortBy('name')
	//         } else {
	//             results = await db_events.event
	//                 .where(`${link_to_type}_id`)
	//                 .equals(link_to_id)
	//                 .and((event) => {
	//                     return event.hide == false;
	//                 })
	//                 .and((event) => {
	//                     return event.enable == true;
	//                 })
	//                 .sortBy('updated_on')
	//         }

	//         return results;
	//     } else {
	//         if (log_lvl) {
	//             console.log('Trying... Nothing to load');
	//         }
	//         return null;
	//     }
	// }));

	// let lq__event_obj = $derived(liveQuery(async () => {
	//     let results = await db_events.event
	//         .get($idaa_slct.event_id ?? '');

	//     return results;
	// }));

	// This (event_li trigger for IDAA) is not currently being used.
	// Updated 2024-11-19
	// $effect(() => {
	//     if ($idaa_trig.event_li) {
	//         $idaa_trig.event_li = false;

	//         if (log_lvl) {
	//             console.log(`Triggered: $idaa_trig.event_li`);
	//         }

	//         if ($idaa_loc.recovery_meetings.qry__enabled !== 'all' || $idaa_loc.recovery_meetings.qry__hidden !== 'all') {
	//             console.log(`Deleting disabled or hidden event.`);
	//             let results = db_events.event
	//                 .clear();
	//             console.log(`Deleted ${results} disabled event.`);

	//         }

	//         $idaa_prom.load__event_obj_li = events_func.load_ae_obj_li__event({
	//             api_cfg: $ae_api,
	//             for_obj_type: 'account',
	//             for_obj_id: $ae_loc.account_id,
	//             qry_conference: false,
	//             enabled: $idaa_loc.recovery_meetings.qry__enabled,
	//             hidden: $idaa_loc.recovery_meetings.qry__hidden,
	//             limit: $idaa_loc.recovery_meetings.qry__limit,
	//             order_by_li: $idaa_loc.recovery_meetings.qry__order_by_li,
	//             try_cache: true,
	//             log_lvl: log_lvl,
	//         });
	//     }
	// });

	// Updated 2024-11-19
	$effect(() => {
		if ($idaa_trig.event_li_qry) {
			$idaa_trig.event_li_qry = false;

			log_lvl = 2;

			if (log_lvl) {
				console.log(`Triggered: $idaa_trig.event_li_qry`);
			}

			// $idaa_sess.recovery_meetings.qry__status = 'loading';

			let and_physical = $idaa_loc.recovery_meetings.qry__physical;
			let and_virtual = $idaa_loc.recovery_meetings.qry__virtual;
			let and_type = $idaa_loc.recovery_meetings.qry__type;
			let fulltext_str = $idaa_loc.recovery_meetings.qry__fulltext_str?.trim() ?? null;
			let enabled = $idaa_loc.recovery_meetings.qry__enabled;
			let hidden = $idaa_loc.recovery_meetings.qry__hidden;
			let limit = $idaa_loc.recovery_meetings.qry__limit;
			let order_by_li = $idaa_loc.recovery_meetings.qry__order_by_li;
			let search_delay = 15;
			let max_tries = 5;

			if (enabled !== 'all' || hidden !== 'all') {
				console.log(`Deleting disabled or hidden event.`);
				let results = db_events.event.clear();
				console.log(`Deleted ${results} disabled event.`);
			}

			if (
				$idaa_sess.recovery_meetings?.qry__status != null &&
				$idaa_sess.recovery_meetings?.qry__status != 'done'
			) {
				console.log('*** TEST SEARCH - $idaa_sess.recovery_meetings.qry__status != done ***');
				// WARNING: This is a temporary fix for the search string. It needs to be fixed in the future. Using lk_search_str for now.
				$idaa_sess.recovery_meetings.status_qry__last_request_str = fulltext_str;

				// We want to delay the initial search request to give the previous search request to finish.
				let random_delay = Math.floor(Math.random() * 50);
				search_delay += 50 + random_delay;
			}

			event_id_random_li = []; // Resetting this seems to help trigger the new results to show correctly??? 2025-07-10

			let count = 0;
			let request_loop = setInterval(() => {
				count++;
				if (log_lvl) {
					console.log(`*** TEST SEARCH - Search delay: ${search_delay} *** loop count=${count}`);
				}
				if (count >= max_tries) {
					console.log('*** TEST SEARCH - Max tries reached ***');
					clearInterval(request_loop);
				}

				if (
					$idaa_sess.recovery_meetings?.qry__status != null &&
					$idaa_sess.recovery_meetings?.qry__status != 'done'
				) {
					let random_delay = Math.floor(Math.random() * 25);
					search_delay += 25 + random_delay;
					console.log(
						`*** TEST SEARCH - $idaa_sess.recovery_meetings.qry__status == loading wait *** search_delay=${search_delay}`
					);
					// $idaa_sess.status_qry__last_request_str = fulltext_str;
				} else {
					console.log('*** TEST SEARCH - $idaa_sess.recovery_meetings.qry__status != loading ***');

					$idaa_sess.recovery_meetings.qry__status = 'loading';
					// event_id_random_li = [];

					and_physical ?? null;
					and_virtual ?? null;
					and_type ?? null;
					// if (and_type) and_type = and_type;
					// if (!and_type) {
					//     and_type = null;
					// }

					console.log(
						`TEST - and_physical: ${and_physical}; and_virtual: ${and_virtual}; and_type: ${and_type}; qry__fulltext_str: ${fulltext_str}`
					);

					$idaa_prom.load__event_obj_qry = events_func
						.qry_ae_obj_li__event({
							api_cfg: $ae_api,
							for_obj_type: 'account',
							for_obj_id: $ae_loc.account_id,

							qry_conference: false,
							qry_physical: and_physical,
							qry_virtual: and_virtual,
							qry_type: and_type,
							qry_str: fulltext_str,

							enabled: enabled,
							hidden: hidden,
							limit: limit,
							order_by_li: order_by_li,
							log_lvl: log_lvl
						})
						.then(function (search_results) {
							// Processing the results from the search.
							$idaa_sess.recovery_meetings.qry__status = 'processing';
							$idaa_slct.event_obj_li = search_results;
							if (log_lvl) {
								console.log(`Found ${search_results.length} matching events.`);
								console.log(
									'TEST SEARCH - Search done. Need to pull out the id_random list for bulk load.'
								);
							}
							event_id_random_li = generate_id_random_li({ event_obj_li: search_results });

							// $idaa_sess.recovery_meetings.qry__status = 'done';

							// if (log_lvl) {
							//
							// }
							// console.log(`TEST search: ${$lq_kv__event_obj_li}`);

							// event_id_random_li = [];

							// // We need to loop through the array of objects and get the event_id_random from each object a new list of event_id_randoms. Then we can use this list to get the full objects from the database.
							// let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.
							// if (search_results && search_results.length) {
							//     for (let i = 0; i < search_results.length; i++) {
							//         tmp_li.push($idaa_slct.event_obj_li[i].event_id_random);
							//     }
							// }
							// event_id_random_li = tmp_li;
						})
						.finally(() => {
							// event_id_random_li = $idaa_slct.event_obj_li.map(session_obj => session_obj.event_id_random);

							// Finally done with the search.
							$idaa_sess.recovery_meetings.qry__status = 'done';

							if (log_lvl > 1) {
								console.log(
									`TEST SEARCH - qry__status: ${$idaa_sess.recovery_meetings.qry__status} event_id_random_li:`,
									event_id_random_li
								);
								// console.log(`TEST SEARCH - search live query: ${$lq_kv__event_obj_li}`);
							}
						});
					clearInterval(request_loop);
				}
			}, search_delay);
		}
	});

	// $effect(() => {
	//     if ($idaa_sess.recovery_meetings.qry__status == 'done') {
	//         if (log_lvl) {
	//             console.log(`*** TEST SEARCH - $idaa_sess.recovery_meetings.qry__status == done ***`);
	//         }
	//         // We are done with the search.
	//         $idaa_sess.recovery_meetings.qry__status = null;

	//         // We need to loop through the array of objects and get the event_id_random from each object a new list of event_id_randoms. Then we can use this list to get the full objects from the database.
	//         let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.
	//         if ($idaa_slct.event_obj_li && $idaa_slct.event_obj_li.length) {
	//             event_id_random_li = [];
	//             // console.log(`TEST SEARCH - Get ids:`, $idaa_slct.event_obj_li);
	//             for (let i = 0; i < $idaa_slct.event_obj_li.length; i++) {
	//                 tmp_li.push($idaa_slct.event_obj_li[i].event_id_random);
	//             }
	//         }
	//         event_id_random_li = tmp_li;
	//         // console.log(`TEST search: event_id_random_li`, $state.snapshot(event_id_random_li));
	//     }
	// });

	function generate_id_random_li({
		event_obj_li = $idaa_slct.event_obj_li
	}: {
		event_obj_li?: Array<any>;
	} = {}) {
		let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

		// We need to loop through the array of objects and get the id_random from each object a new list of id_randoms. Then we can use this list to get the full objects from the database.
		if (event_obj_li && event_obj_li.length) {
			for (let i = 0; i < event_obj_li.length; i++) {
				tmp_li.push(event_obj_li[i].event_id_random);
			}
		}
		if (log_lvl) {
			console.log(`generate_id_random_li:`, tmp_li);
		}

		return tmp_li;
	}

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

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

		// add_activity_log(
		//     {
		//         action: 'idaa_meetings_page',
		//         action_with: 'browser',
		//     }
		// );
	}

	function add_activity_log({
		action = 'idaa_meetings_page',
		action_with = 'none'
	}: {
		action?: string;
		action_with?: string;
	}) {
		let last_cache_refresh_iso = new Date($ae_loc?.last_cache_refresh);

		let activity_description = `
        ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? 'no-email'}
        allow=${$ae_loc?.allow_access}
        last_cache_refresh=${last_cache_refresh_iso.toLocaleString()}
        data_route=${data?.route.toString() ?? 'unknown'}
    `;

		let data_kv = {
			external_client_id: data?.route.id,
			name: `IDAA: ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? ''}`,
			description: activity_description ?? null,
			object_type: 'event', // archive, post, event
			// object_id_random: data?.params?.event_id ?? null,
			// object_id_random: ae_acct.slct.archive_id, // data?.params?.archive_id ?? null,
			url_root: data?.url.origin,
			// url_full_path: data?.url.href,
			url_full_path: data?.url.pathname,
			url_params: data?.url.searchParams.toString(),
			action: action,
			action_with: action_with ?? 'none',
			meta_json: {
				allow_access: $ae_loc?.allow_access,
				last_cache_refresh: $ae_loc?.last_cache_refresh,
				last_cache_refresh_iso: last_cache_refresh_iso.toISOString(),
				last_cache_refresh_locale: last_cache_refresh_iso.toLocaleString(),
				access_level: $ae_loc?.access_level,
				iframe: $ae_loc?.iframe
				// site_access_key: $ae_loc?.site_access_key,
				// site_domain_access_key: $ae_loc?.site_domain_access_key,
				// site_domain: $ae_loc?.site_domain,
				// extra_data: extra_data ?? '',
				// log_lvl: log_lvl,
			}
		};

		core_func.create_ae_obj__activity_log({
			api_cfg: $ae_api,
			account_id: $ae_loc.account_id,
			data_kv: data_kv,
			log_lvl: log_lvl
		});
	}

	// let hide_scroll_btn = $state(true); // This is to hide the scroll to top button initially
	// let scroll_y = $state(75);

	// function go_top() {
	//     document.body.scrollIntoView();
	// }

	// function scroll_container() {
	//     console.log('Element', document.getElementById('ae_idaa__recovery_meetings'))
	//     return document.getElementById('ae_idaa__recovery_meetings') || document.documentElement || document.body;
	//     // return document.documentElement || document.body;
	// }

	// function handle_on_scroll() {
	//     if (!scroll_container()) {
	//         return;
	//     }
	//     console.log(`Scroll position: ${scroll_container().scrollTop}`);

	//     let show_on_px = 500; // The scroll position at which the button will be shown

	//     if (scroll_container().scrollTop > show_on_px) {
	//         hide_scroll_btn = false;
	//     } else {
	//         hide_scroll_btn = true;
	//     }
	// }
</script>

<svelte:head>
	<title>
		IDAA Recovery Meetings - Novi - {$ae_loc?.title}
	</title>
</svelte:head>

<Comp__event_obj_qry />

<!-- preset-filled-surface-100-900  -->
<Element_data_store
	ds_code="recovery_meetings_info"
	ds_type="html"
	class_li="
        rounded-lg
        preset-outlined-surface-200-800
        m-auto p-2 space-y-2
        w-full max-w-xl
        "
	show_edit_btn={true}
/>

<!-- Having this if statement seems to help with loading results. Especially new results. Unsure why... 2025-07-10 -->
<!-- {#if $lq_new__event_obj_li && $lq_new__event_obj_li?.length} -->
{#if Array.isArray(event_id_random_li) && event_id_random_li.length}
	<Comp__event_obj_li_wrapper
		{event_id_random_li}
		link_to_type={'account'}
		link_to_id={$ae_loc.account_id}
		{log_lvl}
	/>
{:else}
	<div class="space-y-2">
		{#if $idaa_sess.recovery_meetings.qry__status === 'loading'}
			<div class="ae_highlight ae_padding_md ae_row ae_flex_justify_center">
				<span class="fas fa-spinner fa-spin m-1"></span>
				Loading...
			</div>
		{:else}
			<div class="ae_highlight ae_padding_md ae_row ae_flex_justify_center">
				No recovery meetings available to show. The search may need to be changed.
				{$idaa_sess.recovery_meetings.qry__status ?? 'Unknown Query Status'}
			</div>
		{/if}
	</div>
{/if}
