<script lang="ts">
/** @type {import('./$types').PageData} */
export let data: any;
// console.log(`ae_events_pres_mgmt event [slug] +page.svelte data:`, data);

import { onMount } from 'svelte';

import { clipboard } from '@skeletonlabs/skeleton';

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils';
import { api, send_email } from '$lib/api';
import Element_ae_crud from '$lib/element_ae_crud.svelte';
import Element_data_store from '$lib/element_data_store.svelte';

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

import { liveQuery } from "dexie";
import { core_func } from '$lib/ae_core_functions';
import { db_events } from "$lib/db_events";
import { ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { events_loc, events_sess, events_slct, events_trigger, events_trig_kv } from '$lib/ae_events_stores';
import { events_func } from '$lib/ae_events_functions';

import Form_agree from './form_agree.svelte';
import Presenter_view from './presenter_view.svelte';

// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
$slct.account_id = data.account_id;
// console.log(`$slct.account_id = `, $slct.account_id);
let ae_acct = data[$slct.account_id];
// console.log(`ae_acct = `, ae_acct);

$ae_loc.url_origin = data.url.origin;

$events_slct.event_id = ae_acct.slct.event_id;
$events_slct.event_obj = ae_acct.slct.event_obj;
$events_slct.event_session_id = ae_acct.slct.event_session_id;
$events_slct.event_session_obj = ae_acct.slct.event_session_obj;
$events_slct.event_presentation_id = null;
$events_slct.event_presentation_obj = null;
$events_slct.event_presentation_obj_li = ae_acct.slct.event_presentation_obj_li;
// $events_slct.event_file_obj_li = ae_acct.slct.event_file_obj_li;

if (!$events_loc.auth__person) {
    $events_loc.auth__person = {
        id: null,
        email: null,
        full_name: null,
        entered_key: null,
        entered_passcode: null,
    };
}

if (!$events_loc.auth__kv) {
    $events_loc.auth__kv = {
        session: {},
        presentation: {},
        presenter: {},
        person: {},
    };
}

if (!$events_loc.pres_mgmt) {
    $events_loc.pres_mgmt = {};
}

if (!$events_sess.pres_mgmt) {
    $events_sess.pres_mgmt = {};
    $events_sess.pres_mgmt.show_content__agree_text = null;
    $events_sess.pres_mgmt.show_content__presenter_start = null;
}

$events_sess.pres_mgmt.show_content__agree_text = false;
$events_sess.pres_mgmt.show_content__presenter_start = false;

// import Leads_add_scan from './leads_add_scan.svelte';
// import Sessions_list from './sessions_list.svelte';
// import Leads_manage from './leads_manage.svelte';
// import Leads_payment from './leads_payment.svelte';

// let param_slug_event_id = data.params.slug;

let event_obj = liveQuery(
    () => db_events.events.get($events_slct.event_id)
    // () => db_events.events.get(param_slug_event_id)
    // () => db_events.events.toArray()
    // () => db_events.events
    //     .where('id_random')
    //     .equals($events_slct.event_id)
    //     // .orderBy('name')
    //     // .offset(10).limit(5)
    //     .toArray()
);

let event_obj_v2 = db_events.events.get($events_slct.event_id);


let lq__event_session_obj = liveQuery(
    () => db_events.sessions.get($events_slct.event_session_id)
);

let lq__event_presentation_obj_li = liveQuery(
    () => db_events.presentations.where('event_session_id_random').equals($events_slct.event_session_id_random).toArray()
);

let lq__event_presentation_obj = liveQuery(
    () => db_events.presentations.get($events_slct.event_presentation_id)
);

let lq__event_presenter_obj = liveQuery(
    () => db_events.presenters.get($events_slct.event_presenter_id)
);

$events_slct.event_presenter_obj = $lq__event_presenter_obj;

let lq__event_file_obj_li = liveQuery(
    () => db_events.files.where('event_session_id_random').equals($events_slct.event_session_id).toArray()
);


$slct.person_obj_kv = {}; // This is intended for the POC lookup list when generated.

// Load the Event Obj with ID based on the slug param.
// $events_slct.event_id = param_slug_event_id;
// console.log('Selected Event ID:', $events_slct.event_id);
// $events_trigger = 'load__event_obj';

// let license_submit_results: Promise<any>|key_val;

// if (!$events_loc.leads.tab) {
//     $events_loc.leads.tab = {};
//     $events_loc.leads.tab[$events_slct.event_id] = 'start';
// }

// if (!$events_loc.leads.auth_exhibit_kv) {
//     $events_loc.leads.auth_exhibit_kv = {};
// }

// if ($events_loc.leads.auth_exhibit_kv && $events_loc.leads.auth_exhibit_kv[$events_slct.event_id]) {
//     console.log('Logged in using shared exhibit staff passcode.');

//     if ($events_loc.leads.auth_exhibit_kv[$events_slct.event_id].key) {
//         console.log(`Using the license key: ${$events_loc.leads.auth_exhibit_kv[$events_slct.event_id].key}`);
//     } else {
//         console.log('License key (email) not used.');
//         $events_loc.leads.tab[$events_slct.event_id] = 'start';
//     }
// } else {
//     console.log('Not logged in using shared exhibit staff passcode.');
//     $events_loc.leads.tab[$events_slct.event_id] = 'start';
// }


onMount(() => {
    console.log('Events Session [slug]: +page.svelte');

    // console.log(`ae_events_pres_mgmt presenter [slug] +page.svelte data:`, data);

    // if (!$events_slct.event_id) {
    //     console.log(`No ID! Nothing to show. Try setting the ID again.`);
    //     $events_slct.event_id = $events_slct.event_id;
    // }
    // if (!$events_slct.event_session_id) {
    //     console.log(`No Session ID! Nothing to show. Try setting the Session ID again.`);
    //     $events_slct.event_session_id = $events_slct.event_session_id;
    // }

    let url_person_id = data.url.searchParams.get('person_id');
    let url_person_pass = data.url.searchParams.get('person_pass');
    let url_presentation_id = data.url.searchParams.get('presentation_id');
    let url_presenter_id = data.url.searchParams.get('presenter_id');
    let url_session_id = data.url.searchParams.get('session_id');

    // This should be turned into a function to correctly authenticate the person and allow them access to their presentations and presenter details.
    if (url_person_pass) {
        console.log(`ae_events_pres_mgmt session [slug] +page.svelte: event_session_id=${$events_slct.session_id}; person_id=${url_person_id}; person_pass=${url_person_pass}; presentation_id=${url_presentation_id}; presenter_id=${url_presenter_id}`);

        // Using temporary session values first.
        $events_sess.auth__entered_key = url_person_id;
        $events_sess.auth__entered_passcode = url_person_pass;

        $events_sess.auth__person.id = url_person_id;
        $events_sess.auth__person.presentation_id = url_presentation_id;
        $events_sess.auth__person.presenter_id = url_presenter_id;
        $events_sess.auth__person.session_id = url_session_id; // For POC or LCI Champions for sessions. Do not set for a presenter!

        $events_sess.auth__kv.person[url_person_id] = true;
        $events_sess.auth__kv.session[$events_slct.event_session_id] = true; // For POC or LCI Champions for sessions. Do not set for a presenter!
        $events_sess.auth__kv.presentation[url_presentation_id] = true;
        $events_sess.auth__kv.presenter[url_presenter_id] = true;

        // We need to set the selected presentation and presenter objects based on the respective IDs.
        if (url_presentation_id && url_presenter_id) {
            $events_slct.event_presentation_id = url_presentation_id;
            $events_slct.event_presenter_id = url_presenter_id;
        }

        //     // We need to load the presentation and presenter objects based on the IDs.
        //     if ($events_slct.event_presentation_obj_li && $events_slct.event_presentation_obj_li.length > 0) {
        //         let event_presentation_obj = $events_slct.event_presentation_obj_li.find((obj) => obj.event_presentation_id_random == url_presentation_id);
        //         $events_slct.presentation_obj = event_presentation_obj;
        //         if (event_presentation_obj.event_presenter_li && event_presentation_obj.event_presenter_li.length > 0) {
        //             let event_presenter_obj = event_presentation_obj.event_presenter_li.find((obj) => obj.event_presenter_id_random == url_presenter_id);
        //             $events_slct.presenter_obj = event_presenter_obj;

        //         }
        //     }

        //     // events_func.handle_load_ae_obj_id__presentation({api_cfg: $ae_api, presentation_id: url_presentation_id});
        // }


        // console.log('Remove the passcode from the URL.');
        // data.url.searchParams.delete('person_id');
        // data.url.searchParams.delete('person_pass');

        // let new_url = data.url.toString()
        // console.log(new_url);
        // goto(new_url, {replaceState: true});
        if (url_presenter_id) {
            presenter_sign_in();
        }

        if (url_session_id) {
            session_sign_in();
        }
    }

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

function presenter_sign_in() {
    console.log('Presenter sign in with URL values');

    $ae_loc.authenticated_access = true;
    $ae_loc.access_type = 'authenticated';

    $events_loc.auth__person.id = $events_sess.auth__entered_key; // person_id
    $events_loc.auth__person.entered_key = $events_sess.auth__entered_key; // also person_id in this case
    $events_loc.auth__person.email = 'test@example.com';
    $events_loc.auth__person.full_name = 'Test Person';

    $events_loc.auth__kv.person[$events_sess.entered_key] = true;
    $events_loc.auth__kv.session[$events_slct.event_session_id] = false; // Set to false for presenters.
    $events_loc.auth__kv.presentation[$events_sess.auth__person.presentation_id] = true;
    $events_loc.auth__kv.presenter[$events_sess.auth__person.presenter_id] = true;

    // Setting again here... just because for now.
    $events_slct.event_presentation_id = $events_sess.auth__person.presentation_id;
    $events_slct.event_presenter_id = $events_sess.auth__person.presenter_id;
}

function session_sign_in() {
    console.log('Session sign in with URL values');

    $ae_loc.authenticated_access = true;
    $ae_loc.access_type = 'authenticated';

    $events_loc.auth__person.id = $events_sess.auth__entered_key; // person_id
    $events_loc.auth__person.entered_key = $events_sess.auth__entered_key; // also person_id in this case
    $events_loc.auth__person.email = 'test@example.com';
    $events_loc.auth__person.full_name = 'Test Person';

    $events_loc.auth__kv.person[$events_sess.entered_key] = true;
    $events_loc.auth__kv.session[$events_slct.event_session_id] = true;
    $events_loc.auth__kv.presentation[$events_sess.auth__person.presentation_id] = false; // Set to false for session POC (LCI Champions).
    $events_loc.auth__kv.presenter[$events_sess.auth__person.presenter_id] = false; // Set to false for session POC (LCI Champions).

    // Setting again here... just because for now.
    // $events_slct.event_presentation_id = $events_sess.auth__person.presentation_id;
    // $events_slct.event_presenter_id = $events_sess.auth__person.presenter_id;
}

function sign_out() {
    $ae_loc.authenticated_access = false;
    $ae_loc.access_type = 'anonymous';

    $events_loc.auth__person = {
        id: null,
        email: null,
        full_name: null,
        entered_key: null,
        entered_passcode: null,
    };
    $events_loc.auth__kv = {
        session: {},
        presentation: {},
        presenter: {},
        person: {},
    };
}

$: if ($slct_trigger == 'load__event_file_obj_li') {
    console.log(`load__event_file_obj_li event_session_id=${$slct.account_id}`);

    $slct_trigger = null;

    events_func.handle_load_ae_obj_li__event_file({
        api_cfg: $ae_api,
        event_session_id: $events_slct.event_session_id,
        try_cache: false
    });
}

$: if ($slct_trigger == 'load__event_presenter_obj_li') {
    console.log(`load__event_presenter_obj_li event_session_id=${$slct.account_id}`);

    $slct_trigger = null;

    events_func.handle_load_ae_obj_li__event_presenter({
        api_cfg: $ae_api,
        event_presentation_id: $events_slct.event_presentation_id,
        try_cache: false
    });
}


function send_init_confirm_email(
        {
            to_email,
            to_name,
            person_id,
            person_passcode,
            presentation_id,
            presenter_id,
            presentation_name
        }: {
            to_email: string,
            to_name: string,
            person_id: string,
            person_passcode: string,
            presentation_id: string,
            presenter_id: string,
            presentation_name: string
        }
        ) {
    console.log(`*** send_init_confirm_email() *** to ${to_email}.`);

    // to_email = 'test+agree@oneskyit.com';

    let sign_in_url = encodeURI(`${data.url.origin}/events_pres_mgmt/session/${$events_slct.event_session_id}?person_id=${person_id}&person_pass=${person_passcode}&presentation_id=${presentation_id}&presenter_id=${presenter_id}`)

    let subject = `LCI Congress 2024 - Pres Mgmt Hub Sign In Link for ${$lq__event_session_obj?.name} (ID: ${$events_slct.event_session_id})`;

    let body_html = `
    <div>${to_name},
    <p>Your link to sign into the presentation management hub for LCI Congress 2024 is below. If you did not request this, please delete and ignore this email. If you need to make any changes or updates to your submission, you may use this link again later.</p>
    </div>

    <div>
    <strong>26th Annual Lean Construction Congress (2024)</strong>:<br>
    <p>
    Session Name: ${$lq__event_session_obj?.name}<br>
    Session ID: ${$lq__event_session_obj?.event_session_id_random}<br>
    Presentation Name: ${presentation_name}<br>
    Presentation ID: ${presentation_id}
    </p>
    <p>Use this link to view or update your LCI 2024 presentation information.<br>
    Copy and paste link: <a href="${sign_in_url}">${sign_in_url}</a></p>
    </div>`;

    api.send_email({
        api_cfg: $ae_api,
        from_email: 'noreply+agree@oneskyit.com',
        from_name: 'LCI 2024 Pres Mgmt Hub',
        to_email: to_email,
        subject: subject,
        body_html: body_html,
    });
}


function send_sign_in_poc_email(
        {
            to_email,
            to_name,
            person_id,
            person_passcode,
            session_id,
        }: {
            to_email: string,
            to_name: string,
            person_id: string,
            person_passcode: string,
            session_id: string,
        }
        ) {
    console.log(`*** send_sign_in_poc_email() *** to ${to_email}.`);

    // to_email = 'test+agree@oneskyit.com';

    let sign_in_url = encodeURI(`${data.url.origin}/events_pres_mgmt/session/${$events_slct.event_session_id}?person_id=${person_id}&person_pass=${person_passcode}&session_id=${session_id}`);

    let subject = `LCI Congress 2024 - Pres Mgmt Hub Sign In Link for ${$lq__event_session_obj?.name} (ID: ${$events_slct.event_session_id})`;

    let body_html = `
    <div>${to_name},
    <p>Your link to sign into the presentation management hub as a session Champion for LCI Congress 2024 is below. If you did not request this, please delete and ignore this email. If you need to make any changes or updates to your submission, you may use this link again later.</p>
    </div>

    <div>
    <strong>26th Annual Lean Construction Congress (2024)</strong>:<br>
    <p>
    Session Name: ${$lq__event_session_obj?.name}<br>
    Session ID: ${$lq__event_session_obj?.event_session_id_random}
    </p>
    <p>Use this link to view or update your LCI 2024 session information.<br>
    Copy and paste link: <a href="${sign_in_url}">${sign_in_url}</a></p>
    </div>`;
    api.send_email({
        api_cfg: $ae_api,
        from_email: 'noreply+agree@oneskyit.com',
        from_name: 'LCI 2024 Pres Mgmt Hub',
        to_email: to_email,
        subject: subject,
        body_html: body_html,
    });
}

</script>


<section
    class="ae_events_pres_mgmt_event_session md:container h-full mx-auto flex flex-col space-y-4 pt-0 pb-8"
    >

<div class="pres_mgmt__session_help flex flex-col items-center space-y-2">
<div>
<button
    type="button"
    on:click={() => {
        $events_loc.pres_mgmt.show_content__session_help = !$events_loc.pres_mgmt.show_content__session_help;
    }}
    class="btn btn-sm m-1 variant-soft-tertiary text-info-300 hover:text-info-800"
    title="Help and information about the session"
    >
    <span class="fas fa-question-circle mx-1"></span>
    {#if $events_loc.pres_mgmt.show_content__session_help}
        Hide
    {:else}
        Show
    {/if}
    Help
</button>
</div>

<Element_data_store
    ds_code="events__pres_mgmt__session_help"
    ds_name="Default: Events - Pres Mgmt Session Help"
    ds_type="html"
    for_type="event"
    for_id={$events_slct.event_id}
    class_li="bg-yellow-100 p-2 rounded-md border border-yellow-200"
    show_edit={false}
    show_edit_btn={true}
    hide={!$events_loc.pres_mgmt.show_content__session_help}
    />
</div>

{#if $events_slct.event_session_id && $lq__event_session_obj}

<h2 class="h2 text-center">{$lq__event_session_obj?.name ?? '-- not set --'}</h2>

<!-- Information about the session -->
<section>

<ul
    class="space-y-2 px-4"
    >
    <li>
        <Element_ae_crud
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$lq__event_session_obj?.event_session_id_random}
            field_name={'name'}
            field_type={'text'}
            field_value={$lq__event_session_obj?.name}
            allow_null={false}
            hide_edit_btn={!$ae_loc.trusted_access}
            outline_element={false}
            show_crud={false}
            display_inline={true}
            display_block_edit={true}
            class_li={''}
            on:ae_crud_updated={e => {
                console.log(`ae_crud_updated:`, e.detail);

                events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $lq__event_session_obj?.event_session_id_random, log_lvl: 1})
                .then(function (load_results) {
                });
            }}
            >
            <strong class="text-sm">Name/Title:</strong> {$lq__event_session_obj.name}
        </Element_ae_crud>

        <Element_ae_crud
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$lq__event_session_obj?.event_session_id_random}
            field_name={'code'}
            field_type={'text'}
            field_value={$lq__event_session_obj?.code}
            allow_null={false}
            hide_edit_btn={!$ae_loc.trusted_access}
            outline_element={false}
            show_crud={false}
            display_inline={true}
            display_block_edit={false}
            class_li={''}
            on:ae_crud_updated={e => {
                console.log(`ae_crud_updated:`, e.detail);

                events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $lq__event_session_obj?.event_session_id_random, log_lvl: 1})
                .then(function (load_results) {
                });
            }}
            >
            <span class="text-sm text-gray-500 bg-yellow-100 p-1 rounded-md border border-yellow-200"
                title="Session code {$lq__event_session_obj.code}"
                >
                <strong class="text-sm">code:</strong>
                <span class="fas fa-barcode"></span>
                {$lq__event_session_obj.code}
            </span>
        </Element_ae_crud>
    </li>
    <li>
        <strong class="text-sm">Date time:</strong>
        <Element_ae_crud
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$lq__event_session_obj?.event_session_id_random}
            field_name={'start_datetime'}
            field_type={'datetime'}
            field_value={$lq__event_session_obj.start_datetime}
            allow_null={false}
            hide_edit_btn={!$ae_loc.trusted_access}
            outline_element={false}
            show_crud={false}
            display_inline={true}
            class_li={''}
            on:ae_crud_updated={e => {
                console.log(`ae_crud_updated:`, e.detail);

                events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $lq__event_session_obj?.event_session_id_random});
                // $events_trigger = 'load__event_session_obj_id';
                // $events_trig_kv['event_session_id'] = $lq__event_session_obj?.event_session_id_random;
            }}
            >
            {ae_util.iso_datetime_formatter($lq__event_session_obj.start_datetime, 'dddd')},
            {ae_util.iso_datetime_formatter($lq__event_session_obj.start_datetime, 'datetime_long')}
        </Element_ae_crud>
        -
        <Element_ae_crud
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$lq__event_session_obj?.event_session_id_random}
            field_name={'end_datetime'}
            field_type={'datetime'}
            field_value={$lq__event_session_obj.end_datetime}
            allow_null={false}
            hide_edit_btn={!$ae_loc.trusted_access}
            outline_element={false}
            show_crud={false}
            display_inline={true}
            class_li={''}
            on:ae_crud_updated={e => {
                console.log(`ae_crud_updated:`, e.detail);

                events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $lq__event_session_obj?.event_session_id_random});
                // $events_trigger = 'load__event_session_obj_id';
                // $events_trig_kv['event_session_id'] = $lq__event_session_obj?.event_session_id_random;
            }}
            >
            {ae_util.iso_datetime_formatter($lq__event_session_obj.end_datetime, 'time_short')}
        </Element_ae_crud>
    </li>
    <li>
        <strong class="text-sm">Location/Room:</strong> {$lq__event_session_obj.event_location_name ? $lq__event_session_obj.event_location_name : '-- not set --'}

        {#if $ae_loc.trusted_access}
        <Element_ae_crud
            trigger_patch={ae_triggers.update_event_location}
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$lq__event_session_obj?.event_session_id_random}
            field_name={'event_location_id_random'}
            field_type={'select'}
            field_value={ae_tmp.event_location_id}
            select_option_li={$slct.event_location_obj_kv}
            allow_null={$ae_loc.administrator_access}
            hide_edit_btn={true}
            outline_element={false}
            show_crud={ae_tmp.show__edit_event_location}
            display_inline={true}
            class_li={'m-1'}
            on:ae_crud_updated={e => {
                console.log(`ae_crud_updated:`, e.detail);

                events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $lq__event_session_obj?.event_session_id_random, log_lvl: 1})
                .then(function (load_results) {
                    ae_tmp.event_location_id = null;
                    ae_tmp.show__edit_event_location = false;

                    // Maybe reload page?
                    // window.location.reload();
                });
            }}
            >
            {#if ae_tmp?.show__edit_location}

                {#await $slct.event_location_obj_li}
                    <span class="fas fa-spinner fa-spin mx-1"></span>
                {:then event_location_obj_li}
                <!-- {#if  event_location_obj_li && event_location_obj_li.length > 0}

                {/if} -->
                {/await}

                <button
                    type="button"
                    on:click={() => {
                        console.log('Cancel editing the location for the session.');

                        ae_tmp.event_location_id = null;
                        ae_tmp.show__edit_event_location = false;
                    }}
                    class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                    >
                    <span class="fas fa-times mx-1"></span>
                    Cancel
                </button>

            {:else}
                <button
                    type="button"
                    on:click={() => {
                        console.log('Edit the location for the session.');

                        let params = {
                            qry__limit: 50,
                        }

                        // $slct.event_location_obj_li = await core_func.handle_load_ae_obj_li__event_location({api_cfg: $ae_api, account_id: $slct.account_id, params: params});

                        $slct.event_location_obj_li = events_func.handle_load_ae_obj_li__event_location({api_cfg: $ae_api, event_id: $slct.event_id, params: params, log_lvl: 1})
                        .then(function (load_results) {
                            console.log(`Loaded event_location_obj_li:`, load_results);

                            // We need to make this ready for the select option list. Convert the list to a key value pair with the event_location_id_random as the key. We also need to set the option text value to: name (room)
                            if (load_results) {
                                let event_location_obj_li = load_results;
                                let event_location_obj_kv = {};
                                event_location_obj_kv[''] = '-- Select a location --';
                                event_location_obj_li.forEach((event_location_obj) => {
                                    let option_text = `${event_location_obj.name} (${event_location_obj.code})`;
                                    event_location_obj_kv[event_location_obj.event_location_id_random] = option_text;
                                });
                                $slct.event_location_obj_kv = event_location_obj_kv;
                            }
                            // $slct.event_location_obj_kv = $slct.event_location_obj_kv;
                            console.log(`$slct.event_location_obj_kv = `, $slct.event_location_obj_kv);

                            return load_results;
                        })
                        .finally(function () {
                            console.log(`Finally...`);
                            ae_tmp.event_location_id = $lq__event_session_obj?.event_location_id_random;
                            ae_tmp.show__edit_event_location = true;
                        });
                    }}
                    class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                    >
                    <span class="fas fa-edit mx-1"></span>
                    Edit
                </button>

            {/if}



        </Element_ae_crud>
        {/if}
    </li>
    <li>
        <strong class="text-sm">Moderator/Champion:</strong>
        <span title={$lq__event_session_obj?.poc_person_id_random}>
            {$lq__event_session_obj.poc_person_full_name ? $lq__event_session_obj.poc_person_full_name : '-- not set --'}
        </span>

        {#if $ae_loc.trusted_access}
        <Element_ae_crud
            trigger_patch={ae_triggers.update_person_poc}
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$lq__event_session_obj?.event_session_id_random}
            field_name={'poc_person_id_random'}
            field_type={'select'}
            field_value={ae_tmp.poc_person_id}
            select_option_li={$slct.person_obj_kv}
            allow_null={$ae_loc.administrator_access}
            hide_edit_btn={true}
            outline_element={false}
            show_crud={ae_tmp.show__edit_poc_person}
            display_inline={true}
            class_li={'m-1'}
            on:ae_crud_updated={e => {
                console.log(`ae_crud_updated:`, e.detail);

                events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $lq__event_session_obj?.event_session_id_random, log_lvl: 1})
                .then(function (load_results) {
                    ae_tmp.poc_person_id = null;
                    ae_tmp.show__edit_poc_person = false;

                    // Maybe reload page?
                    // window.location.reload();
                });
            }}
            >
            {#if ae_tmp?.show__edit_poc_person}

            {#await $slct.person_obj_li}
                <span class="fas fa-spinner fa-spin mx-1"></span>
            {:then person_obj_li}
            {#if  person_obj_li && person_obj_li.length > 0}
                <!-- <label class="text-sm">PoC:
                <select
                    bind:value={ae_tmp.poc_person_id}
                    class="select min-w-fit max-w-md text-sm"
                    >
                <option value="">-- Select a person --</option>
                {#each person_obj_li as person_obj}
                    <option
                        value={person_obj.person_id_random}
                        selected={person_obj.person_id_random == $lq__event_session_obj?.poc_person_id_random}
                        >
                        {person_obj.full_name}
                        ({person_obj.primary_email})
                    </option>
                {/each}
                </select>
                </label>

                <button
                    type="button"
                    disabled={ae_tmp.poc_person_id == $lq__event_session_obj?.poc_person_id_random}
                    on:click={() => {
                        console.log('Save the POC person for the session.');

                        let person_id = ae_tmp.poc_person_id;
                        console.log('Selected person ID:', person_id);

                        ae_triggers.update_person_poc = true;
                    }}
                    class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                    >
                    <span class="fas fa-save mx-1"></span>
                    Save
                </button> -->
            {/if}
            {/await}

            {/if}

            {#if ae_tmp.show__edit_poc_person}
            <button
                type="button"
                on:click={() => {
                    console.log('Cancel the POC person for the session.');

                    ae_tmp.poc_person_id = null;
                    ae_tmp.show__edit_poc_person = false;
                }}
                class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                >
                <span class="fas fa-times mx-1"></span>
                Cancel
            </button>
            {:else}
            <button
                type="button"
                on:click={async () => {
                    console.log('Edit the POC person for the session.');

                    let params = {
                        qry__limit: 300,
                    }

                    // $slct.person_obj_li = await core_func.handle_load_ae_obj_li__person({api_cfg: $ae_api, account_id: $slct.account_id, params: params});

                    $slct.person_obj_li = core_func.handle_load_ae_obj_li__person({api_cfg: $ae_api, account_id: $slct.account_id, params: params})
                    .then(function (load_results) {
                        console.log(`Loaded person_obj_li:`, load_results);

                        // We need to make this ready for the select option list. Convert the list to a key value pair with the person_id_random as the key. We also need to set the option text value to: full_name (primary_email)
                        if (load_results) {
                            let person_obj_li = load_results;
                            let person_obj_kv = {};
                            person_obj_kv[''] = '-- Select a person --';
                            person_obj_li.forEach((person_obj) => {
                                let option_text = `${person_obj.full_name} (${person_obj.primary_email})`;
                                person_obj_kv[person_obj.person_id_random] = option_text;
                            });
                            $slct.person_obj_kv = person_obj_kv;
                        }
                        $slct.person_obj_kv = $slct.person_obj_kv;
                        console.log(`$slct.person_obj_kv = `, $slct.person_obj_kv);

                        return load_results;
                    });

                    ae_tmp.poc_person_id = $lq__event_session_obj?.poc_person_id_random;
                    ae_tmp.show__edit_poc_person = true;
                }}
                class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                >
                <span class="fas fa-edit mx-1"></span>
                Edit
            </button>
            {/if}
        </Element_ae_crud>
        {/if}

        <span class="float-right">
        {#if $events_loc.auth__kv.session[$events_slct.event_session_id]}
            <span class="text-green-500">POC Signed In</span>
        {/if}
        {#if $ae_loc.trusted_access || !$events_loc.auth__person.id }

            <button
                type="button"
                on:click={() => {
                    console.log('Email the access link');
                    if (!$lq__event_session_obj.poc_person_primary_email) {
                        alert('No email address found for this presenter.');
                        return;
                    }
                    if (confirm(`This will send the sign in email to ${$lq__event_session_obj.poc_person_primary_email}`)) {
                        console.log('Send the email to the presenter.');
                    } else {
                        console.log('Cancelled sending the email.');
                        return false;
                    }

                    send_sign_in_poc_email(
                        {
                            to_email: $lq__event_session_obj.poc_person_primary_email,
                            to_name: $lq__event_session_obj.poc_person_full_name,
                            person_id: $lq__event_session_obj.poc_person_id_random,
                            person_passcode: $lq__event_session_obj.poc_person_passcode,
                            session_id: $lq__event_session_obj.event_session_id_random,
                        }
                    );
                }}
                class="btn btn-sm variant-ghost-primary hover:variant-filled-primary"
                title="Email the access link to the POC (moderator/champion)"
                >
                <span class="fas fa-envelope mx-1"></span>
                Email Access Link
            </button>

        {/if}

        {#if $ae_loc.trusted_access}
            <!-- A button to copy the access link to the clipboard. -->
            <!-- Example: /events_pres_mgmt/session/Wh8UnJlbIA0?person_id=fV1dl_IJ0yY&person_pass=abc123 -->
            <button
                type="button"
                use:clipboard={encodeURI(`${$ae_loc.url_origin}/events_pres_mgmt/session/${$events_slct.event_session_id}?person_id=${$lq__event_session_obj.poc_person_id_random}&person_pass=${$lq__event_session_obj.poc_person_passcode}&session_id=${$lq__event_session_obj.event_session_id_random}`)}
                class="btn btn-sm variant-ghost-warning m-1"
                title="Copy the POC (moderator/champion) access link to the clipboard."
                >
                <span class="fas fa-copy mx-1"></span>
                Copy Access Link
            </button>
        {/if}
        </span>

    </li>

    {#if $ae_loc.administrator_access}
    <li>
        <strong class="text-sm">Session passcode:</strong> {$lq__event_session_obj.passcode ? $lq__event_session_obj.passcode : '-- not set --'}
    </li>
    {/if}

    <li>
    <div>
    <Element_ae_crud
        api_cfg={$ae_api}
        object_type={'event_session'}
        object_id={$lq__event_session_obj?.event_session_id_random}
        field_name={'description'}
        field_type={'textarea'}
        field_value={$lq__event_session_obj.description}
        allow_null={false}
        hide_edit_btn={!$ae_loc.trusted_access}
        outline_element={false}
        show_crud={false}
        display_inline={true}
        display_block_edit={true}
        textarea_rows={15}
        class_li={''}
        on:ae_crud_updated={e => {
            console.log(`ae_crud_updated:`, e.detail);

            events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $lq__event_session_obj?.event_session_id_random, log_lvl: 1});
        }}
        >
        <strong class="text-sm">
        Session description:
        </strong>

        <button
            type="button"
            on:click={() => {
                console.log('Show/Hide Description');
                $events_loc.pres_mgmt.show_content__session_description = !$events_loc.pres_mgmt.show_content__session_description;
            }}
            class="btn btn-sm variant-soft-surface hover:variant-filled-surface text-xs"
            >
            {#if $events_loc.pres_mgmt.show_content__session_description}
                <span class="fas fa-eye-slash mx-1"></span>
                <span>Hide Description</span>
            {:else}
                <span class="fas fa-eye mx-1"></span>
                <span>Show</span>
            {/if}
        </button>

        <pre
            class="whitespace-pre-wrap p-2 bg-gray-100 rounded-md"
            class:hidden={!$events_loc.pres_mgmt.show_content__session_description}
            >{$lq__event_session_obj.description}</pre>
    </Element_ae_crud>
    </div>
    </li>

</ul>

<!-- <label
    class="text-sm"
    >Session description:
<textarea
    class="textarea my-1 p-2"
    cols="30"
    rows="4"
    disabled
    >{$lq__event_session_obj.description}</textarea>
</label> -->

<div class="m-1 flex flex-col flex-wrap gap-1 items-center">
{#if $ae_loc.trusted_access || $events_loc.auth__person.id }

    {#if $events_loc.auth__kv.session[$events_slct.event_session_id]}
    <h3 class="h3">Welcome {$lq__event_session_obj?.poc_person_full_name ?? 'Session POC'}</h3>
    {:else}
    <h3 class="h3">Welcome {$lq__event_presenter_obj?.full_name ?? 'Presenter'}</h3>
    {/if}

    {#if $ae_loc.trusted_access || $events_loc.auth__kv.session[$events_slct.event_session_id] || ($events_loc.auth__kv.presenter[$events_slct.event_presenter_id] &&  $lq__event_presenter_obj?.agree)}

    <div class="min-w-max flex flex-col gap-1">
    <a
        class="btn btn-md variant-ghost-primary hover:variant-filled-primary flex flex-row items-center justify-between min-w-full"
        href="https://static.oneskyit.com/c/LCI/files/LCI_Congress_Template_2024.pptx"
        >
        <span class="fas fa-download mx-1"></span>
        <span class="text-center grow">
        Download
        LCI Congress Template 2024 (PowerPoint)
        </span>
    </a>
    <a
        class="btn btn-md variant-ghost-primary hover:variant-filled-primary flex flex-row items-center justify-between min-w-full"
        href="https://static.oneskyit.com/c/LCI/files/LCI_Speaker_and_Champion_Congress_Task_List_2024.xlsx"
        >
        <span class="fas fa-download mx-1"></span>
        Download
        LCI Speaker and Champion Congress Task List (Excel)
    </a>
    </div>

    {:else}
    <span class="text-lg text-red-500 font-bold text-center p-1 m-1 border border-red-200 rounded-md bg-red-100 space-y-2">
        <p><strong>Read and Consent Agreement?</strong></p>

        <p>Please select your name below to view, read, and consent the agreement.</p>

        <p>You will be able to download the LCI Congress Template 2024 (PowerPoint) and LCI Speaker and Champion Congress Task List (Excel) after you have read and consented to the agreement.</p>
        </span>
    {/if}

    {#if $events_loc.auth__person?.id}
    <button
        type="button"
        class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
        on:click={() => {
            sign_out();
            alert('You have been signed out.');
        }}
        >
        <span class="fas fa-times mx-1"></span>
        Sign Out (Clear Session)
    </button>
    {/if}

{:else}
    <div
        class="text-xl text-red-500 font-bold text-center p-1 m-1 border border-red-200 rounded-md bg-red-100"
        >
        <p><strong>Restricted access!</strong></p>
        <p>
            Please select your name below to email the access link.
            The email address associated with your LCI member record will be used.
            The email address is not shown below for safety reasons.
            <!-- This email address must match your LCI member record. -->
        </p>
    </div>

    {#if ($events_sess.auth__person.presenter_id) || ($events_sess.auth__person.session_id)}
    <div
        class="border border-gray-200 p-2 rounded-md m-2 text-center space-y-2"
        >
        <div
            class="text-sm text-gray-500"
            >
            Use the link that was sent to your email address to sign in or enter your key and passcode to sign in.
        </div>
        <div>
        <input
            type="text"
            class="input max-w-36"
            placeholder="Key"
            value={$events_sess.auth__entered_key ?? ''}
            on:input={(e) => $events_sess.auth__entered_key = e.target.value}
            >
        <input
            type="text"
            class="input max-w-36"
            placeholder="Passcode"
            value={$events_sess.auth__entered_passcode ?? ''}
            on:input={(e) => $events_sess.auth__entered_passcode = e.target.value}
            >
        <button
            class="btn btn-md variant-ghost-primary"
            on:click={() => {
                console.log('Sign in with URL values');

                if ($events_sess.auth__person.presenter_id) {
                    presenter_sign_in();
                } else if ($events_sess.auth__person.session_id) {
                    session_sign_in();
                }

                // This needs to be moved to a function!

                // $events_loc.auth__person.id = $events_sess.auth__entered_key; // person_id
                // $events_loc.auth__person.entered_key = $events_sess.auth__entered_key; // also person_id in this case
                // $events_loc.auth__person.email = 'test@example.com';
                // $events_loc.auth__person.full_name = 'Test Person';

                // $events_loc.auth__kv.person[$events_sess.entered_key] = true;
                // $events_loc.auth__kv.session[$events_slct.event_session_id] = true;
                // $events_loc.auth__kv.presentation[$events_sess.auth__person.presentation_id] = true;
                // $events_loc.auth__kv.presenter[$events_sess.auth__person.presenter_id] = true;

                // Setting again here... just because for now.
                // $events_slct.event_presentation_id = $events_sess.auth__person.presentation_id;
                // $events_slct.event_presenter_id = $events_sess.auth__person.presenter_id;
            }}
            >
            <span class="fas fa-sign-in-alt mx-1"></span>
            Sign In
        </button>
        </div>

        <div
            class="text-sm text-gray-500"
            >
            For:
            session: {$events_sess.auth__person.session_id}
            presentation: {$events_sess.auth__person.presentation_id}
            presenter: {$events_sess.auth__person.presenter_id}
            <br>

            {$lq__event_presentation_obj?.name ? `Name: "${$lq__event_presentation_obj.name}"` : '-- not set --'}
        </div>


        {#if $events_loc.auth__person?.id}
            <button
                type="button"
                class="btn btn-sm variant-soft-warning"
                on:click={() => {
                    sign_out();
                    alert('You have been signed out.');
                }}
                >
                <span class="fas fa-times mx-1"></span>
                Sign Out
            </button>
        {/if}
    </div>
    {/if}

{/if}
</div>

</section>


<!-- Presentations in the session -->
<section>

<div class="float-right space-2 flex flex-row items-center">
{#if $ae_loc.trusted_access }
<button
    type="button"
    on:click={() => {
        console.log('Add Presentation');

        let presentation_data = {
            event_id_random: $events_slct.event_id,
            event_session_id_random: $events_slct.event_session_id,
            name: 'New Presentation',
            code: 'new_presentation',
            enable: true,
        }

        events_func.handle_create_ae_obj__event_presentation({
            api_cfg: $ae_api,
            event_id: $events_slct.event_id,
            event_session_id: $events_slct.event_session_id,
            data_kv: presentation_data,
            log_lvl: 1,
        })
    }}
    class="btn btn-sm variant-soft-warning hover:variant-filled-warning"
    >
    <span class="fas fa-plus mx-1"></span>
    Add Presentation
</button>
{/if}
</div>

<h3 class="h3">Presentations:</h3>
{#await $events_slct.event_presentation_obj_li}
    <p>Loading...</p>
{:then event_presentation_obj_li}
    {#if event_presentation_obj_li && event_presentation_obj_li.length > 0}
        <ul
            class="space-y-4 p-4 m-2 bg-gray-100 rounded-md"
            >
        {#each event_presentation_obj_li as event_presentation_obj}
            <li
                class="space-y-2 border border-gray-200 p-2 rounded-md"
                >

            <div class="float-right space-2 flex flex-row items-center">
            {#if $ae_loc.trusted_access }
            <button
                type="button"
                on:click={() => {
                    console.log('Add Presenter');

                    let presenter_data = {
                        event_id_random: $events_slct.event_id,
                        event_session_id_random: $events_slct.event_session_id,
                        event_presentation_id_random: event_presentation_obj.event_presentation_id_random,
                        given_name: 'New',
                        family_name: 'Presenter',
                        email: 'test+newpres@oneskyit.com',
                        code: 'new_presenter',
                        enable: true,
                    }

                    events_func.handle_create_ae_obj__event_presenter({
                        api_cfg: $ae_api,
                        event_id: $events_slct.event_id,
                        event_session_id: $events_slct.event_session_id,
                        event_presentation_id: event_presentation_obj.event_presentation_id_random,
                        data_kv: presenter_data,
                        log_lvl: 1,
                    })
                }}
                class="btn btn-sm variant-soft-warning hover:variant-filled-warning"
                >
                <span class="fas fa-plus mx-1"></span>
                Add Presenter
            </button>
            {/if}

            <!-- Make sure to show the edit button only if the user has the correct permissions. Need to set the presentation ID in the store. -->
            {#if event_presentation_obj && ($ae_loc.trusted_access || $events_loc.auth__kv.presentation[event_presentation_obj.event_presentation_id_random])}

            {#if $events_slct.event_presentation_id == event_presentation_obj.event_presentation_id_random && ae_tmp[$events_slct.event_presentation_id]?.show__edit_presentation_name}
                <button
                    type="button"
                    on:click={() => {
                        console.log('Cancel edit presentation');
                        ae_tmp[$events_slct.event_presentation_id].show__edit_presentation_name = false;

                        // Careful with the trigger_patch. It will keep firing if not reset.
                        ae_triggers.update_event_presentation_name = false;
                    }}
                    class="btn btn-sm variant-soft-warning"
                    >
                    <span class="fas fa-times mx-1">
                    </span>
                    Cancel
                </button>
            {:else}
                <button
                    type="button"
                    on:click={() => {
                        console.log('Edit presentation title and description');
                        $events_slct.event_presentation_id = event_presentation_obj.event_presentation_id_random;
                        $events_slct.event_presentation_obj = event_presentation_obj;
                        ae_tmp[$events_slct.event_presentation_id] = {
                            show__edit_presentation_name: true,
                        }
                    }}
                    title="Edit presentation title and description"
                    class="btn btn-sm variant-soft-warning">
                    <span class="fas fa-edit mx-1">
                    </span>
                    Edit Presentation Name
                </button>
            {/if}

            {#if $events_slct.event_presentation_id == event_presentation_obj.event_presentation_id_random && ae_tmp[$events_slct.event_presentation_id]?.show__edit_presentation_name && $events_slct.event_presentation_obj}
                <!-- Edit the presentation title -->
                <Element_ae_crud
                    trigger_patch={ae_triggers.update_event_presentation_name}
                    api_cfg={$ae_api}
                    object_type={'event_presentation'}
                    object_id={$events_slct.event_presentation_obj.event_presentation_id_random}
                    field_name={'name'}
                    field_type={'input'}
                    field_value={$events_slct.event_presentation_obj.name}
                    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:`, e.detail);

                        events_func.handle_load_ae_obj_id__event_presentation({api_cfg: $ae_api, event_presentation_id: $events_slct.event_presentation_obj.event_presentation_id_random, log_lvl: 1})
                        .then(function (load_results) {
                            // We need to force reload the Indexed DB - Dexie.js?
                            // Sometimes the changes are not seen. The file disappears when the Save button is pressed.

                            // Maybe reload page?
                            // window.location.reload();
                        })
                        .finally(function () {
                            ae_tmp[$events_slct.event_presentation_id].show__edit_presentation_name = false;

                            // Careful with the trigger_patch. It will keep firing if not reset.
                            ae_triggers.update_event_presentation_name = false;
                        });
                        }}
                    >
                    <input
                        bind:value={$events_slct.event_presentation_obj.name}
                        class="input min-w-96 max-w-96 text-sm"
                        />

                    <!-- disabled={$events_slct.event_presentation_obj.name == event_presentation_obj.name} -->
                    <button
                        type="button"
                        on:click={() => {
                            console.log('*** Save button clicked ***');
                            // if (!confirm('Are you sure you want to save this event_presenter?')) {return false;}

                            console.log(`Selected event_presentation_id: ${$events_slct.event_presentation_obj.event_presentation_id_random}`);

                            ae_triggers.update_event_presentation_name = true;
                            // ae_triggers.update_event_presentation_name = $events_slct.event_presentation_obj.event_presentation_id_random;
                        }}
                        class="btn btn-sm variant-soft-success hover:variant-ghost-success mx-1"
                        >
                        <span class="fas fa-save mx-1"></span>
                        Save
                    </button>
                </Element_ae_crud>
            {/if}

            {/if}
            </div>

            <h4 class="h5">
                "{event_presentation_obj.name}"
                {#if event_presentation_obj.code || event_presentation_obj.abstract_code}
                <span class="text-sm text-gray-500 bg-yellow-100 p-1 rounded-md border border-yellow-200"
                    title="Presentation code {event_presentation_obj.code} and abstract code {event_presentation_obj.abstract_code}"
                    >
                    <span class="fas fa-barcode"></span>
                    {event_presentation_obj.code ?? ''} {event_presentation_obj.abstract_code ?? ''}
                </span>
                {/if}
            </h4>

            <div>
            <Element_ae_crud
                api_cfg={$ae_api}
                object_type={'event_presentation'}
                object_id={event_presentation_obj.event_presentation_id_random}
                field_name={'description'}
                field_type={'textarea'}
                field_value={event_presentation_obj.description}
                allow_null={false}
                hide_edit_btn={!$ae_loc.trusted_access}
                outline_element={false}
                show_crud={false}
                display_inline={true}
                display_block_edit={true}
                textarea_rows={15}
                class_li={''}
                on:ae_crud_updated={e => {
                    console.log(`ae_crud_updated:`, e.detail);

                    events_func.handle_load_ae_obj_id__event_presentation({api_cfg: $ae_api, event_presentation_id: event_presentation_obj.event_presentation_id_random, log_lvl: 1});
                }}
                >
            {#if event_presentation_obj.description}
                <strong class="text-sm">
                Description:
                </strong>

                <button
                    type="button"
                    on:click={() => {
                        console.log('Show/Hide Description');
                        if ($events_loc.pres_mgmt.show_content__presentation_description == event_presentation_obj.event_presentation_id_random) {
                            $events_loc.pres_mgmt.show_content__presentation_description = null;
                        } else {
                            $events_loc.pres_mgmt.show_content__presentation_description = event_presentation_obj.event_presentation_id_random;
                        }
                    }}
                    class="btn btn-sm variant-soft-surface hover:variant-filled-surface text-xs"
                    >
                    {#if $events_loc.pres_mgmt.show_content__presentation_description == event_presentation_obj.event_presentation_id_random}
                        <span class="fas fa-eye-slash mx-1"></span>
                        <span>Hide Description</span>
                    {:else}
                        <span class="fas fa-eye mx-1"></span>
                        <span>Show</span>
                    {/if}
                </button>

                <pre
                    class="whitespace-pre-wrap p-2 bg-gray-100 rounded-md"
                    class:hidden={$events_loc.pres_mgmt.show_content__presentation_description !== event_presentation_obj.event_presentation_id_random}
                    >{event_presentation_obj.description}</pre>
            {:else}
                <div class="text-sm text-gray-500 bg-gray-100 p-1 rounded-md border border-gray-200"
                    class:hidden={!$ae_loc.administrator_access}
                    >
                    <span class="fas fa-exclamation-triangle mx-1"></span>
                    No description provided.
                </div>
            {/if}
            </Element_ae_crud>
            </div>


            <!-- Show presenters for this presentation -->
            {#await event_presentation_obj.event_presenter_li}
                <p>Loading...</p>
            {:then event_presenter_li}
                {#if event_presenter_li && event_presenter_li.length > 0}
                    <strong class="text-sm">Presenters:</strong>
                    <ul
                        class="space-y-2 px-4"
                        >
                    {#each event_presenter_li as event_presenter_obj}
                        <li>
                            <button
                                type="button"
                                disabled={!($ae_loc.trusted_access || $events_loc.auth__kv.session[$events_slct.event_session_id]) && (!$events_loc.auth__kv.presenter[event_presenter_obj.event_presenter_id_random] || !event_presenter_obj.agree)}
                                on:click={
                                    () => {
                                        console.log('View presenter details');

                                        $events_slct.event_presentation_id = event_presentation_obj.event_presentation_id_random;
                                        $events_slct.presentation_obj = event_presentation_obj;

                                        $events_slct.event_presenter_id = event_presenter_obj.event_presenter_id_random;
                                        $events_slct.presenter_obj = event_presenter_obj;

                                        $events_sess.pres_mgmt.show_content__presenter_start = event_presenter_obj.event_presenter_id_random;
                                    }
                                }
                                class="btn btn-md variant-ghost-primary hover:variant-filled-primary font-bold min-w-64"
                                title="Person ID: {event_presenter_obj.person_id_random}; Email: {event_presenter_obj.email}"
                            >
                                    <span class="fas fa-user mx-1"></span>
                                    <span class="text-center grow">
                                    {event_presenter_obj.full_name}
                                    </span>
                            </button>



                            {#if $ae_loc.trusted_access || !$events_loc.auth__person?.id }
                            <button
                                type="button"
                                on:click={() => {
                                    console.log('Email the access link');
                                    if (!event_presenter_obj.email) {
                                        alert('No email address found for this presenter.');
                                        return;
                                    }
                                    if (confirm(`This will send the sign in email to ${event_presenter_obj.email}`)) {
                                        console.log('Send the email to the presenter.');
                                    } else {
                                        console.log('Cancelled sending the email.');
                                        return false;
                                    }

                                    send_init_confirm_email(
                                        {
                                            to_email: event_presenter_obj.email,
                                            to_name: event_presenter_obj.full_name,
                                            person_id: event_presenter_obj.person_id_random,
                                            person_passcode: event_presenter_obj.person_passcode,
                                            presentation_id: event_presentation_obj.event_presentation_id_random,
                                            presenter_id: event_presenter_obj.event_presenter_id_random,
                                            presentation_name: event_presentation_obj.name,
                                        }
                                    );

                                    // send_init_confirm_email();

                                    // send_email({
                                    //     to: event_presenter_obj.email,
                                    //     subject: `Access link for ${$lq__event_session_obj.name}`,
                                    //     body: `Hello ${event_presenter_obj.full_name},\n\nHere is the access link for the session: ${data.url.origin}/events_pres_mgmt/session/{$events_slct.event_session_id}?person_id=${event_presenter_obj.person_id_random}&person_pass=${event_presenter_obj.person_passcode}\n\nThank you,\n\nThe LCI Team`,
                                    // });
                                }}
                                class="btn btn-md variant-ghost-primary hover:variant-filled-primary"
                                title="Email the access link to the presenter"
                                >
                                <span class="fas fa-envelope mx-1"></span>
                                Email Access Link
                            </button>
                            {/if}


                            {#if event_presenter_obj.agree}
                                <!-- {#if $ae_loc.trusted_access || $events_loc.auth__kv.presenter[event_presenter_obj.event_presenter_id_random]} -->
                                <button
                                    type="button"
                                    disabled={!$ae_loc.trusted_access && !$events_loc.auth__kv.presenter[event_presenter_obj.event_presenter_id_random]}
                                    on:click={
                                        () => {
                                            console.log('View terms and conditions');
                                            $events_slct.event_presentation_id = event_presentation_obj.event_presentation_id_random;
                                            $events_slct.presentation_obj = event_presentation_obj;

                                            $events_slct.event_presenter_id = event_presenter_obj.event_presenter_id_random;
                                            $events_slct.presenter_obj = event_presenter_obj;

                                            $events_sess.pres_mgmt.show_content__agree_text = event_presenter_obj.event_presenter_id_random;
                                        }
                                    }
                                    class="btn btn-md variant-ghost-success hover:variant-filled-success"
                                    title="Agreed to terms and conditions"
                                    >
                                    <span class="fas fa-check text-green-500 px-1" title="Agreed to terms and conditions"></span>
                                    Agreed
                                </button>
                            {:else}
                                <button
                                    type="button"
                                    disabled={!$ae_loc.trusted_access && !$events_loc.auth__kv.presenter[event_presenter_obj.event_presenter_id_random]}
                                    on:click={
                                        () => {
                                            console.log('View terms and conditions');
                                            $events_slct.event_presentation_id = event_presentation_obj.event_presentation_id_random;
                                            $events_slct.presentation_obj = event_presentation_obj;

                                            $events_slct.event_presenter_id = event_presenter_obj.event_presenter_id_random;
                                            $events_slct.presenter_obj = event_presenter_obj;

                                            $events_sess.pres_mgmt.show_content__agree_text = event_presenter_obj.event_presenter_id_random;
                                        }
                                    }
                                    class="btn btn-md variant-ghost-warning hover:variant-filled-warning"
                                    title="View terms and conditions"
                                    >
                                    <span class="fas fa-times bg-red-500 text-white px-1 mx-1" title="Not agreed to terms and conditions"></span>
                                    Not yet agreed
                                </button>
                            {/if}



                            {#if $ae_loc.trusted_access}
                                <!-- <span class="fas fa-envelope"></span>
                                <a
                                    href="mailto:{event_presenter_obj.email}"
                                    class="text-blue-500"
                                    >{event_presenter_obj.email}</a> -->


                                {#if event_presenter_obj.file_count}
                                    <span>
                                    <span class="fas fa-file mx-1"></span>
                                    {event_presenter_obj.file_count ? `(${event_presenter_obj.file_count}x files)` : '(0 files)'}
                                    </span>
                                {/if}

                                <!-- {#if event_presenter_obj.person_passcode}
                                    <span>
                                    <span class="fas fa-user-secret"></span>
                                    Passcode: {event_presenter_obj.person_passcode}
                                    </span>
                                {/if} -->

                                <!-- {#if event_presenter_obj.passcode}
                                    <span class="bg-red-100 p-1 rounded-md">
                                    <span class="fas fa-key"></span>
                                    Passcode: {event_presenter_obj.passcode}
                                    </span>
                                {/if} -->
                            {/if}


                            <!-- A button to copy the access link to the clipboard. -->
                            <!-- Example: /events_pres_mgmt/session/Wh8UnJlbIA0?person_id=fV1dl_IJ0yY&person_pass=abc123 -->
                            <!-- {#if $ae_loc.trusted_access}
                            <button
                                type="button"
                                class="btn btn-sm variant-soft-primary"

                                use:clipboard={encodeURI(`${data.url.origin}/events_pres_mgmt/session/${$events_slct.event_session_id}?person_id=${event_presenter_obj.person_id_random}&person_pass=${event_presenter_obj.person_passcode}&presentation_id=${event_presentation_obj.event_presentation_id_random}&presenter_id=${event_presenter_obj.event_presenter_id_random}`)}
                                >
                                <span class="fas fa-copy mx-1"></span>
                                Copy Access Link
                            </button>
                            {/if} -->

                            <div class="float-right space-2 flex flex-row items-center">
                                {#if $ae_loc.administrator_access && !event_presenter_obj.person_id_random}
                                <button
                                    type="button"
                                    on:click={async () => {
                                        console.log('Add Person');

                                        let person_data = {
                                            account_id_random: $slct.account_id,
                                            // user_id_random: user_obj.user_id_random,
                                            given_name: 'New',
                                            family_name: 'Presenter',
                                            primary_email: 'test+newpres@oneskyit.com',
                                            code: 'new_presenter',
                                            // Random number between 100000 and 999999
                                            passcode: Math.floor(Math.random() * 900000) + 100000,
                                            enable: true,
                                        }

                                        let new_person_obj = await core_func.handle_create_ae_obj__person({
                                            api_cfg: $ae_api,
                                            // user_id: $ae_loc.user_id,
                                            data_kv: person_data,
                                            log_lvl: 1,
                                        })

                                        console.log('new_person_obj:', new_person_obj);

                                        // We then need to update the event_presenter with the new person_id.
                                        events_func.handle_update_ae_obj__event_presenter({
                                            api_cfg: $ae_api,
                                            event_presenter_id: event_presenter_obj.event_presenter_id_random,
                                            data_kv: {person_id_random: new_person_obj.person_id_random},
                                            log_lvl: 1,
                                        })
                                    }}
                                    class="btn btn-sm variant-soft-warning hover:variant-filled-warning"
                                    >
                                    <span class="fas fa-plus mx-1"></span>
                                    Add Person
                                </button>
                                {/if}
                            </div>

                        </li>
                    {/each}
                    </ul>
                {/if}
            {:catch error}
                <p>Error: {error.message}</p>
            {/await}

            {#if $lq__event_file_obj_li && $lq__event_file_obj_li.length > 0}

            <strong class="text-sm">Files:</strong>
            <ul
                class="space-y-2 px-4"
                >
            {#each $lq__event_file_obj_li as event_file_obj}
                {#if (
                    event_file_obj.event_presentation_id_random == event_presentation_obj.event_presentation_id_random
                    && (
                        $ae_loc.trusted_access
                        || $events_loc.auth__kv.presentation[event_presentation_obj.event_presentation_id_random]
                        || $events_loc.auth__kv.session[$events_slct.event_session_id]    // This is the session ID of the person who signed in.
                    )
                    )}
                    <li>
                         <button
                            on:click={() => {
                                // ae_promises[event_file_obj.event_file_id_random]
                                ae_promises[event_file_obj.event_file_id_random] = api.download_hosted_file({
                                    api_cfg: $ae_api,
                                    hosted_file_id: event_file_obj.hosted_file_id_random,
                                    return_file: true,
                                    filename: event_file_obj.filename,
                                    auto_download: true,
                                    log_lvl: 1
                                });

                                // window.postMessage({ type: 'download_event_file', event_file_id: event_file_obj.event_file_id_random, filename: event_file_obj.filename, auto_download: true }, '*');
                            }}
                            class="btn btn-md variant-soft-primary hover:variant-filled-primary min-w-96"
                            title={`Download this file: ${event_file_obj.filename} [API] -- SHA256 hash: ${event_file_obj.hash_sha256.slice(0, 10)}...`}
                            >
                            {#await ae_promises[event_file_obj.event_file_id_random]}
                                <span class="fas fa-spinner fa-spin mx-1"></span>
                                <span class="">
                                    Downloading
                                    {#if $ae_sess.api_download_kv[event_file_obj.hosted_file_id_random]}
                                        {$ae_sess.api_download_kv[event_file_obj.hosted_file_id_random].percent_completed}%
                                    {/if}
                                    :
                                </span>
                            {:then}
                                <span class="fas fa-download mx-1"></span>
                                <span class="text-sm">
                                Download:
                                </span>
                            {/await}

                            <span class="grow">
                            {ae_util.shorten_filename({filename: event_file_obj.filename, max_length: 25})}
                            </span>
                        </button>
                    </li>
                {/if}
            {/each}
            </ul>
            {/if}

            <!-- Show files list for this presentation -->
            <!-- {#await event_presentation_obj.event_file_li}
                <p>Loading...</p>
            {:then event_file_li}
                {#if event_file_li}
                    <strong class="text-sm">Files:</strong>
                    <ul
                        class="space-y-2 px-4"
                        >
                    {#each event_file_li as file_obj}
                        <li>
                            <span class="fas fa-file"></span>
                            <a
                                href={file_obj.url}
                                class="text-blue-500"
                                >{file_obj.name}</a>
                        </li>
                    {/each}
                    </ul>
                {/if}
            {:catch error}
                <p>Error: {error.message}</p>
            {/await} -->

            </li>
        {/each}
        </ul>
    {:else}
        Nothing to show yet...
    {/if}
{:catch error}
    <p>Error: {error.message}</p>
{/await}
</section>


{/if}

</section>


{#if $events_sess.pres_mgmt?.show_content__agree_text}
    <div class="ae_quick_modal_container">
        <section class="ae_quick_popover">

            <div class="flex flex-col items-center">


            <!-- <div class="h-4 p-10"> -->

            <!-- </div> -->

            <section class="ae_modal_scrollfix">
            <button
                on:click={
                    () => {
                        $events_sess.pres_mgmt.show_content__agree_text = null;
                    }
                }
                class="btn btn-md variant-soft-secondary hover:variant-filled-secondary float-right"
                >
                <span class="fas fa-times mx-1"></span>
                Close
            </button>

            <Form_agree />
            </section>

            <!-- <div class="h-12"> -->
            <button
                on:click={
                    () => {
                        $events_sess.pres_mgmt.show_content__agree_text = null;
                    }
                }
                class="btn btn-md variant-soft-secondary hover:variant-filled-secondary"
                >
                <span class="fas fa-times mx-1"></span>
                Close
            </button>
            <!-- </div>   -->

            </div>

        </section>
    </div>
{/if}


{#if $events_sess.pres_mgmt?.show_content__presenter_start}
    <div class="ae_quick_modal_container">
        <section class="ae_quick_popover">

            <div class="flex flex-col items-center">

            <section class="ae_modal_scrollfix">
            <button
                on:click={
                    () => {
                        $events_sess.pres_mgmt.show_content__presenter_start = null;
                    }
                }
                class="btn btn-md variant-soft-secondary hover:variant-filled-secondary float-right"
                >
                <span class="fas fa-times mx-1"></span>
                Close
            </button>

            <Presenter_view />
            </section>

            <button
                on:click={
                    () => {
                        $events_sess.pres_mgmt.show_content__presenter_start = null;
                    }
                }
                class="btn btn-md variant-soft-secondary hover:variant-filled-secondary"
                >
                <span class="fas fa-times mx-1"></span>
                Close
            </button>

            </div>

        </section>
    </div>
{/if}


<style lang="postcss">
/* Use the div.ae_quick_modal_container to block background clicks when using the section.ae_quick_popover. */
div.ae_quick_modal_container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    background-color: hsla(0, 0%, 50%, .75);
    /* padding: 1rem; */
    /* border: solid thick red; */
}

/* The section.ae_quick_popover should be above the rest of the content and centered on the page. */
section.ae_quick_popover {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
    background-color: hsla(0, 0%, 97%, .97);
    /* margin-top: 1rem;
    margin-bottom: 2rem; */
    /* padding: 1rem;
    padding-top:4rem; */
    /* padding-bottom: 4rem; */
    border: solid thin hsla(0, 0%, 0%, .9);
    border-radius: .5rem;
    box-shadow: 0 0 1rem hsla(0, 0%, 0%, .5);

    min-height: 30%;
    /* max-height: 100vh; */
    min-width: 80%;

    /* overflow-y: auto; */
}
</style>
