<script lang="ts">
import { untrack } from 'svelte';
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.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_MODULE_TITLE,
    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 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 './ae_comp__presenter_view.svelte';
import Presenter_page_menu from './ae_comp__presenter_page_menu.svelte';
import MyClipboard from '$lib/app_components/e_app_clipboard.svelte';
import {
    Archive,
    FileText,
    Info,
    Link,
    ListChecks,
    LoaderCircle,
    Mail,
    Mails,
    TriangleAlert,
    Upload,
    User,
    X
} from '@lucide/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.
let ae_acct = $derived(data[data.account_id]);

$effect(() => {
    if (!ae_acct) return;
    untrack(() => {
        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;
    })
);

// Sync server-side pres_mgmt config into local PersistedState.
// WHY: this page is often reached directly by URL (e.g. a presenter's sign-in
// link) without first visiting the pres_mgmt overview or a session page —
// the only other places this sync runs. Without it, pres_mgmt_loc.current
// keeps stale defaults (e.g. show__presenter_qr=false) even after the admin
// has enabled a feature globally via the Config page.
$effect(() => {
    const remote_cfg = $lq__event_obj?.mod_pres_mgmt_json;
    if (remote_cfg) {
        untrack(() => {
            events_func.sync_config__event_pres_mgmt({
                pres_mgmt_cfg_remote: remote_cfg,
                log_lvl: 0
            });
        });
    }
});

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;
    })
);
// True if this person is authed as the presenter for this specific record.
// Checks four signals in priority order:
//   1. Trusted staff — always authed.
//   2. Exact presenter ID in auth__kv.presenter — direct grant from sign-in link.
//   3. Email key in auth__kv.presenter — expand_auth_for_person keys by email so a
//      presenter signed into ONE presentation auto-grants access to any OTHER presenter
//      record that shares the same email address (e.g. same person in two sessions).
//      Matches the same check used in ae_comp__event_presenter_obj_li.svelte.
//   4. Session-level read access — signed in as a session POC or presenter for this session.
//   5. Direct person_id identity — signed in as this person_id (string ID match).
let presenter_is_authed = $derived(
    $ae_loc.trusted_access ||
    !!events_auth_loc.current.auth__kv.presenter[$lq__event_presenter_obj?.event_presenter_id ?? ''] ||
    !!($lq__event_presenter_obj?.email && 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 ?? ''] ||
    (
        !!events_auth_loc.current.auth__person.id &&
        events_auth_loc.current.auth__person.id === $lq__event_presenter_obj?.person_id
    )
);

// True when the admin's "Require Presenter Agreement" setting (if on) is satisfied —
// either the requirement is off, the presenter has agreed, or staff is managing this
// on their behalf. Trusted staff always bypass it, same as the "agreed" message above.
// WHY this exists separately from presenter_is_authed: a presenter can be signed in
// (authed) without having agreed yet — being signed in must not be enough to upload
// when an agreement is required. See TODO__Agents.md "Presenter agreement not enforced
// before file upload".
let presenter_agree_ok = $derived(
    $ae_loc.trusted_access ||
    !pres_mgmt_loc.current.require__presenter_agree ||
    !!$lq__event_presenter_obj?.agree
);

// The actual gate for showing/using the upload UI — signed in AND (if required) agreed.
let presenter_can_upload = $derived(presenter_is_authed && presenter_agree_ok);

// Build the presenter sign-in URL. person_id is included only when there's a real Person
// record — for email-only presenters (no Person record, person_id is null) the sign-in
// handler derives identity from presenter_id via Dexie lookup.
let presenter_sign_in_url = $derived((() => {
    if (!$lq__event_presenter_obj) return '';
    const base = `${$ae_loc.url_origin}/events/${$lq__event_presenter_obj.event_id}/session/${$lq__event_presenter_obj.event_session_id}`;
    const parts: string[] = [];
    if ($lq__event_presenter_obj.person_id) parts.push(`person_id=${encodeURIComponent($lq__event_presenter_obj.person_id)}`);
    parts.push(`person_pass=${encodeURIComponent($lq__event_presenter_obj.person_passcode ?? $lq__event_presenter_obj.passcode ?? '')}`);
    parts.push(`presentation_id=${encodeURIComponent($lq__event_presenter_obj.event_presentation_id ?? '')}`);
    parts.push(`presenter_id=${encodeURIComponent($lq__event_presenter_obj.event_presenter_id ?? '')}`);
    return `${base}?${parts.join('&')}`;
})());

// 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_MODULE_TITLE}
    </title>
</svelte:head>

<div class="ae_events_pres_mgmt_event_presenter mx-auto w-full max-w-7xl">
    <Presenter_page_menu {lq__event_obj} {lq__event_presenter_obj} />

    {#if !$lq__event_presenter_obj}
        <div>
            <LoaderCircle size="1em" class="mx-1 animate-spin" />
            <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 items-center justify-center gap-1">
                <User size="1em" class="m-1 text-neutral-800/80" />
                <!-- Button to toggle between the regular presenter view and managing presenter files -->
                <button
                    type="button"
                    onclick={() => {
                        if (
                            pres_mgmt_loc.current.show_content__presenter_view == 'manage_files'
                        ) {
                            pres_mgmt_loc.current.show_content__presenter_view =
                                null;
                        } else {
                            pres_mgmt_loc.current.show_content__presenter_view =
                                'manage_files';
                        }
                    }}
                    class="btn btn-md hover:preset-filled-secondary-500"
                    class:preset-filled-secondary-500={pres_mgmt_loc.current.show_content__presenter_view == 'manage_files'}
                    class:preset-filled-tertiary-500={pres_mgmt_loc.current.show_content__presenter_view != 'manage_files'}
                    class:hidden={!$ae_loc.authenticated_access}
                    title="View presenter information or manage files for the presenter">
                    {#if pres_mgmt_loc.current.show_content__presenter_view == 'manage_files'}
                        <Info size="1em" class="m-1" />
                        <!-- View Details -->
                        Presenter Info?
                    {:else}
                        <Archive size="1em" class="m-1" />
                        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 -->
                            <FileText size="1em" class="m-1" />
                            {$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="max-w-xs text-center text-2xl font-bold 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 items-end justify-center gap-0.25 font-normal">
                <span class="text-sm text-gray-600 dark:text-gray-400">
                    {#if !presenter_is_authed}
                        <!-- 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 items-center justify-center gap-0.25">
                    {#if ($lq__event_presenter_obj.person_id || $lq__event_presenter_obj.email) && $ae_loc.trusted_access}
                        <!-- A button to copy the access link to the clipboard. -->
                        <!-- person_id is omitted for email-only presenters — the sign-in
                             handler derives their identity via presenter_id + Dexie lookup. -->
                        <MyClipboard
                            value={presenter_sign_in_url}
                            btn_text="Copy Access Link"
                            btn_title="Copy the presenter access link to the clipboard."
                            btn_class="btn btn-sm preset-tonal-secondary hover:preset-filled-secondary-500 border border-secondary-500 hover:preset-filled-secondary-500"
                            hide_icon={true}
                            hide_text={true}
                            >
                            <Link size="1em" class="" />
                            Copy Link
                        </MyClipboard>
                    {/if}

                    {#if pres_mgmt_loc.current.show__email_access_link && ($lq__event_presenter_obj?.person_primary_email || $lq__event_presenter_obj?.email)}
                        <button
                            type="button"
                            onclick={() => {
                                // WHY: prefer the Person-record email (person_primary_email) when
                                // available — it is the verified/canonical address. Fall back to
                                // presenter.email (from the spreadsheet import) for the ~75% of
                                // LCI presenters who have no Person record in iMIS.
                                const use_email = $lq__event_presenter_obj.person_primary_email ?? $lq__event_presenter_obj.email;
                                // null for email-only presenters — email function omits person_id from URL; sign-in derives identity from presenter_id
                                const use_person_id = $lq__event_presenter_obj.person_id;
                                const use_passcode = $lq__event_presenter_obj.person_passcode ?? $lq__event_presenter_obj.passcode;

                                if (!use_email) {
                                    alert('No email address found for this presenter.');
                                    return;
                                }
                                const display_email = $ae_loc.trusted_access
                                    ? use_email
                                    : ae_util.obscure_email(use_email);
                                if (!confirm(`This will send the sign in email to ${display_email}`)) {
                                    return;
                                }

                                events_func.email_sign_in__event_presenter({
                                    api_cfg: $ae_api,
                                    to_email: use_email,
                                    to_name:
                                        $lq__event_presenter_obj?.full_name ??
                                        '-- not set --',
                                    base_url: $ae_loc.url_origin,
                                    person_id: use_person_id,
                                    person_passcode: use_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-secondary-500 hover:preset-filled-secondary-500 m-0.25 border"
                            title="Email the access link to {$lq__event_presenter_obj?.full_name ?? 'presenter'} ({$ae_loc.trusted_access ? ($lq__event_presenter_obj?.person_primary_email ?? $lq__event_presenter_obj?.email ?? 'no email on file') : ae_util.obscure_email($lq__event_presenter_obj?.person_primary_email ?? $lq__event_presenter_obj?.email)})">
                            <Mail size="1em" class="" />
                            <Link size="1em" class="" />
                            Email Access Link
                        </button>
                    {/if}
                </span>
            </span>
        </header>

        {#if !pres_mgmt_loc.current.show_content__presenter_view || (pres_mgmt_loc.current.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__event_presenter_obj?.agree}
                <div
                    class="m-1 flex w-full flex-col flex-wrap items-center justify-center gap-1">
                    <!-- 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">
                <ListChecks size="1em" class="m-1 text-neutral-800/80" />
                <Mails size="1em" class="m-1 text-neutral-800/80" />
                Manage and Upload Presenter Files
                <span
                    class="badge preset-tonal-success"
                    class:hidden={!$lq__event_presenter_obj?.file_count}>
                    <FileText size="1em" class="m-1" />
                    {$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 presenter_can_upload}
                <Comp_event_files_upload
                    class_li="border border-surface-200-800 rounded-xl p-4 bg-surface-50-900 hover:bg-surface-100-900 transition-colors duration-200"
                    link_to_type="event_presenter"
                    link_to_id={$lq__event_presenter_obj?.event_presenter_id}>
                    {#snippet label()}
                        <span>
                            <div class="text-lg">
                                <Upload size="1em" />
                                <strong class=""
                                    >Upload presenter (speaker) specific files</strong>
                            </div>
                            <div class="text-sm italic opacity-60">
                                <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>
            {:else if presenter_is_authed}
                <p class="bg-warning-100 border-warning-300 text-warning-800 flex items-center gap-2 rounded-md border p-3 text-sm">
                    <TriangleAlert size="1em" class="flex-none" />
                    File upload is locked until you agree to the presenter terms — see the
                    Agreed/Not Agreed action in the Options menu above.
                </p>
            {/if}

            <div class="w-max max-w-full overflow-x-auto">
                <Element_manage_event_file_li_wrap
                    link_to_type={'event_presenter'}
                    link_to_id={$lq__event_presenter_obj?.event_presenter_id}
                    allow_basic={presenter_can_upload}
                    allow_moderator={presenter_can_upload}
                    container_class_li={''} />
            </div>
        {:else if pres_mgmt_loc.current.show_content__presenter_view == 'manage_files' && $ae_loc.authenticated_access}
            <div>
                <h3 class="h5 text-center">
                    <ListChecks size="1em" class="m-1 text-neutral-800/80" />
                    <Mails size="1em" class="m-1 text-neutral-800/80" />
                    Manage and Upload Presenter Files
                    <span
                        class="badge preset-tonal-success"
                        class:hidden={!$lq__event_presenter_obj?.file_count}>
                        <FileText size="1em" class="m-1" />
                        {$lq__event_presenter_obj?.file_count}×
                    </span>
                </h3>

                {#if presenter_can_upload || ($ae_loc.public_access && presenter_agree_ok)}
                    <Comp_event_files_upload
                        class_li="border border-surface-200-800 rounded-xl p-4 bg-surface-50-900 hover:bg-surface-100-900 transition-colors duration-200"
                        link_to_type="event_presenter"
                        link_to_id={$lq__event_presenter_obj.event_presenter_id}>
                        {#snippet label()}
                            <span>
                                <div class="text-lg">
                                    <Upload size="1em" />
                                    <strong class=""
                                        >Upload presenter (speaker) specific
                                        files</strong>
                                </div>
                                <div class="text-sm italic opacity-60">
                                    <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>
                {:else if presenter_is_authed}
                    <p class="bg-warning-100 border-warning-300 text-warning-800 flex items-center gap-2 rounded-md border p-3 text-sm">
                        <TriangleAlert size="1em" class="flex-none" />
                        File upload is locked until you agree to the presenter terms — see the
                        Agreed/Not Agreed action in the Options menu above.
                    </p>
                {/if}

                <div class="w-max max-w-full overflow-x-auto">
                    <Element_manage_event_file_li_wrap
                        link_to_type={'event_presenter'}
                        link_to_id={$lq__event_presenter_obj?.event_presenter_id}
                        allow_basic={presenter_can_upload || ($ae_loc.public_access && presenter_agree_ok)}
                        allow_moderator={presenter_can_upload}
                        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="rounded-md border border-red-200 bg-red-100 p-4">
            <h2 class="h3">
                <TriangleAlert size="1em" class="m-1 text-red-500" />
                Presenter Disabled
            </h2>
            <p>
                This presenter is currently disabled. Please contact the event
                organizer for more information.
            </p>
        </div>
    {/if}
</div>

<!-- Presenter agree modal -->
<Modal
    title="{$lq__event_presenter_obj?.full_name} — Presenter Agreement"
    bind:open={$events_sess.pres_mgmt.show_modal__presenter_agree}
    autoclose={false}
    placement="center"
    size="lg"
    >
    <Comp_event_presenter_form_agree {lq__event_presenter_obj} />

    {#snippet footer()}
        <div class="w-full text-center">
            <button
                type="button"
                onclick={() => ($events_sess.pres_mgmt.show_modal__presenter_agree = false)}
                class="btn preset-tonal-warning border border-warning-500">
                <X size="1em" class="mr-1" />
                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>
