<script lang="ts">
interface Props {
    log_lvl?: number;
    lq__event_obj: any;
    lq__event_presenter_obj: any;
}

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

import { goto } from '$app/navigation';
import { Modal } from 'flowbite-svelte';
import { Check, Info, Pencil, QrCode, Settings, X } from '@lucide/svelte';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { events_sess, events_slct } 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 { api } from '$lib/ae_api/api';
import Element_data_store from '$lib/elements/element_data_store.svelte';
import Comp__events_menu_nav from '../../../../ae_comp__events_menu_nav.svelte';
import AE_Record_Controls from '$lib/elements/ae_record_controls.svelte';

let show_modal = $state(false);
let show_help = $state(false);

// WHY: auth__kv.presenter is keyed by both event_presenter_id AND email.
// A single sign-in link grants auth for one presenter_id, then expand_auth_for_person
// finds all sibling records by person_id (iMIS users) or email (no Person record) and
// sets both keys. This covers multi-session presenters and the ~75% of LCI presenters
// who are not in iMIS and use email as their identity anchor.
let presenter_agree_enabled = $derived(
    $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__person.id &&
     events_auth_loc.current.auth__person.id === $lq__event_presenter_obj?.person_id)
);

async function on_toggle(field: string, new_val: boolean) {
    await api.update_ae_obj({
        api_cfg: $ae_api,
        obj_type: 'event_presenter',
        obj_id: $lq__event_presenter_obj?.event_presenter_id,
        fields: { [field]: new_val }
    });
    events_func.load_ae_obj_id__event_presenter({
        api_cfg: $ae_api,
        event_presenter_id: $lq__event_presenter_obj?.event_presenter_id,
        log_lvl
    });
}

async function on_delete(method: 'delete' | 'disable') {
    await (events_func as any).delete_ae_obj_id__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,
        method
    });
    $events_slct.event_presenter_id = null;
    $events_slct.event_presenter_obj = {};
    goto(
        `/events/${$lq__event_presenter_obj.event_id}/session/${$lq__event_presenter_obj.event_session_id}`
    );
}
</script>

<div class="pres_mgmt__presenter_view_menu ae_container_module_menu">
    <div class="flex w-full flex-col gap-1">
        <Comp__events_menu_nav
            hide={false}
            event_id={$lq__event_presenter_obj?.event_id}
            events__reports={$lq__event_presenter_obj?.event_id &&
                $ae_loc.trusted_access}
            events__session_id={$lq__event_presenter_obj?.event_session_id}
            events__launcher_session_id={$lq__event_presenter_obj?.event_session_id}
            events__session_search={$events_slct.event_id &&
                (!pres_mgmt_loc.current.limit__navigation || $ae_loc.trusted_access)} />

        <div
            class="flex w-full flex-row flex-wrap items-center justify-between gap-1">
            <span
                class="ae_menu__object_options flex flex-row flex-wrap items-center gap-0.5">
                <!-- Options modal trigger -->
                {#if $ae_loc.trusted_access}
                    <button
                        type="button"
                        onclick={() => (show_modal = true)}
                        class="btn btn-sm ae_btn_info"
                        title="Presenter options">
                        <Settings size="1em" class="mr-1" />
                        Options
                    </button>
                {/if}

                <!-- Help toggle -->
                <button
                    type="button"
                    onclick={() => (show_help = !show_help)}
                    class="btn btn-sm"
                    class:ae_btn_info_filled={show_help}
                    class:ae_btn_info={!show_help}
                    title="Help and information about the presenter">
                    <Info size="1em" class="mr-1" />
                    {show_help ? 'Hide Help' : 'Help'}
                </button>
            </span>

            <!-- Presenter agreement action (shown when require__presenter_agree is on) -->
            {#if pres_mgmt_loc.current.require__presenter_agree}
                <span
                    class="ae_menu__action_options flex flex-row items-center justify-around">
                    {#if $lq__event_presenter_obj?.agree}
                        <button
                            type="button"
                            disabled={!presenter_agree_enabled}
                            onclick={() => {
                                $events_slct.event_presentation_id =
                                    $lq__event_presenter_obj?.event_presentation_id_random;
                                $events_slct.event_presenter_id =
                                    $lq__event_presenter_obj?.event_presenter_id;
                                $events_sess.pres_mgmt.show_modal__presenter_agree =
                                    $lq__event_presenter_obj?.event_presenter_id;
                            }}
                            class="btn btn-sm ae_btn_success_filled mx-1 font-bold"
                            title="Agreed to terms and conditions">
                            <Check size="1em" class="mr-1" />
                            Agreed
                        </button>
                    {:else}
                        <button
                            type="button"
                            disabled={!presenter_agree_enabled}
                            onclick={() => {
                                $events_slct.event_presentation_id =
                                    $lq__event_presenter_obj?.event_presentation_id_random;
                                $events_slct.event_presenter_id =
                                    $lq__event_presenter_obj?.event_presenter_id;
                                $events_sess.pres_mgmt.show_modal__presenter_agree =
                                    $lq__event_presenter_obj?.event_presenter_id;
                            }}
                            class="btn btn-sm ae_btn_warning_filled mx-1 font-bold"
                            title="View terms and conditions">
                            <X size="1em" class="mr-1" />
                            Not yet agreed
                        </button>
                    {/if}
                </span>
            {/if}
        </div>
    </div>

    <!-- Options Modal -->
    <Modal
        bind:open={show_modal}
        autoclose={false}
        dismissable={true}
        placement="top-center"
        size="md"
        class="relative mx-auto flex w-full flex-col rounded-lg bg-white text-gray-800 shadow-xl dark:bg-gray-800 dark:text-gray-200"
        headerClass="flex flex-row gap-2 items-center justify-between w-full bg-surface-100 dark:bg-surface-800 p-4 rounded-t-lg border-b border-surface-200 dark:border-surface-700">
        {#snippet header()}
            <h3 class="flex flex-1 items-center gap-2 text-base font-bold">
                <Settings size="1.1em" class="text-primary-500" />
                Presenter Options
            </h3>
            <button
                type="button"
                class="btn-icon btn-icon-sm preset-tonal-surface ml-2"
                onclick={() => (show_modal = false)}>
                <X size="1.1em" />
            </button>
        {/snippet}

        <div class="flex flex-col gap-4 p-4">
            <!-- Presenter-specific display options -->
            {#if $ae_loc.trusted_access}
                <section>
                    <h4
                        class="text-surface-500 mb-2 text-xs font-semibold tracking-wider uppercase">
                        Display
                    </h4>
                    <div class="flex flex-row flex-wrap gap-2">
                        <!-- QR Code toggle — only shown to trusted staff and only when
                             admin has NOT already enabled QR globally (if they have,
                             it shows automatically without needing this toggle) -->
                        {#if !pres_mgmt_loc.current.show__presenter_qr}
                            <button
                                type="button"
                                onclick={() => {
                                    pres_mgmt_loc.current.show_content__presenter_qr =
                                        !pres_mgmt_loc.current.show_content__presenter_qr;
                                }}
                                class="btn btn-sm"
                                class:ae_btn_surface={pres_mgmt_loc.current.show_content__presenter_qr}
                                class:ae_btn_surface_outlined={!pres_mgmt_loc.current.show_content__presenter_qr}>
                                <QrCode size="1em" class="mr-1" />
                                {pres_mgmt_loc.current.show_content__presenter_qr
                                    ? 'Hide QR Code'
                                    : 'Show QR Code'}
                            </button>
                        {/if}
                    </div>
                </section>
            {/if}

            <!-- Edit Mode -->
            {#if $ae_loc.trusted_access}
                <section>
                    <h4
                        class="text-surface-500 mb-2 text-xs font-semibold tracking-wider uppercase">
                        Mode
                    </h4>
                    <button
                        type="button"
                        onclick={() => ($ae_loc.edit_mode = !$ae_loc.edit_mode)}
                        class="btn btn-sm"
                        class:ae_btn_warning={$ae_loc.edit_mode}
                        class:ae_btn_warning_outlined={!$ae_loc.edit_mode}>
                        <Pencil size="1em" class="mr-1" />
                        {$ae_loc.edit_mode ? 'Edit Mode On' : 'Edit Mode?'}
                    </button>
                </section>
            {/if}

            <!-- Record Controls -->
            {#if $ae_loc.trusted_access}
                <section>
                    <h4
                        class="text-surface-500 mb-2 text-xs font-semibold tracking-wider uppercase">
                        Record
                    </h4>
                    <AE_Record_Controls
                        obj={$lq__event_presenter_obj}
                        obj_label="presenter"
                        show_alert={false}
                        show_priority={true}
                        show_enable={true}
                        show_hide={true}
                        allow_delete={$ae_loc.manager_access}
                        allow_disable={$ae_loc.trusted_access &&
                            !$ae_loc.manager_access}
                        {on_toggle}
                        {on_delete}
                        container_class="flex flex-row flex-wrap gap-2 items-center justify-start" />
                </section>
            {/if}
        </div>
    </Modal>

    <!-- Help panel -->
    <Element_data_store
        ds_code="events__pres_mgmt__presenter_page_help"
        ds_name="Default: Events - Pres Mgmt Presenter Page Help"
        ds_type="html"
        for_type="event"
        for_id={$lq__event_presenter_obj?.event_id}
        class_li="ae_container_module_help"
        show_edit={false}
        show_edit_btn={true}
        hide={!show_help} />
</div>
