<script lang="ts">
console.log(`ae_events_pres_mgmt session_view.svelte`);
export let log_lvl = 1;

// Imports (external and then internal)
import { clipboard } from '@skeletonlabs/skeleton';
import { liveQuery } from "dexie";
import { Modal } from 'flowbite-svelte';

// const dispatch = createEventDispatcher();

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils';
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 { core_func } from '$lib/ae_core_functions';
import { db_events } from "$lib/db_events";
import { ae_snip, 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 Comp_event_presenter_form_agree from './ae_comp__event_presenter_form_agree.svelte';
import Comp_event_presentation_obj_li from './ae_comp__event_presentation_obj_li.svelte';
import Comp_event_session_poc_profile from './ae_comp__event_session_poc_profile.svelte';
import Comp_event_session_poc_form_agree from './ae_comp__event_session_poc_form_agree.svelte';


// Exports
export let event_session_id: string;
// export let event_session_obj: key_val;
// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'


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

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

let poc_type = $events_loc.pres_mgmt.label__session_poc_type;

export let lq__event_obj: any;

export let lq__event_session_obj: any;

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

export let lq__auth__event_presenter_obj: any;

export let lq__event_presentation_obj_li: any;

// let lq__event_presentation_obj_li = liveQuery(
//     () => db_events.presentations
//         .where('event_session_id_random')
//         .equals(event_session_id)
//         .sortBy('name')
// );


// Local Variables

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

// let lq__auth__event_presenter_obj = liveQuery(
//     () => db_events.presenters.get($events_slct.auth__event_presenter_id)
// );

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

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


// Functions and Logic
$events_sess.pres_mgmt.session__updated_on = null;
$: if ($lq__event_session_obj) {
    if (log_lvl > 1) {
        console.log(`$lq__event_session_obj:`, $lq__event_session_obj);
    }

    if ($events_loc.pres_mgmt.show_content__session_qr) {

        if ($lq__event_session_obj.updated_on == $events_sess.pres_mgmt.session__updated_on) {
            if (log_lvl > 1) {
                console.log('Updated on is the same.');
            }
        } else {
            if (log_lvl) {
                console.log('Updated on is different.');
            }
            // FUTURE USE: Generate a QR code for the object ID.
            // ae_promises.generate_qr_code_obj_id = core_func.generate_qr_code({api_cfg: $ae_api, account_id: $slct.account_id, qr_type: 'obj', qr_id: $lq__event_session_obj?.event_session_id_random, obj_type: 'event_session', obj_id: $lq__event_session_obj?.event_session_id_random});

            // Generate a QR code for the URL.
            let qr_id_url = `${$lq__event_session_obj?.event_session_id_random}_url`;

            // URL for this page (be sure to URL encode it):
            let url_str = `${$ae_loc.url_origin}/events_pres_mgmt/session/${$lq__event_session_obj?.event_session_id_random}`;
            url_str = encodeURI(url_str);

            ae_promises.generate_qr_code_url = core_func.generate_qr_code({api_cfg: $ae_api, account_id: $slct.account_id, qr_type: 'str', qr_id: qr_id_url, str: url_str});

            $events_sess.pres_mgmt.session__updated_on = $lq__event_session_obj?.updated_on;
        }
    } else {
        if (log_lvl) {
            console.log('Clearing the URL.');
        }
        ae_promises.generate_qr_code_url = null;
        // Resetting the updated_on value helps with the QR code come back when switched back on.
        $events_sess.pres_mgmt.session__updated_on = null;
    }
}
</script>


{#if $lq__event_session_obj}

<section class="p-2">


{#await ae_promises.generate_qr_code_url}
    Generating...
{:then result}
    {#if ae_promises.generate_qr_code_url && $ae_loc.trusted_access}
        <span class="float-right m-1 p-1 flex flex-col items-center justify-center outline outline-gray-200 *:hover:inline">
            <img
                class="qr_code qr_type_url h-32 w-32 hover:h-48 hover:w-48"
                style=""
                src={result}
                alt="URL QR code"
                />
            <span>
                <span class="fas fa-link"></span>
                <span>Session URL</span>
            </span>
            <div class="hidden">
                This QR is a link back to this page.
            </div>
        </span>
    {/if}
{/await}


<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 || !$ae_loc.edit_mode}
            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.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>

        {#if !$events_loc.pres_mgmt?.hide__session_code}
        <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 || !$ae_loc.edit_mode}
            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.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>
        {/if}
    </li>
    <li>
        <strong class="text-sm">
            Date
            &amp;
            <button
                type="button"
                on:click={() => {
                    if ($events_loc.pres_mgmt.time_hours == 12) {
                        $events_loc.pres_mgmt.time_hours = 24;
                        $events_loc.pres_mgmt.datetime_format = 'datetime_long';
                        $events_loc.pres_mgmt.time_format = 'time_short';
                    } else {
                        $events_loc.pres_mgmt.time_hours = 12;
                        $events_loc.pres_mgmt.datetime_format = 'datetime_12_long';
                        $events_loc.pres_mgmt.time_format = 'time_12_short';
                    }
                }}
                >
                time
            </button>
            :</strong>
            <span class="fas fa-calendar-alt"></span>
        <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 || !$ae_loc.edit_mode}
            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.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, $events_loc.pres_mgmt.datetime_format)}
        </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 || !$ae_loc.edit_mode}
            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.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, $events_loc.pres_mgmt.time_format)}
        </Element_ae_crud>
    </li>
    <li>
        <strong class="text-sm">Location/room:</strong>
        <!-- Minimum level access to see the link here is trusted. Administrators can see even if the show launcher link is disabled. -->

        <!-- BEGIN: Legacy link -->
        {#if $ae_loc.administrator_access || $ae_loc.authenticated_access && $events_loc.pres_mgmt.show__launcher_link_legacy}
            <!-- class="text-blue-500 hover:text-blue-800 hover:underline" -->
            <a
                data-sveltekit-preload-data="false"
                href="/event/{$lq__event_session_obj?.event_id_random}/launcher/{$lq__event_session_obj?.event_location_id_random}"
                class="btn btn-sm variant-glass-secondary hover:variant-filled-secondary"
                title="Launcher: {$lq__event_session_obj?.event_location_name} {$lq__event_session_obj?.event_location_id_random}"
                >
                <span class="fas fa-paper-plane m-1"></span>
                {@html $lq__event_session_obj?.event_location_name ? $lq__event_session_obj?.event_location_name : ae_snip.html__not_set}
            </a>
        {:else}
            {@html $lq__event_session_obj.event_location_name ? $lq__event_session_obj.event_location_name : ae_snip.html__not_set}
        {/if}
        <!-- END: Legacy link -->

        {#if $ae_loc.manager_access || $ae_loc.administrator_access && $events_loc.pres_mgmt.show__launcher_link}
            <a
                href="/events_pres_mgmt/launcher/{$lq__event_session_obj?.event_id_random}"
                class="text-blue-500 hover:text-blue-800 hover:underline"
                title="Launcher: {$lq__event_session_obj?.event_location_name} {$lq__event_session_obj?.event_location_id_random}"
                >
                <span class="fas fa-plane"></span>
                <!-- {@html $lq__event_session_obj.event_location_name ? $lq__event_session_obj.event_location_name : ae_snip.html__not_set} -->
            </a>
        {:else}
            <!-- {@html $lq__event_session_obj.event_location_name ? $lq__event_session_obj.event_location_name : ae_snip.html__not_set} -->
        {/if}

        {#if $ae_loc.trusted_access && $ae_loc.edit_mode}
        <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}
            val_empty_is_null={true}
            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.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.load_ae_obj_li__event_location({api_cfg: $ae_api, account_id: $slct.account_id, params: params});

                        $slct.event_location_obj_li = events_func.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
        class:hidden={$events_loc.pres_mgmt?.hide__session_poc}
        >
        <strong class="text-sm">{$events_loc.pres_mgmt?.label__session_poc_name}:</strong>
        {#if $lq__event_session_obj?.poc_person_id_random}
            {#if $ae_loc.manager_access}
            <a
                href="/core/person/{$lq__event_session_obj.poc_person_id_random}"
                class="text-blue-500 hover:text-blue-800 hover:underline"
                    title="View Person: {$lq__event_session_obj?.poc_person_full_name} {$lq__event_session_obj?.poc_person_id_random}"
                >
                {@html $lq__event_session_obj?.poc_person_full_name ? $lq__event_session_obj.poc_person_full_name : ae_snip.html__not_set}
            </a>
            {/if}

        {#if
            $ae_loc.trusted_access ||
            $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random] === true}
            <!-- Modal toggle -->
            <button
                class="btn btn-sm variant-soft-primary hover:variant-filled-primary"
                on:click={() => ($events_sess.pres_mgmt.show__session_poc_profile = true)}>
                <span class="fas fa-id-card m-1"></span>
                <!-- {$events_loc.pres_mgmt?.label__session_poc_name}'s -->
                 {$lq__event_session_obj?.poc_person_full_name}'s Profile
            </button>

            <!-- Main modal -->
            <Modal
                title="{$events_loc.pres_mgmt?.label__session_poc_name}'s Profile"
                bind:open={$events_sess.pres_mgmt.show__session_poc_profile}
                autoclose={false}
                class="bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded-lg border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md relative flex flex-col mx-auto w-full divide-y"
                >

                <Comp_event_session_poc_profile
                        class_li={$events_sess.pres_mgmt.show__session_poc_profile ? '' : ''}
                        person_id={$lq__event_session_obj.poc_person_id_random}
                        lq__event_session_obj={lq__event_session_obj}
                        />

                <svelte:fragment slot="footer">
                    <div class="text-center w-full">
                        <button
                            type="button"
                            on:click={() => {
                                console.log('Close modal session poc profile.');
                                $events_sess.pres_mgmt.show__session_poc_profile = !$events_sess.pres_mgmt.show__session_poc_profile;
                            }}
                            class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                            >
                            <span class="fas fa-times mx-1"></span>
                            Close
                        </button>
                    </div>
                </svelte:fragment>

            </Modal>

            {#if $events_loc.pres_mgmt?.require__session_agree}
            <!-- Modal toggle -->
            <button
                type="button"
                disabled={!$ae_loc.trusted_access &&
            !$events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random] === true}
                class="btn btn-sm hover:variant-filled-success"
                class:variant-soft-success={$lq__event_session_obj?.poc_agree}
                class:variant-ghost-warning={!$lq__event_session_obj?.poc_agree}
                on:click={() => ($events_sess.pres_mgmt.show_modal__session_poc_agree = true)}>
                {#if !$lq__event_session_obj?.poc_agree}
                    <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
                {:else}
                    <span class="fas fa-check text-green-500 px-1" title="Agreed to terms and conditions"></span>
                    Agreed
                {/if}
            </button>

            <!-- Main modal -->
            <Modal
                title="{$events_loc.pres_mgmt?.label__session_poc_name}'s Consent and Release and Terms and Conditions"
                bind:open={$events_sess.pres_mgmt.show_modal__session_poc_agree}
                autoclose={false}
                >

                <Comp_event_session_poc_form_agree
                    lq__event_session_obj={lq__event_session_obj}
                    />

                <svelte:fragment slot="footer">
                    <div class="text-center w-full">

                        <button
                            on:click={() => {
                                $events_sess.pres_mgmt.show_modal__session_poc_agree = false;
                            }}
                            class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                            >
                            <span class="fas fa-times m-1"></span>
                            Close
                        </button>
                    </div>
                </svelte:fragment>

            </Modal>
            {/if}


            <!-- </div> -->

            {:else}
            <span title={$lq__event_session_obj?.poc_person_id_random}>
                {@html $lq__event_session_obj.poc_person_full_name ? $lq__event_session_obj.poc_person_full_name : ae_snip.html__not_set}
            </span>
            {/if}
        {:else}
            {@html ae_snip.html__not_set}
        {/if}

        <!-- {#if $ae_loc.trusted_access && $ae_loc.edit_mode} -->

        <!-- <span title={$lq__event_session_obj?.poc_person_id_random}>
            {@html $lq__event_session_obj.poc_person_full_name ? $lq__event_session_obj.poc_person_full_name : ae_snip.html__not_set}
        </span> -->

        {#if $ae_loc.trusted_access && $ae_loc.edit_mode}
        <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.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] === true}
            <span class="text-green-500">Signed In</span>
        {/if}
        {#if $events_loc.pres_mgmt?.show__email_access_link
            && $lq__event_session_obj.poc_person_primary_email
            && ($ae_loc.trusted_access || !$events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random])
            }

            <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;
                    }

                    events_func.email_sign_in__event_session(
                        {
                            api_cfg: $ae_api,
                            to_email: $lq__event_session_obj.poc_person_primary_email,
                            to_name: $lq__event_session_obj?.poc_person_full_name?? '-- not set --',
                            base_url: $ae_loc.url_origin,
                            person_id: $lq__event_session_obj?.poc_person_id_random?? '-- not set --',
                            person_passcode: $lq__event_session_obj?.poc_person_passcode?? '-- not set --',
                            event_session_id: $lq__event_session_obj?.event_session_id_random?? '-- not set --',
                            session_name: $lq__event_session_obj?.name?? '-- not set --',
                        }
                    );
                }}
                class="btn btn-sm variant-ghost-secondary hover:variant-filled-secondary"
                title="Email the access link to the POC (moderator/champion)"
                >
                <span class="fas fa-envelope mx-1"></span>
                Email Access Link
            </button>

        {/if}

        {#if $events_loc.pres_mgmt?.show__copy_access_link
            && ($ae_loc.trusted_access || $lq__event_session_obj.poc_person_id_random)}
            <!-- 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>
        <span class="fas fa-key"></span>
        {@html $lq__event_session_obj.passcode ? $lq__event_session_obj.passcode : ae_snip.html__not_set}
        <Element_ae_crud
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$lq__event_session_obj?.event_session_id_random}
            field_name={'passcode'}
            field_type={'text'}
            field_value={$lq__event_session_obj?.passcode}
            allow_null={true}
            hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
            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.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) {
                });
            }}
            >
        </Element_ae_crud>
    </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 || !$ae_loc.edit_mode}
        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.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>

        {#if $lq__event_session_obj.description}
        <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>

        {:else}
            {@html ae_snip.html__not_set}
        {/if}
    </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 && $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random]) }

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

    <!-- {#if $ae_loc.trusted_access || $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random] || ($events_loc.auth__kv.presenter[$events_slct.event_presenter_id] &&  $lq__event_presenter_obj?.agree)} -->
    {#if
        $ae_loc.trusted_access ||
        $events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random] === true ||
        ($events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random] == 'read' && $lq__auth__event_presenter_obj?.agree)
        }
        <!-- Message if they have agreed -->
        <Element_data_store
            ds_code="events__pres_mgmt__session_page_authorized_info"
            ds_name="Default: Events - Pres Mgmt Session Authorized Info"
            ds_type="html"
            for_type="event"
            for_id={$lq__event_presenter_obj?.event_id_random}
            class_li="w-fit max-w-screen-lg flex flex-col gap-1"
            show_edit={false}
            show_edit_btn={true}
            mount_reload_sec={1}
            />
    {:else if ($events_loc.auth__kv.session[$lq__event_session_obj?.event_session_id_random] == 'read' && !$lq__event_presenter_obj?.agree)}
        <!-- Message if they have not yet agreed -->
        <Element_data_store
            ds_code="events__pres_mgmt__presenter_agree_read_consent"
            ds_name="Default: Events - Pres Mgmt Session Restricted Access"
            ds_type="html"
            for_type="event"
            for_id={$lq__event_presenter_obj?.event_id_random}
            class_li="w-fit max-w-screen-lg 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"
            show_edit={false}
            show_edit_btn={true}
            />
    {/if}

{:else}

    <Element_data_store
        ds_code="events__pres_mgmt__session_page_restricted_access"
        ds_name="Default: Events - Pres Mgmt Session Restricted Access"
        ds_type="html"
        for_type="event"
        for_id={$lq__event_presenter_obj?.event_id_random}
        class_li="w-fit max-w-screen-lg text-xl text-red-500 font-bold text-center p-1 m-1 border border-red-200 rounded-md bg-red-100"
        show_edit={false}
        show_edit_btn={true}
        />

{/if}



</div>

</section>


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

    {#await $lq__event_presentation_obj_li}
    Loading....
    {:then event_presentation_obj_li}
    {#if $lq__event_presentation_obj_li && $lq__event_presentation_obj_li?.length > 0}
        <!-- {$lq__event_presentation_obj_li?.length} Presentations -->
        <Comp_event_presentation_obj_li
            lq__event_obj={lq__event_obj}
            lq__event_presentation_obj_li={lq__event_presentation_obj_li}
            >
            <!-- event_presentation_id_random_li={[]} -->
        </Comp_event_presentation_obj_li>
    {/if}
    {/await}

</section>

{/if}


<!-- Main modal -->
<Modal
    title="Presenter's Profile"
    bind:open={$events_sess.pres_mgmt.show_modal__presenter_agree}
    autoclose={false}
    class="bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded-lg border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md relative flex flex-col mx-auto w-full divide-y"
    >

    <Comp_event_presenter_form_agree
        lq__event_presenter_obj={lq__event_presenter_obj}
        />

    <svelte:fragment slot="footer">
        <div class="text-center w-full">

            <button
                on:click={() => {
                    $events_sess.pres_mgmt.show_modal__presenter_agree = false;
                }}
                class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                >
                <span class="fas fa-times m-1"></span>
                Close
            </button>
        </div>
    </svelte:fragment>

</Modal>


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