<script lang="ts">
interface Props {
    log_lvl?: number;
    container_class_li?: string | Array<string>;
    display_mode?: string; // 'default', 'compact', 'minimal', 'launcher'
    link_to_type: string;
    link_to_id: string;
    lq__event_presenter_obj_li: any;
}

let {
    log_lvl = 0,
    container_class_li = [],
    display_mode = 'default',
    link_to_type,
    link_to_id,
    lq__event_presenter_obj_li
}: Props = $props();

// Imports
import type { key_val } from '$lib/stores/ae_stores';
// import Element_data_store from '$lib/element_data_store.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 {
    events_sess,
    events_slct,
    events_trigger,
    events_trig_kv
} 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 { ae_util } from '$lib/ae_utils/ae_utils';
import {
    Check,
    FileText,
    ListOrdered,
    Mail,
    Plus,
    RefreshCw,
    Star,
    User,
    UserX,
    Users,
    X
} from '@lucide/svelte';
$effect(() => {
    if (log_lvl) {
        console.log(`link_to_type: ${link_to_type}; link_to_id: ${link_to_id}`);
    }
});

// Variables
// let ae_promises: key_val = {};
let ae_tmp: key_val = $state({});
// let ae_triggers: key_val = {};

// *** Functions and Logic

</script>

<div class="float-right flex flex-row items-center">
    <button
        type="button"
        onclick={() => {
            console.log('*** Refresh button clicked ***');
            ae_tmp.show__file_li = false;
            console.log(
                `$lq__event_presenter_obj_li:`,
                $lq__event_presenter_obj_li
            );
            events_func.load_ae_obj_li__event_presenter({
                api_cfg: $ae_api,
                for_obj_type: link_to_type,
                for_obj_id: link_to_id,
                log_lvl: log_lvl
            });
        }}
        class="btn btn-sm preset-tonal-tertiary hover:preset-tonal-warning border-warning-500 m-1 border p-1 transition hover:transition-all *:hover:inline"
        class:hidden={!$ae_loc.edit_mode ||
            !$ae_loc.trusted_access ||
            display_mode != 'default'}
        title="Refresh the list of presenters">
        <RefreshCw size="1em" class="m-1" />
        <span class="hidden"> Presenters </span>
    </button>
</div>

<section
    class="ae_comp event_presenter_obj_li container w-full min-w-full space-y-2 overflow-x-auto px-0.5 py-2 {container_class_li}">
    <h3
        class:hidden={$lq__event_presenter_obj_li?.length < 2 &&
            !$ae_loc.edit_mode}
        class="h5 text-success-800-400">
        <span class="text-sm">
            Presenters:

            {#if $lq__event_presenter_obj_li?.length}
                <span
                    class="preset-filled-surface-300-700 rounded-lg px-4 text-xl font-bold"
                    title="Count {$lq__event_presenter_obj_li.length ??
                        'None'}">
                    <ListOrdered size=".9em" class="text-surface-800-200" />
                    {$lq__event_presenter_obj_li.length ?? 'None'}&times;
                </span>
            {/if}

            <!-- {#if !$lq__event_presenter_obj_li?.length}
        <span class="text-sm text-gray-500">
            No presenters available to show at this time
        </span>
    {/if} -->
        </span>
    </h3>

    <!-- Show presenters for this LiveQuery -->
    <ul class="m-2 space-y-1 px-4">
        {#each $lq__event_presenter_obj_li ?? [] as event_presenter_obj (event_presenter_obj.event_presenter_id)}
            <!-- This is a hack. I can not get the LiveQuery to work with specific presentation IDs. It only works with the session ID. I need to figure out how to get the presenters for the specific presentation. -->
            <!-- {#if event_presenter_obj.event_presentation_id == event_presentation_obj.event_presentation_id} -->
            <li
                class:dim={event_presenter_obj?.hide}
                class:dim_warning={!event_presenter_obj?.enable}
                class:hidden={!event_presenter_obj?.enable &&
                    !$ae_loc.administrator_access}>
                <a
                    href="/events/{event_presenter_obj.event_id}/presenter/{event_presenter_obj.event_presenter_id}"
                    class:btn-sm={display_mode != 'default'}
                    class="
                ae_obj__event_presenter
                btn preset-tonal-primary border-primary-500 hover:preset-filled-primary-500
                my-0.5
                max-w-96 min-w-64 overflow-hidden border
                font-bold
                "
                    title="Person ID: {event_presenter_obj.person_id}; Email: {event_presenter_obj.person_primary_email}">
                    {#if event_presenter_obj?.given_name && event_presenter_obj?.given_name != 'Group'}
                        <User
                            size="1em"
                            class="text-surface-800-200 m-0.5 text-sm" />
                    {:else if event_presenter_obj?.given_name == 'Group'}
                        <Users
                            size="1em"
                            class="text-surface-800-200 m-0.5 text-sm" />
                    {:else}
                        <UserX
                            size="1em"
                            class="text-surface-800-200 m-0.5 text-sm" />
                    {/if}
                    {#if event_presenter_obj.priority}
                        <Star
                            size="1em"
                            class="text-yellow-800-200 m-0.5 text-sm" />
                    {/if}
                    <span class="grow text-center">
                        {#if event_presenter_obj?.given_name && event_presenter_obj?.given_name != 'Group'}
                            {event_presenter_obj?.full_name}
                        {:else if event_presenter_obj?.given_name == 'Group'}
                            {ae_util.shorten_string({
                                string: event_presenter_obj?.affiliations,
                                max_length: 25
                            })}
                        {:else}
                            --not set--
                        {/if}
                    </span>

                    {#if event_presenter_obj?.file_count}
                        <span
                            class="badge preset-tonal-success hover:preset-filled-success-500"
                            title="{event_presenter_obj.file_count} files">
                            <FileText size="1em" class="mx-1" />
                            {event_presenter_obj?.file_count}×
                            <!-- {event_presenter_obj?.file_count ? `(${event_presenter_obj?.file_count}&times; files)` : '(0 files)'} -->
                        </span>
                    {/if}
                </a>

                {#if pres_mgmt_loc.current.show__email_access_link && (event_presenter_obj?.person_primary_email || event_presenter_obj?.email) && ($ae_loc.trusted_access || !events_auth_loc.current.auth__person?.id)}
                    <button
                        type="button"
                        onclick={() => {
                            // Prefer Person-record email; fall back to presenter.email for
                            // presenters without a Person record (common for LCI/iMIS gaps).
                            const use_email = event_presenter_obj.person_primary_email ?? 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 = event_presenter_obj.person_id;
                            const use_passcode = event_presenter_obj.person_passcode ?? 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 access link email to ${event_presenter_obj.full_name ?? 'this presenter'} (${display_email})?`)) {
                                return;
                            }

                            events_func.email_sign_in__event_presenter({
                                api_cfg: $ae_api,
                                to_email: use_email,
                                to_name:
                                    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: event_presenter_obj.event_id,
                                event_session_id:
                                    event_presenter_obj.event_session_id,
                                event_presentation_id:
                                    event_presenter_obj.event_presentation_id,
                                event_presenter_id:
                                    event_presenter_obj.event_presenter_id,
                                session_name:
                                    event_presenter_obj?.event_session_name ??
                                    '-- not set --',
                                presentation_name:
                                    event_presenter_obj?.event_presentation_name ??
                                    '-- not set --'
                            });
                        }}
                        class="btn preset-tonal-secondary border-secondary-500 hover:preset-filled-secondary-500 my-0.5 border transition-all hover:transition-all"
                        class:btn-sm={display_mode != 'default'}
                        title="Email the access link to {event_presenter_obj.full_name ?? 'presenter'} ({$ae_loc.trusted_access ? (event_presenter_obj.person_primary_email ?? event_presenter_obj.email ?? 'no email on file') : ae_util.obscure_email(event_presenter_obj.person_primary_email ?? event_presenter_obj.email)})">
                        <Mail size="1em" class="mr-1" />
                        Email Access Link
                    </button>
                {/if}

                {#if pres_mgmt_loc.current.require__presenter_agree}
                    {#if event_presenter_obj?.agree}
                        <!-- {#if $ae_loc.trusted_access || $events_loc.auth__kv.presenter[event_presenter_obj.event_presenter_id]} -->
                        <button
                            type="button"
                            disabled={!$ae_loc.trusted_access &&
                                !events_auth_loc.current.auth__kv.presenter[event_presenter_obj.event_presenter_id] &&
                                !events_auth_loc.current.auth__kv.presenter[event_presenter_obj.email ?? ''] &&
                                !(events_auth_loc.current.auth__person.id && events_auth_loc.current.auth__person.id === event_presenter_obj.person_id)}
                            onclick={() => {
                                console.log('View terms and conditions');
                                $events_slct.event_presentation_id =
                                    event_presenter_obj.event_presentation_id;
                                $events_slct.event_presenter_id =
                                    event_presenter_obj.event_presenter_id;
                                $events_sess.pres_mgmt.show_modal__presenter_agree =
                                    event_presenter_obj.event_presenter_id;
                            }}
                            class="btn preset-tonal-success hover:preset-filled-success-500 my-0.5"
                            class:btn-sm={display_mode != 'default'}
                            title="Agreed to terms and conditions">
                            <Check size="1em" class="mr-1" />
                            Agreed
                        </button>
                    {:else}
                        <button
                            type="button"
                            disabled={!$ae_loc.trusted_access &&
                                !events_auth_loc.current.auth__kv.presenter[event_presenter_obj.event_presenter_id] &&
                                !events_auth_loc.current.auth__kv.presenter[event_presenter_obj.email ?? ''] &&
                                !(events_auth_loc.current.auth__person.id && events_auth_loc.current.auth__person.id === event_presenter_obj.person_id)}
                            onclick={() => {
                                console.log('View terms and conditions');
                                $events_slct.event_presentation_id =
                                    event_presenter_obj.event_presentation_id;
                                $events_slct.event_presenter_id =
                                    event_presenter_obj.event_presenter_id;
                                $events_sess.pres_mgmt.show_modal__presenter_agree =
                                    event_presenter_obj.event_presenter_id;
                            }}
                            class="btn preset-tonal-warning border-warning-500 hover:preset-filled-warning-500 my-0.5 border"
                            class:btn-sm={display_mode != 'default'}
                            title="View terms and conditions">
                            <X size="1em" class="mr-1" />
                            Not yet agreed
                        </button>
                    {/if}
                {/if}

                <div class="space-2 float-right flex flex-row items-center">
                    {#if $ae_loc.administrator_access && !event_presenter_obj.person_id}
                        <button
                            type="button"
                            onclick={async () => {
                                console.log('Add Person');
                                if (
                                    !confirm(
                                        `Add a new person 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;
                                }

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

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

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

                                if (new_person_obj) {
                                    // We then need to update the event_presenter with the new person_id.
                                    events_func.update_ae_obj__event_presenter({
                                        api_cfg: $ae_api,
                                        event_presentation_id:
                                            event_presenter_obj.event_presentation_id,
                                        event_presenter_id:
                                            event_presenter_obj.event_presenter_id,
                                        data_kv: {
                                            person_id: new_person_obj.person_id
                                        },
                                        log_lvl: log_lvl
                                    });
                                }
                            }}
                            class:hidden={!$ae_loc.edit_mode}
                            class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500">
                            <Plus size="1em" class="mx-1" />
                            Add Person
                        </button>
                    {/if}
                </div>
            </li>
            <!-- {/if} -->
        {/each}
    </ul>
</section>
