<script lang="ts">
	export let data: any;
	console.log(`ae_events_badges [slug] +page data:`, data);

	import { onMount } from 'svelte';

	import type { key_val } from '$lib/stores/ae_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	import { api } from '$lib/api/api';
	import { events_func } from '$lib/ae_events_functions';
	import { liveQuery } from 'dexie';
	import { db_events } from '$lib/ae_events/db_events';
	import { ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/stores/ae_stores';
	import {
		events_loc,
		events_sess,
		events_slct,
		events_trigger
	} from '$lib/stores/ae_events_stores';

	import Element_qr_scanner from '$lib/element_qr_scanner_v2.svelte';
	import Element_ae_crud from '$lib/elements/element_ae_crud.svelte';

	import { goto } from '$app/navigation';

	// The lq__ prefix is used to indicate that this is a liveQuery object and it should use the $ prefix when referencing the object.
	let lq__event_badge_li = liveQuery(() => db_events.badge.toArray());

	// import Edit_modal_event_badge from '../10_edit_modal__event_badge_obj.svelte';

	let ae_promises: key_val = {};
	let load_obj_li_results: Promise<any> | key_val;
	let search_submit_results: Promise<any> | key_val;
	// let scan_submit_results: Promise<any>|key_val;

	$ae_loc.hostname = data.url.hostname;
	$ae_loc.site_domain = data.url.origin;

	// We don't want the edit or view to show up by default. Maybe if we see an object ID param in the URL, we can show a modal.
	$events_loc.show_edit__event_badge_obj = false;
	$events_loc.show_view__event_badge_obj = false;

	// These will likely be used for patch/update triggers. Maybe delete?
	let ae_triggers: key_val = {};

	let ae_event_badge_get_promise: Promise<any>;
	let ae_event_obj_get_promise;

	if ($events_slct.event_id) {
		console.log('Selected Event ID:', $events_slct.event_id);
		// $events_trigger = 'load__event_badge_obj_li';
		// $events_trigger = 'load__event_obj';
	}

	// Reset this to an empty array.
	$events_slct.badge_obj_li = [];

	// ISHLT 2024 badge type codes
	let badge_type_code_li = [
		{ code: 'current_member', name: 'Member' },
		{ code: 'inactive_member', name: 'Non-Member' },
		{ code: 'current_member_trainee', name: 'Trainee Member' },
		{ code: 'inactive_member_trainee', name: 'Trainee Non-Member' },
		{ code: 'ex_all', name: 'Exhibitor All Access' },
		{ code: 'ex_booth', name: 'Exhibitor Booth Staff' },
		{ code: 'hftx', name: 'HFTX Master Academy' },
		{ code: 'mcs', name: 'MCS Master Academy' },
		{ code: 'pediatric', name: 'Pediatric' },
		{ code: 'guest', name: 'Guest' },
		{ code: 'staff', name: 'Staff' },
		{ code: 'volunteer', name: 'Volunteer' },
		{ code: 'test', name: 'Test' }
	];

	onMount(() => {
		console.log('Events Badges [New/Edit]: +page.svelte');

		// Load the AE Obj with ID based on the URL param.
		if (data.url.searchParams.get('event_id')) {
			$events_loc.event_id = data.url.searchParams.get('event_id');
			$events_slct.event_id = data.url.searchParams.get('event_id');
		}

		// Load the Event Presenter Obj with ID based on the URL param.
		if (data.url.searchParams.get('event_badge_id')) {
			$events_slct.badge_id = data.url.searchParams.get('event_badge_id');
		}

		let url = window.location.href;
		$ae_loc.href_url = url;

		// The assumption is that if they know how to get to exactly this page then they are authorized in some way. Very limited risk!
		$ae_loc.auth_access = true;
	});

	if ($events_slct.event_badge_id) {
		console.log('Selected Event Presenter ID:', $events_slct.event_badge_id);
		$events_trigger = 'load__event_badge';

		// $events_loc.show_edit__event_badge_obj = true;
		// $events_trigger = 'show_edit__event_badge';
	}

	$: if ($events_trigger == 'load__event_badge' && $events_slct.event_badge_id) {
		console.log('Selected Event Presenter ID:', $events_slct.event_badge_id);

		$events_trigger = null;

		handle_load_ae_obj_id__event_badge({
			event_badge_id: $events_slct.event_badge_id,
			try_cache: false
		});

		// modalStore.trigger(modal_edit__event_badge);
		// $events_trigger = 'show_edit__event_badge';
	}

	async function handle_load_ae_obj_id__event_badge({ event_badge_id, try_cache = false }) {
		console.log(`*** handle_load_ae_obj_id__event_badge() *** event_badge_id=${event_badge_id}`);

		let params = {};

		// $ae_sess.hub.event_badge_id_status_qry__search = 'loading';
		ae_event_badge_get_promise = api
			.get_ae_obj_id_crud({
				api_cfg: $ae_api,
				obj_type: 'event_badge',
				obj_id: event_badge_id,
				use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
				use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
				params: params,
				log_lvl: 0
			})
			.then(function (event_badge_get_result) {
				if (event_badge_get_result) {
					$events_slct.event_badge_obj = event_badge_get_result;
					console.log(`event_badge object:`, $events_slct.event_badge);
				}

				// Auto show the selected event_badge ID
				// Is this pushState needed here?
				// Set the URL param "event_badge_id" to the current event_badge ID.
				// const url = new URL(location);
				// url.searchParams.set('event_badge_id', $events_slct.event_badge_id);
				// history.pushState({}, '', url);

				// Is this postMessage needed here?
				// let message = {'event_badge_id': $events_slct.event_badge_id};
				// window.parent.postMessage(message, "*");
			})
			.catch(function (error: any) {
				console.log('No results returned or failed.', error);
			});

		return ae_event_badge_get_promise;
	}

	// Updated 2024-03-06 late
	$: if ($events_trigger == 'load__event_badge_obj_li' && $events_slct.event_id) {
		console.log(`load__event_badge_obj_li() $events_slct.event_id=${$events_slct.event_id}`);

		$events_trigger = null;

		if (
			!$events_sess.badges.fulltext_search_qry_str ||
			$events_sess?.badges.fulltext_search_qry_str.length <= 1
		) {
			$events_slct.badge_obj_li = [];
			// $events_sess.badges.fulltext_search_qry_str = '';
		} else {
			let type_code = $events_sess.badges.search_badge_type_code;

			let search_str = $events_sess.badges.fulltext_search_qry_str.trim();
			let search_method = 'lk'; // 'ft', 'lk', 'eq'
			let ft_search_str_new = '';
			let lk_search_str_new = '';

			if (search_method == 'ft') {
				// Add quotes around the search string to make it an exact match.
				ft_search_str_new = `"${search_str}"`;
			} else if (search_method == 'lk') {
				// Add a wildcard to the search string to make it a like match.
				lk_search_str_new = search_str
					.trim()
					.replace(',', ' ')
					.replace(';', ' ')
					.replace('  ', '%')
					.replace(' ', '%');
				lk_search_str_new = `%${lk_search_str_new}%`;
			}
			console.log(`"${search_str}"`);

			let enabled = 'enabled';
			let hidden = 'not_hidden';
			let limit = 35;

			if ($ae_loc.administrator_access) {
				enabled = 'all';
				hidden = 'all';
				limit = 250;
			} else if ($ae_loc.trusted_access) {
				enabled = 'enabled';
				hidden = 'all';
				limit = 150;
			}

			if ($events_sess.status_qry__search == 'loading') {
				console.log('*** $events_sess.status_qry__search == loading ***');

				setTimeout(() => {
					console.log('Delayed for X second.');

					$events_sess.status_qry__search = 'loading';

					search_submit_results = events_func
						.search__event_badge({
							api_cfg: $ae_api,
							event_id: $events_slct.event_id,
							type_code: type_code,
							fulltext_search_qry_str: ft_search_str_new,
							like_search_qry_str: lk_search_str_new,
							external_event_id: $events_loc.badges.default__external_registration_id,
							enabled: enabled,
							hidden: hidden,
							limit: limit
						})
						.then(function (search_results) {
							$events_slct.badge_obj_li = search_results;
							console.log(search_results);
							$events_sess.status_qry__search = 'done';
						});
				}, 250);
			} else {
				console.log('*** $events_sess.status_qry__search != loading ***');

				$events_sess.status_qry__search = 'loading';

				search_submit_results = events_func
					.search__event_badge({
						api_cfg: $ae_api,
						event_id: $events_slct.event_id,
						type_code: type_code,
						fulltext_search_qry_str: ft_search_str_new,
						like_search_qry_str: lk_search_str_new,
						external_event_id: $events_loc.badges.default__external_registration_id,
						enabled: enabled,
						hidden: hidden,
						limit: limit
					})
					.then(function (search_results) {
						$events_slct.badge_obj_li = search_results;
						console.log(search_results);
						$events_sess.status_qry__search = 'done';
					});
			}
		} // end if search string is valid
	}

	let load_event_badge_results = null;
	function handle_qr_scan_result(event) {
		console.log('*** handle_qr_scan_result() ***');

		let qr_scan_result = event.detail.result;
		console.log(qr_scan_result);
		let qr_scan_obj = ae_util.process_data_string(qr_scan_result);

		if (qr_scan_obj.qr_type == 'OBJ') {
			console.log(`Got a QR type of OBJ. Type ${qr_scan_obj.type}; ID ${qr_scan_obj.id}`);

			if (qr_scan_obj.type && qr_scan_obj.id && qr_scan_obj.type == 'event_badge') {
				console.log(`Found an Event Badge object type and ID.`);
				let event_badge_id = qr_scan_obj.id;

				$events_sess.badges.qr_scan_result = `Found a badge type with ID: ${event_badge_id}`;

				load_event_badge_results = events_func
					.handle_load_ae_obj_id__badge({ api_cfg: $ae_api, badge_id: event_badge_id })
					.then((result) => {
						$events_slct.badge_id = event_badge_id;
						$events_slct.badge_obj = result;
						console.log(result);

						// Confirm they want to view the badge.
						if (
							$events_slct.badge_obj.print_count >= 1 &&
							!confirm(
								`That badge has already been printed ${$events_slct.badge_obj.print_count} times. View badge for ${$events_slct.badge_obj.full_name}?`
							)
						) {
							return;
						}

						// ae_util.handle_url_and_message('event_badge_id', badge_obj.event_badge_id_random);

						// Go to the badge view page
						// Example: /event/badge/view_badge?event_badge_id=THE_ID
						goto(
							`/event/badge/view_badge?event_badge_id=${$events_slct.badge_obj.event_badge_id_random}`,
							{ replaceState: true }
						);
					});
			} else if (qr_scan_obj.type && qr_scan_obj.id && qr_scan_obj.type == 'event_exhibit') {
				console.log(`Ignoring.`);
			} else if (qr_scan_obj.type && qr_scan_obj.id && qr_scan_obj.type == 'event_person') {
				console.log(`Ignoring.`);
			} else if (qr_scan_obj.type && qr_scan_obj.id && qr_scan_obj.type == 'event_session') {
				console.log(`Ignoring.`);
			} else {
				console.log(`Ignoring. The object returned was unexpected or not valid.`);
				console.log(qr_scan_obj);
			}
		} else if (qr_scan_obj.qr_type == 'MECARD') {
			console.log(
				`Got a QR type of MECARD. This was not expected, but we will at least display it???`
			);

			// https://github.com/ertant/vCard
			// vcard = vCardParser.parse(qr_scan_obj.str); // vCard
			// console.log(vcard);

			mecard = qr_scan_obj.str.split(';'); // vCard
			// NOTE: Next we need to loop through the values and split each again on ":".
			// NOTE: Then probably do a second check based on the known key values (N, EMAIL, ADR).
			console.log(mecard);

			show_mecard = true;
		} else {
			console.log(
				`Got a QR type of ${qr_scan_obj.qr_type}. Display warning to user, but otherwise ignoring.`
			);
			console.log(qr_scan_obj);
		}
	}

	function handle_qr_camera(event) {
		console.log('*** handle_qr_camera() ***', event.detail);

		if (!$ae_loc.hub.qr) {
			$ae_loc.hub.qr = {};
		}

		if (event.detail.status == 'allowed') {
			// console.log('Camera access allowed');
			$ae_loc.hub.qr.camera_status = 'allowed';
		} else if (event.detail.status == 'denied') {
			console.log('Camera access denied!?');
			$ae_loc.hub.qr.camera_status = 'denied';
		}
	}
</script>

<section class="ae_events_badges_review md:container h-full mx-auto">
	<!-- {#if $ae_loc.ds.hub__page__events_badges__create_info_header} -->
	{#if $ae_loc.iframe}
		<span class="flex flex-row items-center justify-center">
			<img
				src={$ae_loc.site_cfg_json?.header_image_path}
				alt="header"
				class="w-auto max-h-20 m-2"
			/>
			<h1 class="h3 text-center m-2">Review & Print<br />Your Badge</h1>
		</span>
	{:else}
		<header>
			<h1 class="h2 text-center">Badge Review and Print</h1>
		</header>
	{/if}

	<div class="preset-tonal-success border border-success-500 my-2 p-2 flex flex-row items-center">
		{#if $events_sess.badges.show_form__search}
			<form
				on:submit|preventDefault={() => {
					$events_trigger = 'load__event_badge_obj_li';
				}}
				autocomplete="off"
				class="form grow flex flex-row flex-wrap gap-1 justify-center items-center w-full"
			>
				{#if $ae_loc.trusted_access && badge_type_code_li}
					<div class="search_by_badge_type_code">
						<select
							bind:value={$events_sess.badges.search_badge_type_code}
							on:change={() => {
								$events_trigger = 'load__event_badge_obj_li';
							}}
							class="select text-xs transition-all"
						>
							<option value="">-- All Badge Types --</option>
							{#each badge_type_code_li as badge_type_code}
								<option value={badge_type_code.code}>{badge_type_code.name}</option>
							{/each}
						</select>
					</div>
				{/if}

				<!-- <input
    type="search"
    placeholder="name, email, affiliations"
    id="badge_fulltext_search_qry_str"
    name="fulltext_search_qry_str"
    bind:value={$events_sess.badges.fulltext_search_qry_str}
    class="input text-xl hover:text-3xl font-bold font-mono w-96"
    on:change={() => {
        if ($events_sess.badges.fulltext_search_qry_str.length >= 3) {
            $events_trigger = 'load__event_badge_obj_li';
        }
    }}
    > -->
				<input
					type="search"
					placeholder="name, email, affiliations"
					id="badge_fulltext_search_qry_str"
					name="fulltext_search_qry_str"
					bind:value={$events_sess.badges.fulltext_search_qry_str}
					class="input text-1xl hover:text-3xl font-bold font-mono w-96 hover:w-2/5 transition-all"
					on:keyup={() => {
						if ($events_sess.badges.fulltext_search_qry_str.length >= 3) {
							$events_trigger = 'load__event_badge_obj_li';
						}
					}}
					autofocus
					suggest="off"
					data-lpignore="true"
				/>

				<button
					type="submit"
					class="btn btn-lg preset-tonal-success border border-success-500 hover:preset-tonal-success text-2xl font-bold w-48 transition-all"
					on:click={() => {}}
				>
					{#if $events_sess.status_qry__search == 'loading'}
						<span class="fas fa-spinner fa-spin"></span>
					{:else}
						<!-- Nothing -->
					{/if}
					<span class="fas fa-search mx-1"></span>
					Search
				</button>
			</form>

			<!-- **BEGIN** Scan Form -->
		{:else if $events_sess.badges.show_form__scan}
			<!-- <div class="ae_quick_modal_container">
    <section
        class="
            ae_quick_popover
            events__badges__scan
            z-50
            flex
            flex-col
            gap-4
            justify-stretch
            max-h-full
            min-w-full
            "
        >
        <header class="popover__header flex gap-1 justify-between items-center p-1 border-b">
            <h2 class="h3">Scan</h2>

            <div class="popover__actions">
                <button
                    type="button"
                    class="btn variant-soft-primary"
                    on:click={() => {
                        $events_sess.badges.show_form__scan = false;
                        $events_sess.badges.qr_scan_start = false;
                    }}
                    >
                    <span class="fas fa-times mx-1"></span>
                    Close
                </button>
            </div>
        </header>

        <section class="popover__content grow flex flex-col gap-4 items-center ae_modal_scrollfix"> -->

			<!-- <div class=""> -->
			<!-- <Element_qr_scanner start_qr_scanner={$events_sess.badges.qr_scan_start} show_qr_scan_result={true} show_qr_manual_badge_id_entry_option={true} on:qr_scan_result={handle_qr_scan_result} on:qr_camera={handle_qr_camera} /> -->
			<!-- </div> -->

			<!-- <div class="qr_quick_results variant-soft-secondary font-bold p-4">
            {@html $events_sess.badges.qr_scan_result ?? 'No results yet'}
        </div> -->

			<!-- This block needs to be moved or something. It takes up too much space! -->
			<!-- This uses the events_slct with badge_id and badge_obj. -->
			<!-- {#if $events_slct.badge_id && $events_slct.badge_obj} -->

			<!-- {/if} -->
		{/if}
		<!-- **END** Scan Form -->

		<div>
			{#if $events_sess.badges.show_form__search}
				<button
					type="button"
					on:click={() => {
						localStorage.setItem('ae_badge_printed_redirect_path', '/events_badges/review');
						// goto('/events_badges/print', {replaceState: true});

						$events_sess.badges.show_form__search = false;
						$events_sess.badges.show_form__search_results = false;
						$events_sess.badges.show_form__scan = true;
						$events_sess.badges.qr_scan_start = true;
					}}
					class="btn btn-sm preset-tonal-primary border border-primary-500"
				>
					<span class="fas fa-qrcode mx-1"></span>
					QR Scan
				</button>
			{:else if $events_sess.badges.show_form__scan}
				<button
					type="button"
					on:click={() => {
						$events_sess.badges.show_form__search = true;
						$events_sess.badges.show_form__search_results = false;
						$events_sess.badges.show_form__scan = false;
						$events_sess.badges.qr_scan_start = false;
					}}
					class="btn btn-sm preset-tonal-primary border border-primary-500"
				>
					<span class="fas fa-search mx-1"></span>
					Search
				</button>
			{/if}
		</div>
	</div>

	{#await load_obj_li_results}
		<span class="modal-loading">
			<span class="fas fa-spinner fa-spin"></span>
			<span class="loading-text"> Loading... </span>
		</span>
	{:then load_obj_li_results}
		{#if load_obj_li_results}
			<span class="fas fa-check text-green-500"></span>
			<span class="saved-text"> Loaded </span>
		{/if}
	{/await}

	{#if $events_sess.badges.show_form__search}
		{#if $events_slct?.badge_obj_li.length}
			<!-- {#if $event_badge_li} -->
			<section class="ae_h_scrollfix">
				<h2 class="h3">Results:</h2>
				<table class="table">
					<thead>
						<tr>
							<th>Badge</th>
							<!-- The email should only be the first 3 chars and then @domain name. -->
							<th>Email / Affiliations / Location</th>
							<!-- <th>Affiliations / Location</th> -->
							<th>Badge Type</th>
						</tr>
					</thead>
					<tbody>
						{#each $events_slct.badge_obj_li as badge_obj}
							<!-- {#each $lq__event_badge_li as badge_obj} -->
							<tr
								class:hidden={(badge_obj.print_count >= 1 || badge_obj.hide) &&
									!$ae_loc.trusted_access}
								class:fade_50={(badge_obj.print_count >= 1 || badge_obj.hide) &&
									$ae_loc.trusted_access}
							>
								<td class="">
									<button
										class="btn btn-lg text-xl preset-tonal-secondary border border-secondary-500 hover:preset-tonal-secondary w-96 overflow-hidden transition-all"
										on:click={() => {
											// Confirm they want to view the badge.
											if (
												badge_obj.print_count >= 1 &&
												!confirm(
													`That badge has already been printed ${badge_obj.print_count} times. View badge for ${badge_obj.full_name}?`
												)
											) {
												return;
											}
											// ae_util.handle_url_and_message('event_badge_id', badge_obj.event_badge_id_random);

											// Go to the badge view page
											// Example: /event/badge/view_badge?event_badge_id=THE_ID
											goto(
												`/event/badge/view_badge?event_badge_id=${badge_obj.event_badge_id_random}`,
												{ replaceState: true }
											);
										}}
									>
										<span class="flex flex-row justify-between items-center w-full">
											<span>
												{#if badge_obj.hide}
													<span class="fas fa-eye-slash mx-1"></span>
												{:else}
													<span class="fas fa-id-badge mx-1"></span>
												{/if}
												{#if badge_obj.print_count >= 1}
													<!-- Show a green checkmark -->
													<span class="fas fa-check text-green-500"></span>

													{#if $ae_loc.trusted_access}
														<span class="print_count preset-tonal-warning px-1"
															>{badge_obj.print_count}×</span
														>
													{/if}
												{/if}
											</span>

											<span class="font-bold">
												{#if badge_obj.full_name_override}
													{badge_obj.full_name_override}
												{:else if badge_obj.full_name}
													{badge_obj.full_name}
												{:else if badge_obj.given_name}
													{badge_obj.given_name} {badge_obj.family_name}
												{:else}
													-- no name --
												{/if}
											</span>
										</span>
									</button>
								</td>
								<td class="">
									<div class="">
										<div>
											<!-- The email should only be the first 3 chars and then @domain name. -->
											<!-- Example: original: scott.idem@oneskyit.com obscured: sco...@oneskyit.com -->
											<span class="fas fa-envelope mx-1"></span>
											{badge_obj.email ? badge_obj.email.replace(/^(.{3}).*@/, '$1...@') : ''}
										</div>

										<div>
											{#if badge_obj?.affiliations}
												<span class="fas fa-users mx-1"></span>
												{badge_obj.affiliations}
											{:else if badge_obj.location}
												<span class="fas fa-map-marker-alt mx-1"></span>
												{badge_obj.location}
											{:else if badge_obj.city && badge_obj.state_province}
												<span class="fas fa-map-marker-alt mx-1"></span>
												{badge_obj.city}, {badge_obj.state_province}
											{:else if badge_obj.city}
												<span class="fas fa-map-marker-alt mx-1"></span>
												{badge_obj.city}
											{:else if badge_obj.state_province}
												<span class="fas fa-map-marker-alt mx-1"></span>
												{badge_obj.state_province}
											{:else}
												-- none --
											{/if}
										</div>
									</div>
								</td>
								<td class="">
									<div class="flex flex-row items-center justify-between">
										<span title={badge_obj.registration_type}>{badge_obj.badge_type}</span>

										<div>
											<Element_ae_crud
												trigger_patch={ae_triggers.print_count}
												api_cfg={$ae_api}
												object_type={'event_badge'}
												object_id={badge_obj.event_badge_id_random}
												field_name={'print_count'}
												field_type={'text'}
												field_value={badge_obj.print_count}
												allow_null={false}
												hide_edit_btn={true}
												outline_element={false}
												show_crud={false}
												display_inline={true}
												class_li={'m-1'}
												on:ae_crud_updated={(e) => {
													console.log(`ae_crud_updated event:`, e.detail);
													// events_func.handle_load_ae_obj_id__badge({api_cfg: $ae_api, badge_id: $events_slct.badge_id});
												}}
											>
												<!-- {@html (badge_obj.print_count ? `<span class="fas fa-users m-1"></span> ${badge_obj.print_count}` : '<span class="fas fa-users m-1"></span> 0')} -->
												{#if $ae_loc.administrator_access}
													<span class="fas fa-print m-1"></span>
													<input
														type="number"
														min="0"
														max="10"
														step="1"
														bind:value={badge_obj.print_count}
														class="input text-sm w-16 m-1"
													/>
													<button
														type="button"
														on:click={() => {
															// badge_obj.print_count = 0;
															ae_triggers.print_count = true;
														}}
														class="btn btn-sm preset-tonal-warning"
													>
														<span class="fas fa-save m-1"></span>
														Save
													</button>
												{/if}
											</Element_ae_crud>

											<Element_ae_crud
												trigger_patch={ae_triggers.hide}
												api_cfg={$ae_api}
												object_type={'event_badge'}
												object_id={badge_obj?.event_badge_id_random}
												field_name={'hide'}
												field_type={'button'}
												field_value={badge_obj.hide}
												allow_null={false}
												hide_edit_btn={true}
												outline_element={false}
												show_crud={false}
												display_inline={true}
												class_li={'m-1'}
												on:ae_crud_updated={(e) => {
													console.log(`ae_crud_updated event:`, e.detail);
													// events_func.handle_load_ae_obj_id__badge({api_cfg: $ae_api, badge_id: badge_obj.badge_id_random});
												}}
											>
												<!-- {#if $ae_loc.trusted_access}
        {(badge_obj?.hide ? 'Hidden' : 'Not Hidden')}
        {/if} -->
												<button
													on:click={() => {
														// $events_slct.badge_obj = badge_obj;
														badge_obj.hide = !badge_obj?.hide;
														ae_triggers.hide = true;
													}}
													class="btn btn-sm preset-tonal-warning"
													class:hidden={!$ae_loc.trusted_access}
												>
													{#if $ae_loc.trusted_access}
														{@html badge_obj?.hide
															? '<span class="fas fa-eye m-1"></span> Unhide?'
															: '<span class="fas fa-eye-slash m-1"></span> Hide?'}
													{:else}
														<!-- Users see this as the "Archive" option button -->
														{@html badge_obj?.hide
															? '<span class="fas fa-archive m-1"></span> Unarchive'
															: '<span class="fas fa-archive m-1"></span> Archive'}
													{/if}
												</button>
											</Element_ae_crud>
										</div>
									</div>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</section>
		{:else}
			<div class="text-xl preset-filled-success-500 font-bold p-2">
				Type your name, email, or affiliations. Results will start to appear automatically.
			</div>

			{#if $events_sess.badges.fulltext_search_qry_str && $events_sess.badges.fulltext_search_qry_str.length > 5}
				<div class="text-xl preset-filled-warning-500 font-bold p-2">
					No badges found. Please change your search.
				</div>
			{/if}
		{/if}
	{:else if $events_sess.badges.show_form__scan}
		<div class="ae_quick_modal_container">
			<section
				class="
            ae_quick_popover_small
            events__badges__scan
            z-50
            flex
            flex-col
            gap-4
            justify-stretch

            "
			>
				<header class="popover__header flex gap-2 justify-between items-center p-1 border-b">
					<h2 class="h3">Scan</h2>

					<div class="popover__actions flex flex-row gap-2 items-center">
						<div>
							<button
								type="button"
								on:click={() => {
									console.log('Turn on iframe mode');
									$ae_loc.iframe = !$ae_loc.iframe;
								}}
								class="btn btn-sm preset-tonal w-48"
							>
								<span class="fas fa-compress mx-1"></span>
								Turn {$ae_loc.iframe ? 'off' : 'on'} iframe mode
							</button>
						</div>

						<button
							type="button"
							class="btn preset-tonal-primary"
							on:click={() => {
								$events_sess.badges.show_form__search = true;
								$events_sess.badges.show_form__search_results = false;
								$events_sess.badges.show_form__scan = false;
								$events_sess.badges.qr_scan_start = false;

								$events_slct.badge_id = null;
								$events_slct.badge_obj = null;
							}}
						>
							<span class="fas fa-times mx-1"></span>
							Close
						</button>
					</div>
				</header>

				<section class="popover__content grow flex flex-col gap-4 items-center ae_modal_scrollfix">
					<Element_qr_scanner
						start_qr_scanner={$events_sess.badges.qr_scan_start}
						show_qr_scan_result={true}
						show_qr_manual_badge_id_entry_option={true}
						on:qr_scan_result={handle_qr_scan_result}
						on:qr_camera={handle_qr_camera}
					/>

					<div class="qr_quick_results preset-tonal-secondary font-bold p-4">
						{@html $events_sess.badges.qr_scan_result ?? 'No results yet'}
					</div>

					{#if $events_slct.badge_id && $events_slct.badge_obj}
						<p>Badge ID: <strong>{$events_slct.badge_obj.event_badge_id_random}</strong></p>
					{/if}
				</section>
				<!-- .popover__content -->
			</section>
			<!-- .ae_quick_popover -->
		</div>
	{/if}

	<!-- {#if $ae_loc.ds.hub__page__events_badges__create_info}
{@html $ae_loc.ds.hub__page__events_badges__create_info}
{:else}
<section>
        <div class="alert alert-info">
            More information goes here.
        </div>
</section>
{/if} -->
</section>
