<script lang="ts">
interface Props {
    log_lvl?: number;
    // export let event_presenter_id: string;
    lq__event_presenter_obj: any;
    // export let event_presentation_id: string;
    lq__event_presentation_obj: any;
}

let {
    log_lvl = 0,
    lq__event_presenter_obj,
    lq__event_presentation_obj
}: Props = $props();

console.log(`ae_events_pres_mgmt presenter_view.svelte`);

import { onMount } from 'svelte';
import { browser } from '$app/environment';

import { ae_util } from '$lib/ae_utils/ae_utils';
import { api } from '$lib/ae_api/api';
import Element_ae_obj_field_editor from '$lib/elements/element_ae_obj_field_editor.svelte';
import MyClipboard from '$lib/app_components/e_app_clipboard.svelte';

import { core_func } from '$lib/ae_core/ae_core_functions';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
// import { db_events } from "$lib/ae_events/db_events";
import {
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { pres_mgmt_loc } from '$lib/stores/ae_events_stores__pres_mgmt.svelte';
import { events_auth_loc } from '$lib/stores/ae_events_stores__auth.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';
import {
    Asterisk,
    BookOpen,
    Building2,
    Check,
    CircleUser,
    FingerprintPattern,
    IdCard,
    Link,
    LoaderCircle,
    Mail,
    MessageSquareText,
    Plus,
    Presentation,
    RefreshCw,
    Save,
    Tag,
    Unlink,
    User,
    UserCheck,
    UserRound
} from '@lucide/svelte';
// Exports

// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'

// let ae_placeholder_li: key_val = {};
let ae_promises: { [key: string]: any } = $state({});
let ae_tmp: { [key: string]: any } = $state({ show__file_li: true });

ae_tmp.biography = null;

$effect(() => {
    if (
        browser &&
        ae_tmp.biography === null &&
        $lq__event_presenter_obj?.biography
    ) {
        ae_tmp.biography = $lq__event_presenter_obj?.biography ?? '';
        if (log_lvl) {
            console.log(`ae_tmp.biography:`, ae_tmp.biography);
        }
    }
});

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

onMount(() => {
    if (log_lvl) {
        console.log(
            `Events Pres Mgmt: presenter_view.svelte - event_presenter_id: ${$lq__event_presenter_obj?.event_presenter_id}`,
            $lq__event_presenter_obj
        );
    }

    $slct_trigger = 'load__event_file_obj_li';
});

ae_promises.generate_qr_code_url = null;
$events_sess.pres_mgmt.presenter__updated_on = null;
$effect(() => {
    if ($lq__event_presenter_obj) {
        if (log_lvl > 1) {
            console.log(`$lq__event_presenter_obj:`, $lq__event_presenter_obj);
        }

        // Generate QR when admin has enabled it (show__presenter_qr) OR trusted staff
        // has turned on their local override (show_content__presenter_qr).
        // show_content__presenter_qr is NOT required when show__presenter_qr is true —
        // non-trusted users (presenters) have no way to toggle it.
        if (
            pres_mgmt_loc.current.show__presenter_qr ||
            ($ae_loc.trusted_access && pres_mgmt_loc.current.show_content__presenter_qr)
        ) {
            if (
                $lq__event_presenter_obj.updated_on ==
                $events_sess.pres_mgmt.presenter__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_presenter_obj?.event_presenter_id, obj_type: 'event_presenter', obj_id: $lq__event_presenter_obj?.event_presenter_id});

                // Generate a QR code for the URL.
                // URL for this page (be sure to URL encode it):
                let url_str = `${$ae_loc.url_origin}/events/${$lq__event_presenter_obj?.event_id}/presenter/${$lq__event_presenter_obj?.event_presenter_id}`;
                url_str = encodeURI(url_str);

                ae_promises.generate_qr_code_url =
                    core_func.js_generate_qr_code('str', { str: url_str });

                // $events_sess.pres_mgmt.presenter__url_str = url_str;
                $events_sess.pres_mgmt.presenter__updated_on =
                    $lq__event_presenter_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.presenter__updated_on = null;
        }
    }
});

async function load_person_options_for_presenter_link() {
    if (!$slct.account_id) return;
    if (Object.keys($slct.person_obj_kv ?? {}).length > 1) return;
    $slct.person_obj_li = core_func
        .load_ae_obj_li__person({
            api_cfg: $ae_api,
            for_obj_type: 'account',
            for_obj_id: $slct.account_id,
            limit: 1000,
            order_by_li: { family_name: 'ASC', given_name: 'ASC', updated_on: 'DESC', created_on: 'DESC' }
        })
        .then(function (load_results) {
            if (load_results) {
                let person_obj_kv: Record<string, string> = {};
                person_obj_kv[''] = '-- Select a person --';
                load_results.forEach((person_obj) => {
                    let option_text = `${person_obj?.last_first_name ?? person_obj?.given_name} (${person_obj?.primary_email?.length ? person_obj?.primary_email : '-- not set --'})`;
                    person_obj_kv[person_obj.person_id] = option_text;
                });
                $slct.person_obj_kv = person_obj_kv;
            }
            return load_results;
        });
}
</script>

{#if $lq__event_presenter_obj}
    <h3 class="h5 text-center">
        <IdCard size="1em" />
        <!-- <span class="fas fa-info"></span> -->
        Presenter Details
    </h3>

    <section class="p-2">
        <h3 class="h6 text-lg/6">

            <!-- text-blue-500 hover:text-blue-800  -->
            <!-- hover:underline  -->
            <a
                href="/events/{$lq__event_presenter_obj?.event_id}/session/{$lq__event_presenter_obj?.event_session_id}"
                class="btn preset-tonal-secondary preset-outlined-secondary-100-900"
                title="ID: {$lq__event_presenter_obj?.event_session_id}"
                >
                <span class="text-surface-800-200 text-sm">
                    <Presentation
                        size="1em"
                        class="" />
                        Session:
                </span>
                "{$lq__event_presenter_obj?.event_session_name}"
            </a>
        </h3>
        <h3 class="h6 text-lg/6">
            <Element_ae_obj_field_editor
                object_type={'event_presentation'}
                object_id={$lq__event_presenter_obj?.event_presentation_id}
                field_name={'name'}
                field_type={'text'}
                current_value={$lq__event_presenter_obj?.event_presentation_name}
                on_success={() =>
                    events_func.load_ae_obj_id__event_presentation({
                        api_cfg: $ae_api,
                        event_presentation_id:
                            $lq__event_presenter_obj?.event_presentation_id,
                        log_lvl: 0
                    })}>
                <span class="text-surface-800-200 text-sm">
                    <MessageSquareText
                    size="1em"
                    class="text-primary-500" />
                    Presentation:
                </span>
                <span
                    title="ID: {$lq__event_presenter_obj?.event_presentation_id}">
                    "{$lq__event_presenter_obj?.event_presentation_name}"
                </span>
            </Element_ae_obj_field_editor>
        </h3>

        <h3 class="h6 text-lg/6">
            <span class="text-surface-800-200 text-sm"> Presenter: </span>
        </h3>

        {#await ae_promises.generate_qr_code_url}
            Generating...
        {:then result}
            {#if ae_promises.generate_qr_code_url && (pres_mgmt_loc.current.show__presenter_qr || ($ae_loc.trusted_access && pres_mgmt_loc.current.show_content__presenter_qr))}
                <div
                    class="group float-right m-1 flex flex-col items-center justify-center p-1 outline outline-gray-200 transition-all">
                    <!-- svelte-ignore a11y_click_events_have_key_events -->
                    <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
                    <img
                        src={result}
                        onclick={() => {
                            $events_sess.pres_mgmt.qr_bigger =
                                !$events_sess.pres_mgmt.qr_bigger;
                        }}
                        class:h-48={$events_sess.pres_mgmt.qr_bigger}
                        class:w-48={$events_sess.pres_mgmt.qr_bigger}
                        class:hover:h-96={$events_sess.pres_mgmt.qr_bigger}
                        class:hover:w-96={$events_sess.pres_mgmt.qr_bigger}
                        class="qr_code qr_type_url
                            z-10 h-32

                            w-32 cursor-crosshair transition-all
                            duration-500
                            ease-in-out
                            "
                        alt="URL QR code" />
                    <span>
                        <Link size="1em" />
                        <span>Presenter URL</span>
                    </span>
                    <div
                        class="hidden shrink p-1 text-center text-xs text-gray-500 italic group-hover:block">
                        This QR is a link back to this page.
                    </div>
                </div>
            {/if}
        {/await}

        <ul class="space-y-1.5 px-4">
            <li
                class:hidden={!$ae_loc.trusted_access ||
                    (!$ae_loc.edit_mode && !$ae_loc.manager_access)}>
                <Element_ae_obj_field_editor
                    object_type={'event_presenter'}
                    object_id={$lq__event_presenter_obj?.event_presenter_id}
                    field_name={'external_id'}
                    field_type={'text'}
                    current_value={$lq__event_presenter_obj.external_id}
                    allow_null={true}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <IdCard size="1em" />
                    {pres_mgmt_loc.current.label__presenter_external_id ??
                        'External ID'}:
                    <span class="font-bold">
                        {@html $lq__event_presenter_obj?.external_id ??
                            ae_snip.html__not_set}
                    </span>
                </Element_ae_obj_field_editor>

                {#if $lq__event_presenter_obj?.person_id && $lq__event_presenter_obj.external_id != $lq__event_presenter_obj.person_external_id}
                    <div>
                        <Element_ae_obj_field_editor
                            object_type={'person'}
                            object_id={$lq__event_presenter_obj.person_id}
                            field_name={'external_id'}
                            field_type={'text'}
                            current_value={$lq__event_presenter_obj.person_external_id}
                            allow_null={true}
                            on_success={() =>
                                events_func.load_ae_obj_id__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    log_lvl: 0
                                })}>
                            <Asterisk size="1em" />
                            <IdCard size="1em" />
                            {pres_mgmt_loc.current.label__person_external_id ??
                                'Person External ID'}:
                            <span class="font-bold">
                                {@html $lq__event_presenter_obj.person_external_id ??
                                    ae_snip.html__not_set}
                            </span>
                        </Element_ae_obj_field_editor>

                        <button
                            type="button"
                            onclick={async () => {
                                console.log(
                                    '*** Sync external ID button clicked ***'
                                );
                                if (
                                    !confirm(
                                        'Are you sure you want to sync the external IDs?'
                                    )
                                ) {
                                    return false;
                                }
                                await api.update_ae_obj({
                                    api_cfg: $ae_api,
                                    obj_type: 'person',
                                    obj_id: $lq__event_presenter_obj.person_id,
                                    fields: {
                                        external_id:
                                            $lq__event_presenter_obj.external_id
                                    }
                                });
                                events_func.load_ae_obj_id__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    log_lvl: 0
                                });
                            }}
                            class="btn btn-sm preset-tonal-warning group"
                            title="Use the external ID from this presenter record to overwrite the person record.">
                            <RefreshCw size="1em" class="m-0.75" />
                            <span class="hidden group-hover:inline">Sync</span>
                        </button>
                    </div>
                {/if}
            </li>

            <li
                class=""
                class:hidden={!$ae_loc.trusted_access ||
                    (!$ae_loc.edit_mode && !$ae_loc.manager_access)}>
                <User size="1em" />

                <Element_ae_obj_field_editor
                    object_type={'event_presenter'}
                    object_id={$lq__event_presenter_obj?.event_presenter_id}
                    field_name={'given_name'}
                    field_type={'text'}
                    current_value={$lq__event_presenter_obj.given_name}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <span class="font-bold">
                        {$lq__event_presenter_obj.given_name}
                    </span>
                </Element_ae_obj_field_editor>

                <Element_ae_obj_field_editor
                    object_type={'event_presenter'}
                    object_id={$lq__event_presenter_obj?.event_presenter_id}
                    field_name={'family_name'}
                    field_type={'text'}
                    current_value={$lq__event_presenter_obj.family_name}
                    allow_null={true}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <span class="font-bold">
                        {$lq__event_presenter_obj.family_name}
                    </span>
                </Element_ae_obj_field_editor>

                {#if $lq__event_presenter_obj.person_id && ($lq__event_presenter_obj.person_given_name != $lq__event_presenter_obj.given_name || $lq__event_presenter_obj.person_family_name != $lq__event_presenter_obj.family_name)}
                    {#if $lq__event_presenter_obj.person_given_name != $lq__event_presenter_obj.given_name}
                        <div>
                            <Asterisk size="1em" />
                            <CircleUser size="1em" />
                            given name:
                            <Element_ae_obj_field_editor
                                object_type={'person'}
                                object_id={$lq__event_presenter_obj.person_id}
                                field_name={'given_name'}
                                field_type={'text'}
                                current_value={$lq__event_presenter_obj.person_given_name}
                                on_success={() =>
                                    events_func.load_ae_obj_id__event_presenter(
                                        {
                                            api_cfg: $ae_api,
                                            event_presenter_id:
                                                $lq__event_presenter_obj?.event_presenter_id,
                                            log_lvl
                                        }
                                    )}>
                                <span class="font-bold">
                                    {@html $lq__event_presenter_obj.person_given_name ??
                                        ae_snip.html__not_set}
                                </span>
                            </Element_ae_obj_field_editor>

                            {#if $ae_loc.edit_mode && $ae_loc.trusted_access}
                                <!-- Sync button: overwrites person.given_name with presenter.given_name -->
                                <button
                                    type="button"
                                    onclick={async () => {
                                        console.log(
                                            '*** Sync name button clicked ***'
                                        );
                                        if (
                                            !confirm(
                                                'Are you sure you want to sync the names?'
                                            )
                                        ) {
                                            return false;
                                        }
                                        await api.update_ae_obj({
                                            api_cfg: $ae_api,
                                            obj_type: 'person',
                                            obj_id: $lq__event_presenter_obj.person_id,
                                            fields: {
                                                given_name:
                                                    $lq__event_presenter_obj.given_name
                                            }
                                        });
                                        events_func.load_ae_obj_id__event_presenter(
                                            {
                                                api_cfg: $ae_api,
                                                event_presenter_id:
                                                    $lq__event_presenter_obj?.event_presenter_id,
                                                log_lvl
                                            }
                                        );
                                    }}
                                    class="btn btn-sm preset-tonal-warning group transition-all"
                                    title="Use the name from this presenter record to overwrite the person record. Presenter ID: {$lq__event_presenter_obj?.event_presenter_id} to Person ID: {$lq__event_presenter_obj?.person_id}">
                                    <RefreshCw size="1em" class="m-0.75" />
                                    <span
                                        class="hidden group-hover:inline-block"
                                        >Sync</span>
                                </button>
                            {/if}
                        </div>
                    {/if}

                    {#if $lq__event_presenter_obj.person_family_name != $lq__event_presenter_obj.family_name}
                        <div>
                            <Asterisk size="1em" />
                            <CircleUser size="1em" />
                            family name:
                            <Element_ae_obj_field_editor
                                object_type={'person'}
                                object_id={$lq__event_presenter_obj.person_id}
                                field_name={'family_name'}
                                field_type={'text'}
                                current_value={$lq__event_presenter_obj.person_family_name}
                                allow_null={true}
                                on_success={() =>
                                    events_func.load_ae_obj_id__event_presenter(
                                        {
                                            api_cfg: $ae_api,
                                            event_presenter_id:
                                                $lq__event_presenter_obj?.event_presenter_id,
                                            log_lvl: 0
                                        }
                                    )}>
                                <span class="font-bold">
                                    {@html $lq__event_presenter_obj.person_family_name ??
                                        ae_snip.html__not_set}
                                </span>
                            </Element_ae_obj_field_editor>

                            {#if $ae_loc.edit_mode && $ae_loc.trusted_access}
                                <!-- Sync button: overwrites person.family_name with presenter.family_name -->
                                <button
                                    type="button"
                                    onclick={async () => {
                                        console.log(
                                            '*** Sync name button clicked ***'
                                        );
                                        if (
                                            !confirm(
                                                'Are you sure you want to sync the names?'
                                            )
                                        ) {
                                            return false;
                                        }
                                        await api.update_ae_obj({
                                            api_cfg: $ae_api,
                                            obj_type: 'person',
                                            obj_id: $lq__event_presenter_obj.person_id,
                                            fields: {
                                                family_name:
                                                    $lq__event_presenter_obj.family_name
                                            }
                                        });
                                        events_func.load_ae_obj_id__event_presenter(
                                            {
                                                api_cfg: $ae_api,
                                                event_presenter_id:
                                                    $lq__event_presenter_obj?.event_presenter_id,
                                                log_lvl: 0
                                            }
                                        );
                                    }}
                                    class="btn btn-sm preset-tonal-warning group"
                                    title="Use the name from this presenter record to overwrite the person record. Presenter ID: {$lq__event_presenter_obj?.event_presenter_id} to Person ID: {$lq__event_presenter_obj?.person_id}">
                                    <RefreshCw size="1em" class="m-0.75" />
                                    <span class="hidden group-hover:inline"
                                        >Sync</span>
                                </button>
                            {/if}
                        </div>
                    {/if}
                {/if}
            </li>

            <li
                class:hidden={!$ae_loc.trusted_access &&
                    !events_auth_loc.current.auth__kv.presenter[$lq__event_presenter_obj?.event_presenter_id] &&
                    !events_auth_loc.current.auth__kv.presenter[$lq__event_presenter_obj?.email ?? ''] &&
                    !events_auth_loc.current.auth__kv.session[$lq__event_presenter_obj.event_session_id]}>
                <Element_ae_obj_field_editor
                    object_type={'event_presenter'}
                    object_id={$lq__event_presenter_obj?.event_presenter_id}
                    field_name={'email'}
                    field_type={'email'}
                    current_value={$lq__event_presenter_obj.email}
                    allow_null={true}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <Mail size="1em" />
                    {#if $lq__event_presenter_obj.email}
                        <span class="font-bold">
                            <a
                                href="mailto:{$lq__event_presenter_obj.email}"
                                class="text-blue-500 hover:text-blue-800 hover:underline"
                                title="Presenter's email address"
                                >{$lq__event_presenter_obj.email}</a>
                        </span>
                    {:else}
                        email
                        {@html ae_snip.html__not_set}
                    {/if}
                </Element_ae_obj_field_editor>

                {#if $lq__event_presenter_obj.person_primary_email && $lq__event_presenter_obj.person_primary_email != $lq__event_presenter_obj.email}
                    <div>
                        <Element_ae_obj_field_editor
                            object_type={'person'}
                            object_id={$lq__event_presenter_obj.person_id}
                            field_name={'primary_email'}
                            field_type={'email'}
                            current_value={$lq__event_presenter_obj.person_primary_email}
                            on_success={() =>
                                events_func.load_ae_obj_id__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    log_lvl: 0
                                })}>
                            <Asterisk size="1em" />
                            <Mail size="1em" />
                            {#if $lq__event_presenter_obj.person_primary_email}
                                <span class="font-bold">
                                    <a
                                        href="mailto:{$lq__event_presenter_obj.person_primary_email}"
                                        class="text-blue-500 hover:text-blue-800 hover:underline"
                                        title="Person's primary email address"
                                        >{$lq__event_presenter_obj.person_primary_email}</a>
                                </span>
                            {:else}
                                email
                                {@html ae_snip.html__not_set}
                            {/if}
                        </Element_ae_obj_field_editor>

                        {#if $ae_loc.trusted_access}
                            <!-- Sync button: overwrites person.primary_email with presenter.email -->
                            <button
                                type="button"
                                onclick={async () => {
                                    console.log(
                                        '*** Sync email button clicked ***'
                                    );
                                    if (
                                        !confirm(
                                            'Are you sure you want to sync the email addresses?'
                                        )
                                    ) {
                                        return false;
                                    }
                                    await api.update_ae_obj({
                                        api_cfg: $ae_api,
                                        obj_type: 'person',
                                        obj_id: $lq__event_presenter_obj.person_id,
                                        fields: {
                                            primary_email:
                                                $lq__event_presenter_obj.email
                                        }
                                    });
                                    events_func.load_ae_obj_id__event_presenter(
                                        {
                                            api_cfg: $ae_api,
                                            event_presenter_id:
                                                $lq__event_presenter_obj?.event_presenter_id,
                                            log_lvl: 0
                                        }
                                    );
                                }}
                                class="btn btn-sm preset-tonal-warning group"
                                title="Use the email address from this presenter record to overwrite the person record.">
                                <RefreshCw size="1em" class="m-0.75" />
                                <span class="hidden group-hover:inline"
                                    >Sync</span>
                            </button>
                        {/if}
                    </div>
                {/if}
            </li>

            <li
                class:hidden={!$ae_loc.authenticated_access &&
                    !$lq__event_presenter_obj.affiliations}>
                <Element_ae_obj_field_editor
                    object_type={'event_presenter'}
                    object_id={$lq__event_presenter_obj?.event_presenter_id}
                    field_name={'affiliations'}
                    field_type={'text'}
                    current_value={$lq__event_presenter_obj.affiliations}
                    allow_null={true}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <Building2 size="1em" />
                    {#if $lq__event_presenter_obj.affiliations && $lq__event_presenter_obj.affiliations.length}
                        <span class="font-bold">
                            {$lq__event_presenter_obj.affiliations}
                        </span>
                    {:else}
                        affiliations
                        {@html ae_snip.html__not_set}
                    {/if}
                </Element_ae_obj_field_editor>

                {#if $ae_loc.trusted_access}
                {#if $lq__event_presenter_obj.person_id && $lq__event_presenter_obj.person_affiliations != $lq__event_presenter_obj.affiliations}
                    <div>
                        <Element_ae_obj_field_editor
                            object_type={'person'}
                            object_id={$lq__event_presenter_obj.person_id}
                            field_name={'affiliations'}
                            field_type={'text'}
                            current_value={$lq__event_presenter_obj.person_affiliations}
                            allow_null={true}
                            on_success={() =>
                                events_func.load_ae_obj_id__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    log_lvl: 0
                                })}>
                            <Asterisk size="1em" />
                            <Building2 size="1em" />
                            <span class="font-bold">
                                <!-- eslint-disable-next-line svelte/no-at-html-tags -->
                                {@html $lq__event_presenter_obj.person_affiliations ??
                                    'affiliations' + ae_snip.html__not_set}
                            </span>
                        </Element_ae_obj_field_editor>

                        {#if $ae_loc.trusted_access}
                            <!-- Sync button: overwrites person.affiliations with presenter.affiliations -->
                            <button
                                type="button"
                                onclick={async () => {
                                    console.log(
                                        '*** Sync affiliations button clicked ***'
                                    );
                                    if (
                                        !confirm(
                                            'Are you sure you want to sync the affiliations?'
                                        )
                                    ) {
                                        return false;
                                    }
                                    await api.update_ae_obj({
                                        api_cfg: $ae_api,
                                        obj_type: 'person',
                                        obj_id: $lq__event_presenter_obj.person_id,
                                        fields: {
                                            affiliations:
                                                $lq__event_presenter_obj.affiliations
                                        }
                                    });
                                    events_func.load_ae_obj_id__event_presenter(
                                        {
                                            api_cfg: $ae_api,
                                            event_presenter_id:
                                                $lq__event_presenter_obj?.event_presenter_id,
                                            log_lvl: 0
                                        }
                                    );
                                }}
                                class="btn btn-sm preset-tonal-warning group"
                                title="Use the affiliations from this presenter record to overwrite the person record.">
                                <RefreshCw size="1em" class="m-0.75" />
                                <span class="hidden group-hover:inline"
                                    >Sync</span>
                            </button>
                        {/if}
                    </div>
                {/if}
                {/if}
            </li>

            <li
                class:hidden={!$ae_loc.authenticated_access &&
                    !$lq__event_presenter_obj.professional_title}>
                <Element_ae_obj_field_editor
                    object_type={'event_presenter'}
                    object_id={$lq__event_presenter_obj?.event_presenter_id}
                    field_name={'professional_title'}
                    field_type={'text'}
                    current_value={$lq__event_presenter_obj.professional_title}
                    allow_null={true}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <Tag size="1em" />
                    {#if $lq__event_presenter_obj.professional_title && $lq__event_presenter_obj.professional_title.length}
                        <span class="font-bold">
                            {$lq__event_presenter_obj.professional_title}
                        </span>
                    {:else}
                        professional title
                        <!-- eslint-disable-next-line svelte/no-at-html-tags -->
                        {@html ae_snip.html__not_set}
                    {/if}
                </Element_ae_obj_field_editor>

                {#if $ae_loc.trusted_access && $ae_loc.edit_mode && $lq__event_presenter_obj.person_id && $lq__event_presenter_obj.person_professional_title != $lq__event_presenter_obj.professional_title}
                    <div>
                        <Element_ae_obj_field_editor
                            object_type={'person'}
                            object_id={$lq__event_presenter_obj.person_id}
                            field_name={'professional_title'}
                            field_type={'text'}
                            current_value={$lq__event_presenter_obj.person_professional_title}
                            allow_null={true}
                            on_success={() =>
                                events_func.load_ae_obj_id__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    log_lvl: 0
                                })}>
                            <Asterisk size="1em" />
                            <Tag size="1em" />
                            <span class="font-bold">
                                <!-- eslint-disable-next-line svelte/no-at-html-tags -->
                                {@html $lq__event_presenter_obj.person_professional_title &&
                                $lq__event_presenter_obj
                                    .person_professional_title.length
                                    ? $lq__event_presenter_obj.person_professional_title
                                    : 'professional title' +
                                      ae_snip.html__not_set}
                            </span>
                        </Element_ae_obj_field_editor>

                        {#if $ae_loc.trusted_access && $ae_loc.edit_mode}
                            <!-- Sync button: overwrites person.professional_title with presenter.professional_title -->
                            <button
                                type="button"
                                onclick={async () => {
                                    console.log(
                                        '*** Sync professional title button clicked ***'
                                    );
                                    if (
                                        !confirm(
                                            'Are you sure you want to sync the professional title?'
                                        )
                                    ) {
                                        return false;
                                    }
                                    await api.update_ae_obj({
                                        api_cfg: $ae_api,
                                        obj_type: 'person',
                                        obj_id: $lq__event_presenter_obj.person_id,
                                        fields: {
                                            professional_title:
                                                $lq__event_presenter_obj.professional_title
                                        }
                                    });
                                    events_func.load_ae_obj_id__event_presenter(
                                        {
                                            api_cfg: $ae_api,
                                            event_presenter_id:
                                                $lq__event_presenter_obj?.event_presenter_id,
                                            log_lvl: 0
                                        }
                                    );
                                }}
                                class="btn btn-sm preset-tonal-warning group"
                                title="Use the professional title from this presenter record to overwrite the person record.">
                                <RefreshCw size="1em" class="m-0.75" />
                                <span class="hidden group-hover:inline"
                                    >Sync</span>
                            </button>
                        {/if}
                    </div>
                {/if}
            </li>

            <li
                class:hidden={!$ae_loc.trusted_access ||
                    (!$ae_loc.edit_mode && !$ae_loc.manager_access)}>
                <UserCheck size="1em" />
                Person link:
                <!-- Allow for linking the presenter to a person record. -->
                {#if $ae_loc.trusted_access}
                    {#if !$lq__event_presenter_obj.person_id || $ae_loc.administrator_access}
                        <!-- No person linked yet (any trusted staff can assign) or re-linking (admin only).
                             WHY admin-only for re-link: staff were creating duplicate person records when
                             correcting initial link mistakes. "Add Person" below handles the first-time
                             case without that risk. -->
                        <Element_ae_obj_field_editor
                            object_type="event_presenter"
                            object_id={$lq__event_presenter_obj?.event_presenter_id}
                            field_name="person_id"
                            field_type="select"
                            current_value={$lq__event_presenter_obj.person_id}
                            select_options={$slct.person_obj_kv}
                            allow_null={$ae_loc.administrator_access}
                            on_open={load_person_options_for_presenter_link}
                            on_success={() =>
                                events_func.load_ae_obj_id__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    log_lvl: 0
                                })}>
                            {#if $lq__event_presenter_obj.person_id}
                                <a
                                    href="/core/person/{$lq__event_presenter_obj.person_id}"
                                    class="text-blue-500 hover:text-blue-800 hover:underline"
                                    title="View Person: {$lq__event_presenter_obj.person_full_name} {$lq__event_presenter_obj.person_id}">
                                    <Link size="1em" />
                                    {$lq__event_presenter_obj.person_id}
                                </a>
                            {:else}
                                <span class="inline-flex items-center gap-1 text-xs opacity-60">
                                    <Unlink size="1em" />
                                    person — not linked
                                </span>
                            {/if}
                        </Element_ae_obj_field_editor>
                    {:else}
                        <!-- Person already linked; non-admin staff see read-only. -->
                        <a
                            href="/core/person/{$lq__event_presenter_obj.person_id}"
                            class="text-blue-500 hover:text-blue-800 hover:underline"
                            title="View Person: {$lq__event_presenter_obj.person_full_name} {$lq__event_presenter_obj.person_id}">
                            <Link size="1em" />
                            {$lq__event_presenter_obj.person_id}
                        </a>
                    {/if}
                {/if}

                <!-- A sync button to use the person record fields to update the event_presenter fields -->
                {#if $ae_loc.administrator_access && $lq__event_presenter_obj?.person_id}
                    <button
                        type="button"
                        onclick={() => {
                            console.log('*** Sync person button clicked ***');
                            if (
                                !confirm(
                                    'Are you sure you want to sync from the person record?'
                                )
                            ) {
                                return false;
                            }

                            // NOTE: The external_id should not really be changed once it is set. The person.external_sys_id may need to be updated as well.
                            let event_presenter_data = {
                                external_id:
                                    $lq__event_presenter_obj.person_external_id,
                                given_name:
                                    $lq__event_presenter_obj.person_given_name,
                                family_name:
                                    $lq__event_presenter_obj.person_family_name,
                                professional_title:
                                    $lq__event_presenter_obj.person_professional_title,
                                affiliations:
                                    $lq__event_presenter_obj.person_affiliations,
                                email: $lq__event_presenter_obj.person_primary_email
                                // 'passcode': $lq__event_presenter_obj.person_passcode,
                            };

                            let person_update_result = (events_func as any)
                                .update_ae_obj__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presentation_id:
                                        $lq__event_presenter_obj?.event_presentation_id,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    data_kv: event_presenter_data,
                                    log_lvl: 0
                                })
                                .then(function (update_result: any) {
                                    // console.log(update_result);
                                    // return update_result;
                                });

                            return person_update_result;
                        }}
                        class="btn btn-sm preset-tonal-warning group"
                        title="Sync the person record fields to the presenter record. Person ID: {$lq__event_presenter_obj.person_id} to Presenter ID: {$lq__event_presenter_obj?.event_presenter_id}">
                        <RefreshCw size="1em" class="m-0.75" />
                        <span class="hidden group-hover:inline"
                            >Sync Person</span>
                    </button>
                {/if}

                {#if $ae_loc.trusted_access && !$lq__event_presenter_obj?.person_id}
                    <button
                        type="button"
                        onclick={async () => {
                            console.log('Add Person');
                            if ($ae_loc.administrator_access) {
                                if (
                                    !confirm(
                                        `Add a new person (${$lq__event_presenter_obj.given_name}) to the account? You will be able to edit their details after the person record is created.\n\n${$ae_loc.account_name}\nID: ${$slct.account_id}`
                                    )
                                ) {
                                    return;
                                }
                            } else {
                                if (
                                    !confirm(
                                        `Add a new person (${$lq__event_presenter_obj.given_name}) to the account based on this presenter? Be sure to check if there is an existing person record first.\n\n${$ae_loc.account_name}\nID: ${$slct.account_id}`
                                    )
                                ) {
                                    return;
                                }
                            }
                            let person_data = {
                                account_id: $slct.account_id,
                                source_code: 'manual:SK:presenter',
                                external_id:
                                    $lq__event_presenter_obj?.external_id ??
                                    null,
                                external_sys_id:
                                    $lq__event_presenter_obj?.external_id ??
                                    null,
                                // user_id: user_obj.user_id,
                                given_name:
                                    $lq__event_presenter_obj.given_name ??
                                    'New',
                                family_name:
                                    $lq__event_presenter_obj?.family_name ??
                                    null,
                                primary_email:
                                    $lq__event_presenter_obj?.email ?? null,
                                // code: $lq__event_presenter_obj?.code?? null,
                                // Random number between 100000 and 999999
                                passcode:
                                    Math.floor(Math.random() * 900000) + 100000,
                                professional_title:
                                    $lq__event_presenter_obj?.professional_title ??
                                    null,
                                affiliations:
                                    $lq__event_presenter_obj?.affiliations ??
                                    null,
                                enable: true
                            };

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

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

                            // We then need to update the event_presenter with the new person_id.
                            if (new_person_obj) {
                                events_func.update_ae_obj__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presentation_id:
                                        $lq__event_presenter_obj?.event_presentation_id,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    data_kv: {
                                        person_id: new_person_obj.person_id
                                    },
                                    log_lvl: 0
                                });
                            }
                        }}
                        class:hidden={!$ae_loc.edit_mode}
                        class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500"
                        title="Add a new person based on this presenter. Presenter ID: {$lq__event_presenter_obj?.event_presenter_id}">
                        <Plus size="1em" class="m-.75" />
                        Add Person
                    </button>
                {/if}
            </li>

            <li
                class:hidden={!$lq__event_presenter_obj.person_id ||
                    (!$ae_loc.trusted_access ||
                    (!$ae_loc.edit_mode && !$ae_loc.manager_access) &&
                        !events_auth_loc.current.auth__kv.presenter[$lq__event_presenter_obj?.event_presenter_id] &&
                        !events_auth_loc.current.auth__kv.presenter[$lq__event_presenter_obj?.email ?? ''])}>
                <Element_ae_obj_field_editor
                    object_type={'person'}
                    object_id={$lq__event_presenter_obj.person_id}
                    field_name={'passcode'}
                    field_type={'text'}
                    current_value={$lq__event_presenter_obj.person_passcode}
                    allow_null={true}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <Asterisk size="1em" />
                    <UserRound size="1em" />
                    Passcode:
                    <span class="font-bold">
                        {@html $lq__event_presenter_obj.person_passcode ??
                            ae_snip.html__not_set}
                    </span>
                </Element_ae_obj_field_editor>

                <!-- <span class="fas fa-user-secret"></span>
        {$lq__event_presenter_obj.person_passcode} (your passcode)

        <button type="button"
            title="Edit your passcode"
            class="btn btn-sm preset-tonal-warning"
            class:hidden={!$ae_loc.trusted_access}
            >
            <Pencil size="1em" aria-hidden="true" />
            Edit
        </button> -->
            </li>

            <li
                class:hidden={!$lq__event_presenter_obj.person_id ||
                    !$ae_loc.trusted_access ||
                    !$ae_loc.edit_mode}>
                <Element_ae_obj_field_editor
                    object_type={'person'}
                    object_id={$lq__event_presenter_obj.person_id}
                    field_name={'external_sys_id'}
                    field_type={'text'}
                    current_value={$lq__event_presenter_obj.person_external_sys_id}
                    allow_null={true}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_presenter({
                            api_cfg: $ae_api,
                            event_presenter_id:
                                $lq__event_presenter_obj?.event_presenter_id,
                            log_lvl: 0
                        })}>
                    <Asterisk size="1em" />
                    <FingerprintPattern size="1em" />
                    External System ID:
                    <span class="font-bold">
                        {@html $lq__event_presenter_obj.person_external_sys_id ??
                            ae_snip.html__not_set}
                    </span>
                </Element_ae_obj_field_editor>
            </li>

            <!-- The presenters biography. There should be a character counter. -->
            <li
                class:hidden={pres_mgmt_loc.current.hide__presenter_biography ||
                    (!$ae_loc.authenticated_access &&
                        !$lq__event_presenter_obj.biography)}>
                <div
                    class="label event_presenter__biography required space-y-4">
                    <!-- {#if clipboard_success}Copied!{:else}Copy Access Link{/if} -->
                    <!-- <span class="fas fa-copy mx-1"></span> -->
                    <MyClipboard
                        value={ae_tmp.biography?.trim()}
                        btn_text="Copy Biography Text"
                        btn_title="Copy the presenter biography text to the clipboard."
                        btn_class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500 float-right m-1"
                    ></MyClipboard>

                    <label for="presenter__biography" class="label">
                        <BookOpen size="1em" />
                        Presenter Biography
                        <span class="text-sm text-gray-500">
                            (75 to 100 words or 600 character limit)
                        </span>
                    </label>

                    <textarea
                        name="biography"
                        id="presenter__biography"
                        disabled={!$ae_loc.trusted_access &&
                            !events_auth_loc.current.auth__kv.presenter[$lq__event_presenter_obj?.event_presenter_id] &&
                            !events_auth_loc.current.auth__kv.presenter[$lq__event_presenter_obj?.email ?? '']}
                        class="textarea ae_value event_presenter__biography font-mono"
                        class:preset-tonal-error={ae_tmp.biography &&
                        ae_tmp.biography.length > 600
                            ? true
                            : false}
                        required
                        rows={!ae_tmp.biography ? 1 : 8}
                        cols="70"
                        bind:value={ae_tmp.biography}
                        placeholder="Enter brief biography here"></textarea>
                </div>

                {#if ae_tmp.biography}
                    <p>
                        Biography length: {ae_tmp.biography
                            ? ae_util.number_w_commas(ae_tmp.biography.length)
                            : 0} characters; {ae_tmp.biography
                            ? ae_util.number_w_commas(
                                  ae_util.count_words(ae_tmp.biography)
                              )
                            : 0} estimated words
                    </p>
                    <!-- <p>Biography length: </p> -->
                    <p>
                        The biography should be plain text only and be at most
                        100 words.
                    </p>
                    <!-- <p>1,250 characters is roughly 250 words</p> -->
                    <!-- <p>1,375 characters is roughly 250 to 300 words</p> -->
                {/if}

                <div class="flex flex-wrap items-center gap-2 p-1">
                    <button
                        type="button"
                        class="btn btn-md preset-tonal-primary hover:preset-filled-primary-500"
                        disabled={ae_tmp.biography ==
                            $lq__event_presenter_obj.biography}
                        onclick={() => {
                            console.log('*** Save button clicked ***');

                            let event_presenter_data = {
                                biography: ae_tmp.biography,
                                data_json: {
                                    ...$lq__event_presenter_obj.data_json,
                                    biography_updated_on:
                                        new Date().toISOString()
                                }
                            };

                            ae_promises.update__event_presenter_obj =
                                events_func
                                    .update_ae_obj__event_presenter({
                                        api_cfg: $ae_api,
                                        event_presentation_id:
                                            $lq__event_presenter_obj?.event_presentation_id,
                                        event_presenter_id:
                                            $lq__event_presenter_obj?.event_presenter_id,
                                        data_kv: event_presenter_data,
                                        log_lvl: 0
                                    })
                                    .then(function (update_result: any) {});
                        }}
                        class:hidden={!ae_tmp.biography ||
                            ae_tmp.biography?.length < 20}>
                        {#await ae_promises.update__event_presenter_obj}
                            <LoaderCircle
                                size="1em"
                                class="mx-1 animate-spin" />
                        {:then}
                            {#if ae_tmp.biography == $lq__event_presenter_obj.biography}
                                <Check size="1em" class="mx-1" />
                            {:else}
                                <Save size="1em" class="mx-1" />
                            {/if}
                        {/await}
                        Save Biography
                    </button>

                    {#if $lq__event_presenter_obj.data_json?.biography_updated_on}
                        <span class="text-sm text-gray-500">
                            Last saved: {ae_util.iso_datetime_formatter(
                                $lq__event_presenter_obj.data_json
                                    ?.biography_updated_on,
                                'datetime_12_long'
                            )}
                        </span>
                    {/if}
                </div>
            </li>
        </ul>
    </section>
{/if}
