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

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

    // Imports (external and then internal)
    // import type { key_val } from '$lib/stores/ae_stores';
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import Element_data_store from '$lib/elements/element_data_store_v3.svelte';

    import { liveQuery } from 'dexie';
    import { Modal } from 'flowbite-svelte';
    // import { core_func } from '$lib/ae_core_functions';
    import { db_events } from '$lib/ae_events/db_events';
    import {
        ae_snip,
        ae_loc,
        ae_sess,
        ae_api,
        ae_trig,
        slct,
        slct_trigger
    } from '$lib/stores/ae_stores';
    import {
        events_loc,
        events_sess,
        events_slct,
        events_trigger
    } from '$lib/stores/ae_events_stores';
    import { events_func } from '$lib/ae_events_functions';

    import Comp_event_files_upload from '../../../../ae_comp__event_files_upload.svelte';
    import Element_manage_event_file_li_wrap from '$lib/elements/element_manage_event_file_li_direct.svelte';
    import Comp_event_presenter_form_agree from './ae_comp__event_presenter_form_agree.svelte';
    import Presenter_view from './presenter_view.svelte';
    import Presenter_page_menu from './presenter_page_menu.svelte';
    import MyClipboard from '$lib/app_components/e_app_clipboard.svelte';

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

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

    $ae_loc.url_origin = data.url.origin;

    $events_slct.event_presenter_id = ae_acct.slct.event_presenter_id;
    // $events_slct.event_presenter_obj = ae_acct.slct.event_presenter_obj;
    $events_slct.event_file_obj_li = ae_acct.slct.event_file_obj_li;

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

    let lq__event_obj = $derived(
        liveQuery(async () => {
            let results = await db_events.event.get(ae_acct.slct.event_id);

            return results;
        })
    );
    let lq__event_presenter_obj = $derived(
        liveQuery(async () => {
            let results = await db_events.presenter.get(
                ae_acct.slct.event_presenter_id
            );

            return results;
        })
    );

    let lq__event_presentation_obj = $derived(
        liveQuery(async () => {
            let results = await db_events.presentation.get(
                ae_acct.slct.event_presentation_id
            );

            return results;
        })
    );
    let lq__auth__event_presenter_obj = $derived(
        liveQuery(async () => {
            let results = await db_events.presenter.get(
                $events_loc.auth__person?.presenter_id ?? null
            );

            return results;
        })
    );

    // if (browser && $lq__event_presenter_obj) {
    //     console.log('Pres Mgmt [page]: +presenter.svelte');
    //     $events_slct.event_presenter_obj = $lq__event_presenter_obj;
    //     console.log(`$events_slct.event_presenter_obj = `, $events_slct.event_presenter_obj);
    // }

    // *** Functions and Logic
</script>

<svelte:head>
    <title>
        Presenter: {ae_util.shorten_string({
            string: $lq__event_presenter_obj?.full_name,
            max_length: 20,
            begin_length: 10,
            end_length: 4
        })}
        ({$lq__event_presenter_obj?.event_presenter_id ?? 'loading...'}) - Pres
        Mgmt - {$events_loc?.title}
    </title>
</svelte:head>

<section
    class="
        ae_events_pres_mgmt_event_presenter
        md:container
        flex flex-col gap-1
        items-center
        justify-start
        mx-auto
        py-1 px-2 pb-16
        h-full
        min-w-full
        max-w-max
        "
>
    <Presenter_page_menu {data} {lq__event_obj} {lq__event_presenter_obj} />

    {#if !$lq__event_presenter_obj}
        <div>
            <span class="fas fa-spinner fa-spin mx-1"></span>
            <span>Loading presenter information...</span>
        </div>
    {:else if $lq__event_presenter_obj?.enable || $ae_loc.trusted_access}
        <header class="ae_module_header">
            <span
                class="flex flex-row flex-wrap gap-1 items-center justify-center"
            >
                <span class="fas fa-user m-1 text-neutral-800/80"></span>
                <!-- Button to toggle between the regular presenter view and managing presenter files -->
                <button
                    type="button"
                    onclick={() => {
                        if (
                            $events_loc.pres_mgmt
                                .show_content__presenter_view == 'manage_files'
                        ) {
                            $events_loc.pres_mgmt.show_content__presenter_view =
                                null;
                        } else {
                            $events_loc.pres_mgmt.show_content__presenter_view =
                                'manage_files';
                        }
                    }}
                    class="btn btn-md hover:preset-filled-secondary-500"
                    class:preset-filled-secondary-500={$events_loc.pres_mgmt
                        .show_content__presenter_view == 'manage_files'}
                    class:preset-filled-tertiary-500={$events_loc.pres_mgmt
                        .show_content__presenter_view != 'manage_files'}
                    class:hidden={!$ae_loc.authenticated_access}
                    title="View presenter information or manage files for the presenter"
                >
                    {#if $events_loc.pres_mgmt.show_content__presenter_view == 'manage_files'}
                        <span class="fas fa-info m-1"></span>
                        <!-- View Details -->
                        Presenter Info?
                    {:else}
                        <span class="fas fa-file-archive m-1"></span>
                        Presenter Files?
                        <span
                            class="badge preset-tonal-success"
                            class:hidden={!$lq__event_presenter_obj?.file_count}
                        >
                            <!-- absolute -top-1.5 -right-1.5 z-10 -->
                            <span class="fas fa-file-alt m-1"></span>
                            {$lq__event_presenter_obj?.file_count}×
                        </span>
                    {/if}
                </button>
            </span>

            <!-- <span class="grow flex flex-row flex-wrap gap-1 items-center justify-around"> -->
            <h2
                class="text-2xl font-bold text-center max-w-xs sm:max-w-lg md:max-w-2xl"
                title="{$lq__event_presenter_obj?.full_name} ID: {$lq__event_presenter_obj?.event_presenter_id}"
            >
                {@html $lq__event_presenter_obj?.full_name ??
                    ae_snip.html__not_set}
                <!-- <span class="text-sm text-gray-600 dark:text-gray-400">
            Presenter ID: {$lq__event_presenter_obj?.event_presenter_id}
        </span> -->
            </h2>

            <span
                class="flex flex-col gap-0.25 items-end justify-center font-normal"
            >
                <span class="text-sm text-gray-600 dark:text-gray-400">
                    {#if !$ae_loc.trusted_access && !$events_loc.auth__kv.presenter[$lq__event_presenter_obj?.event_presenter_id] && !$events_loc.auth__kv.session[$lq__event_presenter_obj.event_session_id]}
                        <!-- Only show the domain name of the email address. -->
                        <!-- ( -->
                        <!-- {$lq__event_presenter_obj.email.replace(/@.*$/, '@...')} -->
                        <!-- {$lq__event_presenter_obj.person_primary_email.substring(0, 1) + '...@example.com'} -->

                        <!-- ) -->
                        <!-- {@html $lq__event_presenter_obj?.person_primary_email ? $lq__event_presenter_obj?.person_primary_email.replace(/^(.{3}).*@/, '$1...@') : 'email'+ae_snip.html__not_set} -->
                        <!-- ) -->
                        Not signed in as presenter
                        {#if $lq__event_presenter_obj?.person_primary_email}
                            ({$lq__event_presenter_obj.person_primary_email.replace(
                                /^(.{3}).*@/,
                                '$1...@'
                            )})
                        {:else}
                            <!-- email
                    {ae_snip.html__not_set} -->
                        {/if}
                    {:else}
                        ({@html $lq__event_presenter_obj?.person_primary_email &&
                        $lq__event_presenter_obj?.person_primary_email.length
                            ? $lq__event_presenter_obj?.person_primary_email
                            : 'email ' + ae_snip.html__not_set})
                    {/if}
                </span>

                <span
                    class="flex flex-row flex-wrap gap-0.25 items-center justify-center"
                >
                    {#if $lq__event_presenter_obj.person_id && $ae_loc.trusted_access}
                        <!-- A button to copy the access link to the clipboard. -->
                        <!-- Example: /events/CHs3F44Xq76/session/Wh8UnJlbIA0?person_id=fV1dl_IJ0yY&person_pass=abc123 -->

                        <!-- {#snippet btn_text()}
                    <span class="fas fa-copy m-1"></span>
                    Copy Access Link
                {/snippet} -->
                        <MyClipboard
                            value={encodeURI(
                                `${$ae_loc.url_origin}/events/${$lq__event_presenter_obj.event_id}/session/${$lq__event_presenter_obj.event_session_id}?person_id=${$lq__event_presenter_obj.person_id}&person_pass=${$lq__event_presenter_obj.person_passcode}&presentation_id=${$lq__event_presenter_obj?.event_presentation_id}&presenter_id=${$lq__event_presenter_obj?.event_presenter_id}`
                            )}
                            btn_text="Copy Access Link"
                            btn_title="Copy the presenter access link to the clipboard."
                            btn_class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500 border border-warning-500 hover:preset-filled-warning-500"
                        ></MyClipboard>
                    {/if}

                    {#if $events_loc.pres_mgmt?.require__presenter_agree && $events_loc?.pres_mgmt?.show__email_access_link && $lq__event_presenter_obj?.person_primary_email && ($ae_loc.public_access || !$events_loc.auth__person?.id)}
                        <button
                            type="button"
                            onclick={() => {
                                console.log('Email the access link');
                                if (
                                    !$lq__event_presenter_obj.person_primary_email
                                ) {
                                    alert(
                                        'No email address found for this presenter.'
                                    );
                                    return;
                                }
                                if (
                                    confirm(
                                        `This will send the sign in email to ${$lq__event_presenter_obj.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_presenter({
                                    api_cfg: $ae_api,
                                    to_email:
                                        $lq__event_presenter_obj?.person_primary_email,
                                    to_name:
                                        $lq__event_presenter_obj?.full_name ??
                                        '-- not set --',
                                    base_url: $ae_loc.url_origin,
                                    person_id:
                                        $lq__event_presenter_obj?.person_id,
                                    person_passcode:
                                        $lq__event_presenter_obj?.person_passcode ??
                                        '-- not set --',
                                    event_id:
                                        $lq__event_presenter_obj?.event_id,
                                    event_session_id:
                                        $lq__event_presenter_obj?.event_session_id,
                                    event_presentation_id:
                                        $lq__event_presenter_obj?.event_presentation_id,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    session_name:
                                        $lq__event_presenter_obj?.event_session_name ??
                                        '-- not set --',
                                    presentation_name:
                                        $lq__event_presenter_obj?.event_presentation_name ??
                                        '-- not set --'
                                });
                            }}
                            class="btn btn-sm preset-tonal-secondary border border-secondary-500 hover:preset-filled-secondary-500 m-0.25"
                            title="Email the access link to the presenter"
                        >
                            <span class="fas fa-envelope m-1"></span>
                            Email Access Link
                        </button>
                    {/if}
                </span>
            </span>
        </header>

        {#if !$events_loc.pres_mgmt.show_content__presenter_view || ($events_loc.pres_mgmt.show_content__presenter_view == 'default' && $lq__event_presenter_obj)}
            <Presenter_view
                {lq__event_presenter_obj}
                {lq__event_presentation_obj}
            />

            {#if $ae_loc.trusted_access || $lq__auth__event_presenter_obj?.agree}
                <div
                    class="m-1 flex flex-col flex-wrap gap-1 items-center justify-center w-full"
                >
                    <!-- 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}
                        class_li="w-fit max-w-(--breakpoint-lg) flex flex-row gap-1"
                        show_edit={false}
                        show_edit_btn={true}
                        mount_reload_sec={1}
                    />
                </div>
            {/if}

            <h3 class="h5 text-center">
                <span class="fas fa-tasks m-1 text-neutral-800/80"></span>
                <span class="fas fa-mail-bulk m-1 text-neutral-800/80"></span>
                Manage and Upload Presenter Files
                <span
                    class="badge preset-tonal-success"
                    class:hidden={!$lq__event_presenter_obj?.file_count}
                >
                    <span class="fas fa-file-alt m-1"></span>
                    {$lq__event_presenter_obj?.file_count}×
                </span>
            </h3>

            <!-- Yes... This is a duplicate of what is shown when they press "Presenter Files" button. It can be cleaned up later. -->
            {#if $ae_loc.trusted_access || $events_loc.auth__kv.presenter[$lq__event_presenter_obj?.event_presenter_id]}
                <Comp_event_files_upload
                    class_li="border border-gray-300 rounded-md p-2 bg-gray-100 hover:bg-gray-200"
                    link_to_type="event_presenter"
                    link_to_id={$lq__event_presenter_obj?.event_presenter_id}
                >
                    {#snippet label()}
                        <span>
                            <div class="text-lg">
                                <span class="fas fa-upload"></span>
                                <strong class=""
                                    >Upload presenter (speaker) specific files</strong
                                >
                            </div>
                            <div
                                class="text-sm text-gray-600 dark:text-gray-400 italic"
                            >
                                <strong
                                    >Presenter (speaker) presentation files only</strong
                                ><br />
                                Recommended: PowerPoint (pptx) or Keynote (key)<br
                                />
                                Media: Audio and videos files should be directly embedded
                                in PowerPoint (PPTX) files<br />
                                Supplemental files: mp4, PDF, Word Doc, Excel, txt,
                                etc
                            </div>
                        </span>
                    {/snippet}
                </Comp_event_files_upload>
            {/if}

            <div class="overflow-x-auto w-max max-w-full">
                <Element_manage_event_file_li_wrap
                    link_to_type={'event_presenter'}
                    link_to_id={$lq__event_presenter_obj?.event_presenter_id}
                    allow_basic={$events_loc.auth__kv.presenter[
                        $lq__event_presenter_obj?.event_presenter_id
                    ] ||
                        $events_loc.auth__kv.presenter[
                            $lq__event_presenter_obj?.event_presenter_id
                        ]}
                    allow_moderator={$events_loc.auth__kv.presenter[
                        $lq__event_presenter_obj?.event_presenter_id
                    ]}
                    container_class_li={''}
                />
            </div>
        {:else if $events_loc.pres_mgmt.show_content__presenter_view == 'manage_files' && $ae_loc.authenticated_access}
            <div>
                <h3 class="h5 text-center">
                    <span class="fas fa-tasks m-1 text-neutral-800/80"></span>
                    <span class="fas fa-mail-bulk m-1 text-neutral-800/80"
                    ></span>
                    Manage and Upload Presenter Files
                    <span
                        class="badge preset-tonal-success"
                        class:hidden={!$lq__event_presenter_obj?.file_count}
                    >
                        <span class="fas fa-file-alt m-1"></span>
                        {$lq__event_presenter_obj?.file_count}×
                    </span>
                </h3>

                {#if $ae_loc.public_access || $events_loc.auth__kv.presenter[$lq__event_presenter_obj?.event_presenter_id]}
                    <Comp_event_files_upload
                        class_li="border border-gray-300 rounded-md p-2 bg-gray-100 hover:bg-gray-200"
                        link_to_type="event_presenter"
                        link_to_id={$lq__event_presenter_obj.event_presenter_id}
                    >
                        {#snippet label()}
                            <span>
                                <div class="text-lg">
                                    <span class="fas fa-upload"></span>
                                    <strong class=""
                                        >Upload presenter (speaker) specific
                                        files</strong
                                    >
                                </div>
                                <div
                                    class="text-sm text-gray-600 dark:text-gray-400 italic"
                                >
                                    <strong
                                        >Presentation related files only</strong
                                    ><br />
                                    Recommended: PowerPoint (pptx) or Keynote (key)<br
                                    />
                                    Media: Audio and videos files should be directly
                                    embedded in PowerPoint (PPTX) files<br />
                                    Supplemental files: mp4, PDF, Word Doc, Excel,
                                    txt, etc
                                </div>
                            </span>
                        {/snippet}
                    </Comp_event_files_upload>
                {/if}

                <div class="overflow-x-auto w-max max-w-full">
                    <Element_manage_event_file_li_wrap
                        link_to_type={'event_presenter'}
                        link_to_id={$lq__event_presenter_obj?.event_presenter_id}
                        allow_basic={$ae_loc.public_access ||
                            $events_loc.auth__kv.presenter[
                                $lq__event_presenter_obj?.event_presenter_id
                            ]}
                        allow_moderator={$events_loc.auth__kv.presenter[
                            $lq__event_presenter_obj?.event_presenter_id
                        ]}
                        container_class_li={''}
                    />
                </div>
            </div>

            <!-- Show message if the presenter has agreed -->
            <!-- {#if
        ($ae_loc.trusted_access ||
        $lq__auth__event_presenter_obj?.agree)
        }
        <div class="m-1 flex flex-col flex-wrap gap-1 items-center justify-center w-full">
        <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}
            class_li="w-fit max-w-(--breakpoint-lg) flex flex-row gap-1"
            show_edit={false}
            show_edit_btn={true}
            mount_reload_sec={1}
            />
        </div>
    {/if} -->
        {/if}
    {:else}
        <div class="bg-red-100 p-4 border border-red-200 rounded-md">
            <h2 class="h3">
                <span class="fas fa-exclamation-triangle text-red-500 m-1"
                ></span>
                Presenter Disabled
            </h2>
            <p>
                This presenter is currently disabled. Please contact the event
                organizer for more information.
            </p>
        </div>
    {/if}
</section>

<!-- Main modal -->
<Modal
    title="{$lq__event_presenter_obj?.full_name} Presenter Consent and Release and Terms and Conditions"
    bind:open={$events_sess.pres_mgmt.show_modal__presenter_agree}
    autoclose={false}
    placement="top-center"
    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} />

    {#snippet footer()}
        <div class="text-center w-full">
            <button
                type="button"
                onclick={() => {
                    $events_sess.pres_mgmt.show_modal__presenter_agree = false;
                }}
                class="btn btn-sm preset-tonal-warning hover:preset-tonal-warning border border-warning-500"
            >
                <span class="fas fa-times m-1"></span>
                Close
            </button>
        </div>
    {/snippet}
</Modal>

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

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

    min-height: 30%;
    min-width: 80%;
} */
</style>
