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

let {
    log_lvl = $bindable(0),
    lq__event_presenter_obj,
    lq__event_session_obj,
    lq__auth__event_presenter_obj,
    lq__event_presentation_obj_li
}: Props = $props();

// Imports
import { Modal } from 'flowbite-svelte';
import { liveQuery } from 'dexie';
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
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_api, slct } 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 { db_events } from '$lib/ae_events/db_events';

import Comp_event_session_poc_profile from './ae_comp__event_session_poc_profile.svelte';
import Comp_event_session_poc_form_agree from './ae_comp__event_session_poc_form_agree.svelte';
import {
    Check,
    ChevronDown,
    ChevronUp,
    Clock,
    IdCard,
    Link,
    Mail,
    MapPin,
    Pencil,
    RefreshCw,
    Unlink,
    X
} from '@lucide/svelte';

if (!$events_sess.pres_mgmt) {
    $events_sess.pres_mgmt = {};
    $events_sess.pres_mgmt.show_modal__presenter_agree = null;
    $events_sess.pres_mgmt.show_content__presenter_start = null;
}

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

// Description expand/collapse — collapsed by default (descriptions can be long)
let desc_expanded = $state(false);

// Email POC status — shows feedback after sending
let poc_email_status = $state<'idle' | 'sending' | 'sent' | 'error'>('idle');

// Location list for the session's event — used to build the select options in edit mode.
// WHY: event_location_id is a FK; the editor needs the full list so staff can pick from
// known rooms instead of typing a raw UUID. Keyed by event_id from the session object.
let current_event_id = $derived($lq__event_session_obj?.event_id ?? null);
let lq__event_location_obj_li = $derived(
    liveQuery(async () => {
        if (!current_event_id) return [];
        return await db_events.location
            .where('event_id')
            .equals(current_event_id)
            .sortBy('name');
    })
);
// { event_location_id: location_name } — consumed by Element_ae_obj_field_editor select
let location_select_options = $derived(
    Object.fromEntries(
        ($lq__event_location_obj_li ?? []).map((loc) => [
            (loc as { event_location_id: string }).event_location_id,
            (loc as { name: string }).name
        ])
    )
);

// Event object — used to seed the default date for session datetime editors.
let lq__event_obj = $derived(
    liveQuery(async () => {
        if (!current_event_id) return null;
        return await db_events.event.get(current_event_id);
    })
);

// Loads account people into the shared select options map so staff can assign
// a session POC from known person records instead of typing IDs manually.
async function load_person_options_for_session_poc() {
    if (!$slct.account_id) return;
    // Don't reload if already loaded or loading
    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, // We need to keep this limit high to show all people for selection: $ae_loc.person.qry_limit__people
            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;
        });
}

// Seed defaults from event start date (date only) so staff don't have to type
// the date from scratch. Time defaults to 08:00 / 09:00 as a neutral placeholder.
let event_start_date = $derived(
    $lq__event_obj?.start_datetime
        ? ae_util.iso_datetime_formatter($lq__event_obj.start_datetime, 'date_iso')
        : ''
);
let default_start_datetime = $derived(event_start_date ? `${event_start_date}T08:00` : '');
let default_end_datetime = $derived(event_start_date ? `${event_start_date}T09:00` : '');

// Derived helpers for the POC sign-in URL (used by both copy link and email).
// WHY: poc_person_passcode gates access for the session POC without requiring a full account.
// session_id is required as a query param so sign_in_out.svelte calls session_sign_in().
let poc_sign_in_url = $derived(
    $lq__event_session_obj?.poc_person_id && $lq__event_session_obj?.poc_person_passcode
        ? `${$ae_loc.url_origin}/events/${$lq__event_session_obj.event_id}/session/${$lq__event_session_obj.event_session_id}?person_id=${encodeURIComponent($lq__event_session_obj.poc_person_id)}&person_pass=${encodeURIComponent($lq__event_session_obj.poc_person_passcode)}&session_id=${encodeURIComponent($lq__event_session_obj.event_session_id)}`
        : null
);

// person_obj_kv is populated by load_person_options_for_session_poc; gate the
// select editor on it being non-empty so staff don't see a blank dropdown.
let person_options_loaded = $derived(Object.keys($slct.person_obj_kv ?? {}).length > 0);

// Whether the current session POC is signed in (auth'd) on this device.
// Also grants access by person_id so a POC signed in via one session link is automatically
// auth'd on all other sessions where their person record is the assigned POC.
let poc_is_authed = $derived(
    events_auth_loc.current.auth__kv.session[$lq__event_session_obj?.event_session_id] === true ||
    (
        !!events_auth_loc.current.auth__person.id &&
        events_auth_loc.current.auth__person.id === $lq__event_session_obj?.poc_person_id
    )
);

// QR Code Generation Logic
$events_sess.pres_mgmt.session__updated_on = null;
$effect(() => {
    // Generate QR when admin has enabled it (show__session_qr) OR trusted staff
    // has turned on their local override (show_content__session_qr).
    // show_content__session_qr is NOT required when show__session_qr is true —
    // non-trusted users (POCs, presenters) have no way to toggle it.
    if (
        $lq__event_session_obj?.id &&
        (pres_mgmt_loc.current.show__session_qr || ($ae_loc.trusted_access && pres_mgmt_loc.current.show_content__session_qr)) &&
        !$events_sess.pres_mgmt.session_qr_url[$lq__event_session_obj.id]
    ) {
        $events_sess.pres_mgmt.session_qr_url[$lq__event_session_obj.id] = true;
        let url_str = encodeURI(
            `${$ae_loc.url_origin}/events/${$lq__event_session_obj.event_id}/session/${$lq__event_session_obj.id}`
        );

        core_func
            .js_generate_qr_code('str', { str: url_str })
            .then((result) => {
                $events_sess.pres_mgmt.session_qr_url[
                    $lq__event_session_obj.id
                ] = result;
            });
    }
});


async function send_poc_email_link() {
    const sess = $lq__event_session_obj;
    if (!sess?.poc_person_primary_email) return;
    const display_email = $ae_loc.trusted_access
        ? sess.poc_person_primary_email
        : ae_util.obscure_email(sess.poc_person_primary_email);
    if (!confirm(`Send sign-in link to ${sess.poc_person_full_name} (${display_email})?`)) return;
    poc_email_status = 'sending';
    try {
        await events_func.email_sign_in__event_session({
            api_cfg: $ae_api,
            to_email: sess.poc_person_primary_email,
            to_name: sess.poc_person_full_name ?? '',
            base_url: $ae_loc.url_origin,
            person_id: sess.poc_person_id,
            person_passcode: sess.poc_person_passcode ?? '',
            event_id: sess.event_id,
            event_session_id: sess.event_session_id,
            session_name: sess.name
        });
        poc_email_status = 'sent';
        setTimeout(() => { poc_email_status = 'idle'; }, 4000);
    } catch {
        poc_email_status = 'error';
        setTimeout(() => { poc_email_status = 'idle'; }, 4000);
    }
}
</script>

<!--
    SESSION VIEW — Speaker Ready Room & Remote Upload
    Primary users: Presenters uploading files (remote) + Staff helping presenters (onsite).
    Design intent: "Is this the right session?" must be answerable in <3 seconds.
    Show: name, time, room, POC, description. Hide admin noise unless edit_mode.
    Section 508: all interactive elements labelled, focus rings, sufficient contrast.
-->
<section class="space-y-2">
    <!-- SESSION HERO CARD: Name, Code, Datetime, Room, POC — all in one block -->
    <div class="border-surface-200-800 bg-surface-50-900 overflow-hidden rounded-xl border shadow-sm">
        <div class="flex flex-col gap-3 px-4 pt-4 pb-3">

            <!-- QR code: floats top-right, compact by default, toggle to enlarge.
                 Only rendered once the async URL is resolved (string), never while
                 it is still the boolean `true` loading placeholder. -->
            {#if $lq__event_session_obj && (pres_mgmt_loc.current.show__session_qr || ($ae_loc.trusted_access && pres_mgmt_loc.current.show_content__session_qr)) && typeof $events_sess.pres_mgmt.session_qr_url?.[$lq__event_session_obj.id] === 'string'}
                <div class="float-right mb-1 ml-3 flex flex-col items-center gap-1">
                    <button
                        type="button"
                        onclick={() =>
                            ($events_sess.pres_mgmt.qr_bigger =
                                !$events_sess.pres_mgmt.qr_bigger)}
                        class="focus-visible:ring-primary-500 rounded focus-visible:ring-2"
                        title="Toggle QR code size"
                        aria-label="Toggle QR code size">
                        <img
                            src={$events_sess.pres_mgmt.session_qr_url[
                                $lq__event_session_obj.id
                            ]}
                            class="border-surface-200-800 rounded border transition-all duration-500"
                            class:h-20={!$events_sess.pres_mgmt.qr_bigger}
                            class:w-20={!$events_sess.pres_mgmt.qr_bigger}
                            class:h-40={$events_sess.pres_mgmt.qr_bigger}
                            class:w-40={$events_sess.pres_mgmt.qr_bigger}
                            alt="QR code link to this session page" />
                    </button>
                    <MyClipboard
                        value={encodeURI(
                            `${$ae_loc.url_origin}/events/${$lq__event_session_obj.event_id}/session/${$lq__event_session_obj.id}`
                        )}
                        btn_class="btn btn-sm preset-tonal-surface text-xs"
                        hide_icon={false}
                        hide_text={true}>
                        <Link size="1em" />
                    </MyClipboard>
                </div>
            {/if}

            <!-- Session Name + Code: always visible regardless of edit_mode -->
            {#if $lq__event_session_obj}
                <div>
                    {#if $ae_loc.edit_mode}
                        <Element_ae_obj_field_editor
                            object_type={'event_session'}
                            object_id={$lq__event_session_obj.id}
                            field_name={'name'}
                            field_type={'text'}
                            current_value={$lq__event_session_obj.name}
                            on_success={() =>
                                events_func.load_ae_obj_id__event_session({
                                    api_cfg: $ae_api,
                                    event_session_id: $lq__event_session_obj.id
                                })}>
                            <div class="text-xl leading-snug font-bold">
                                {$lq__event_session_obj.name}
                            </div>
                        </Element_ae_obj_field_editor>

                        {#if !pres_mgmt_loc.current.hide__session_code}
                            <Element_ae_obj_field_editor
                                object_type="event_session"
                                object_id={$lq__event_session_obj.id}
                                field_name="code"
                                field_type="text"
                                edit_label="Session Code"
                                current_value={$lq__event_session_obj.code}
                                placeholder="e.g. SES-101"
                                on_success={() =>
                                    events_func.load_ae_obj_id__event_session({
                                        api_cfg: $ae_api,
                                        event_session_id: $lq__event_session_obj.id
                                    })}>
                                <span class="badge preset-tonal-surface mt-1 text-xs"
                                    >code: {$lq__event_session_obj.code}</span>
                            </Element_ae_obj_field_editor>
                        {/if}
                    {:else}
                        <!-- <div class="text-xl leading-snug font-bold">
                            {$lq__event_session_obj.name}
                        </div>
                        {#if !pres_mgmt_loc.current.hide__session_code && $lq__event_session_obj.code}
                            <span class="badge preset-tonal-surface mt-1 text-xs"
                                >code: {$lq__event_session_obj.code}</span>
                        {/if} -->
                    {/if}
                </div>
            {:else}
                <!-- Skeleton placeholder while LiveQuery resolves -->
                <div class="bg-surface-200-800 h-7 w-2/3 animate-pulse rounded"></div>
            {/if}

            <!-- Info rows: Datetime, Room, POC -->
            {#if $lq__event_session_obj}
                <ul class="flex flex-col gap-2">

                    <!-- Date/Time row -->
                    <li class="flex flex-wrap items-center gap-2">
                        <span
                            class="bg-primary-500/10 text-primary-700 dark:text-primary-300 inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-semibold transition-colors duration-200">
                            <button
                                type="button"
                                onclick={() => (pres_mgmt_loc.current.use_12h = !pres_mgmt_loc.current.use_12h)}
                                title={pres_mgmt_loc.current.use_12h ? 'Switch to 24-hour time' : 'Switch to 12-hour time'}
                                class="cursor-pointer rounded focus-visible:ring-1 focus-visible:ring-current"
                                aria-label={pres_mgmt_loc.current.use_12h ? 'Switch to 24-hour time' : 'Switch to 12-hour time'}>
                                <Clock size="1em" class="text-xs" />
                            </button>
                            {ae_util.iso_datetime_formatter(
                                $lq__event_session_obj.start_datetime,
                                'dddd'
                            )},
                            {ae_util.iso_datetime_formatter(
                                $lq__event_session_obj.start_datetime,
                                'datetime_long',
                                pres_mgmt_loc.current.use_12h
                            )}
                            {#if $lq__event_session_obj.end_datetime}
                                &ndash;
                                {ae_util.iso_datetime_formatter(
                                    $lq__event_session_obj.end_datetime,
                                    'datetime_long',
                                    pres_mgmt_loc.current.use_12h
                                )}
                            {/if}
                        </span>

                        <!-- Datetime editors — only in edit_mode -->
                        {#if $ae_loc.edit_mode}
                            <div class="flex flex-wrap gap-3">
                                <Element_ae_obj_field_editor
                                    display_block={true}
                                    object_type="event_session"
                                    object_id={$lq__event_session_obj.id}
                                    field_name="start_datetime"
                                    field_type="datetime"
                                    edit_label="Start Date & Time"
                                    current_value={$lq__event_session_obj.start_datetime || default_start_datetime}
                                    on_success={() =>
                                        events_func.load_ae_obj_id__event_session({
                                            api_cfg: $ae_api,
                                            event_session_id: $lq__event_session_obj.id
                                        })}>
                                    <span class="text-xs font-semibold opacity-60">
                                        <Clock size="0.9em" class="mr-1 inline" />Start:
                                        {ae_util.iso_datetime_formatter($lq__event_session_obj.start_datetime, 'datetime_long', pres_mgmt_loc.current.use_12h)}
                                    </span>
                                </Element_ae_obj_field_editor>

                                <Element_ae_obj_field_editor
                                    display_block={true}
                                    object_type="event_session"
                                    object_id={$lq__event_session_obj.id}
                                    field_name="end_datetime"
                                    field_type="datetime"
                                    edit_label="End Date & Time"
                                    current_value={$lq__event_session_obj.end_datetime || default_end_datetime}
                                    on_success={() =>
                                        events_func.load_ae_obj_id__event_session({
                                            api_cfg: $ae_api,
                                            event_session_id: $lq__event_session_obj.id
                                        })}>
                                    <span class="text-xs font-semibold opacity-60">
                                        <Clock size="0.9em" class="mr-1 inline" />End:
                                        {#if $lq__event_session_obj.end_datetime}

                                        {ae_util.iso_datetime_formatter($lq__event_session_obj.end_datetime, 'datetime_long', pres_mgmt_loc.current.use_12h)}
                                        {:else}
                                            <span class="italic opacity-60">Not set</span>
                                        {/if}
                                    </span>
                                </Element_ae_obj_field_editor>
                            </div>
                        {/if}
                    </li>

                    <!-- Room/Location row (hidden by config) -->
                    <li class:hidden={pres_mgmt_loc.current.hide__session_location}>
                        {#if $ae_loc.edit_mode}
                            <!-- Room/Location: editable in edit_mode via select from this event's locations.
                                 WHY: event_location_id is a FK — staff need to pick from known rooms,
                                 not type a raw UUID. The liveQuery above loads locations for this event. -->
                            <Element_ae_obj_field_editor
                                display_block={true}
                                object_type="event_session"
                                object_id={$lq__event_session_obj.id}
                                field_name="event_location_id"
                                field_type="select"
                                edit_label="Room / Location"
                                current_value={$lq__event_session_obj.event_location_id ?? null}
                                allow_null={true}
                                select_options={location_select_options}
                                on_success={() =>
                                    events_func.load_ae_obj_id__event_session({
                                        api_cfg: $ae_api,
                                        event_session_id: $lq__event_session_obj.id
                                    })}>
                                <span
                                    class="bg-tertiary-500/10 text-tertiary-700 dark:text-tertiary-300 inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-semibold transition-colors duration-200">
                                    <MapPin size="1em" class="text-xs" />
                                    {$lq__event_session_obj.event_location_name ?? 'No room assigned'}
                                </span>
                            </Element_ae_obj_field_editor>
                        {:else if $lq__event_session_obj.event_location_name}
                            <span
                                class="bg-tertiary-500/10 text-tertiary-700 dark:text-tertiary-300 inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-sm font-semibold transition-colors duration-200">
                                <MapPin size="1em" class="text-xs" />
                                {$lq__event_session_obj.event_location_name}
                            </span>
                        {/if}
                    </li>

                    <!-- POC / Host row (hidden by config) -->
                    <li class:hidden={pres_mgmt_loc.current.hide__session_poc}>
                        <div class="flex flex-wrap items-center gap-2">
                            <span class="text-sm font-semibold opacity-60">
                                {pres_mgmt_loc.current.label__session_poc_name}:
                            </span>

                            {#if $lq__event_session_obj?.poc_person_id}
                                <!-- Profile button — only visible to trusted staff or signed-in session POC.
                                     WHY: poc_person_full_name is PII; non-authed users just see the name as text. -->
                                {#if $ae_loc.trusted_access || poc_is_authed}
                                    <button
                                        type="button"
                                        class="btn btn-sm preset-tonal-primary transition-colors duration-200"
                                        onclick={() =>
                                            ($events_sess.pres_mgmt.show__session_poc_profile = true)}
                                        aria-haspopup="dialog">
                                        <IdCard size="1em" class="mr-1" />
                                        {$lq__event_session_obj.poc_person_full_name}'s Profile
                                    </button>
                                {:else}
                                    <span class="text-sm"
                                        >{$lq__event_session_obj.poc_person_full_name}</span>
                                {/if}

                                <!-- Copy POC sign-in link — trusted staff only, when feature is enabled.
                                     WHY: allows onsite staff to paste the link into chat/email quickly. -->
                                {#if $ae_loc.trusted_access && pres_mgmt_loc.current.show__copy_access_link && poc_sign_in_url}
                                    <MyClipboard
                                        value={poc_sign_in_url}
                                        btn_class="btn btn-sm preset-outlined-secondary-300-700 transition-all duration-200 preset-filled-secondary-50-950"
                                        btn_text=""
                                        btn_title="Copy the {pres_mgmt_loc.current.label__session_poc_name} sign-in link to the clipboard for {$lq__event_session_obj?.poc_person_full_name} ({$lq__event_session_obj?.poc_person_primary_email})"
                                        hide_icon={true}
                                        hide_text={true}>
                                        <Link size="1em" class="" />
                                        Copy Link
                                    </MyClipboard>
                                {/if}

                                <!-- Email POC sign-in link — shown when email feature is enabled and
                                     the POC has an email on file. Decoupled from require__session_agree:
                                     staff need to send sign-in links whether or not an agreement form is
                                     required. Hidden once the POC is already signed in (poc_is_authed);
                                     trusted staff can still see it in case they need to resend. -->
                                {#if pres_mgmt_loc.current.show__email_access_link && $lq__event_session_obj?.poc_person_primary_email && ($ae_loc.trusted_access || !poc_is_authed)}
                                    <button
                                        type="button"
                                        disabled={poc_email_status === 'sending'}
                                        onclick={send_poc_email_link}
                                        title="Email the sign-in link to {pres_mgmt_loc.current.label__session_poc_name}: {$lq__event_session_obj?.poc_person_full_name} ({$ae_loc.trusted_access ? $lq__event_session_obj?.poc_person_primary_email : ae_util.obscure_email($lq__event_session_obj?.poc_person_primary_email)})"
                                        class="btn btn-sm preset-outlined-secondary-300-700 transition-all duration-200"
                                        class:preset-tonal-secondary={poc_email_status === 'idle'}
                                        class:preset-tonal-warning={poc_email_status === 'sending'}
                                        class:preset-tonal-success={poc_email_status === 'sent'}
                                        class:preset-tonal-error={poc_email_status === 'error'}>
                                        <Mail size="1em" class="" />
                                        {#if poc_email_status === 'sending'}
                                            Sending…
                                        {:else if poc_email_status === 'sent'}
                                            Sent!
                                        {:else if poc_email_status === 'error'}
                                            Error
                                        {:else}
                                            Email Sign-In Link
                                        {/if}
                                    </button>
                                {/if}

                                <!-- Agreement button — visible when require__session_agree is on
                                     and user is trusted staff or the signed-in POC. -->
                                {#if pres_mgmt_loc.current.require__session_agree && ($ae_loc.trusted_access || poc_is_authed)}
                                    <button
                                        type="button"
                                        disabled={!$ae_loc.trusted_access && !poc_is_authed}
                                        class="btn btn-sm transition-colors duration-200"
                                        class:preset-tonal-success={$lq__event_session_obj?.poc_agree}
                                        class:preset-tonal-error={!$lq__event_session_obj?.poc_agree && poc_is_authed}
                                        class:preset-outlined-error-300-700={!$lq__event_session_obj?.poc_agree && poc_is_authed}
                                        class:preset-tonal-warning={!$lq__event_session_obj?.poc_agree && !poc_is_authed}
                                        onclick={() =>
                                            ($events_sess.pres_mgmt.show_modal__session_poc_agree = true)}
                                        title="You must agree to the consent and release form before you can help manage this session. This is required for all {pres_mgmt_loc.current.label__session_poc_name} users."
                                        >
                                        {#if $lq__event_session_obj?.poc_agree}
                                            <Check size="1em" class="mr-1" /> Agreed
                                        {:else}
                                            <X size="1em" class="mr-1" /> Not yet agreed
                                        {/if}
                                    </button>

                                    <Modal
                                        title="{$lq__event_session_obj?.poc_person_full_name} — {pres_mgmt_loc.current.label__session_poc_name} Agreement"
                                        bind:open={$events_sess.pres_mgmt.show_modal__session_poc_agree}
                                        autoclose={false}
                                        placement="center"
                                        size="lg"
                                        >
                                        <Comp_event_session_poc_form_agree
                                            lq__event_session_obj={$lq__event_session_obj} />
                                        {#snippet footer()}
                                            <div class="w-full text-center">
                                                <button
                                                    type="button"
                                                    onclick={() => ($events_sess.pres_mgmt.show_modal__session_poc_agree = false)}
                                                    class="btn preset-tonal-warning border border-warning-500">
                                                    <X size="1em" class="mr-1" />
                                                    Close
                                                </button>
                                            </div>
                                        {/snippet}
                                    </Modal>
                                {/if}

                                <!-- Profile modal (same dynamic label) -->
                                <Modal
                                    title="{pres_mgmt_loc.current.label__session_poc_name}'s Profile"
                                    bind:open={$events_sess.pres_mgmt.show__session_poc_profile}
                                    autoclose={false}>
                                    <Comp_event_session_poc_profile
                                        lq__event_session_obj={$lq__event_session_obj} />
                                    {#snippet footer()}
                                        <button
                                            onclick={() =>
                                                ($events_sess.pres_mgmt.show__session_poc_profile = false)}
                                            class="btn preset-tonal-warning">Close</button>
                                    {/snippet}
                                </Modal>
                            {:else}
                                <span class="text-sm italic opacity-40"
                                    >No {pres_mgmt_loc.current.label__session_poc_name} assigned</span>
                            {/if}

                            <!-- POC person selector — trusted staff in edit_mode only.
                                 WHY: Automatically load person list when editor opens via on_open.
                                 Eliminates the previous manual \"Select Person\" step.
                                 The editor now shows a loading state if options are empty. -->
                            {#if $ae_loc.trusted_access && $ae_loc.edit_mode}
                                <div class="mt-1 flex flex-wrap items-center gap-2">
                                    <Element_ae_obj_field_editor
                                        object_type="event_session"
                                        object_id={$lq__event_session_obj.id}
                                        field_name="poc_person_id"
                                        field_type="select"
                                        edit_label="Session {pres_mgmt_loc.current.label__session_poc_name}"
                                        current_value={$lq__event_session_obj.poc_person_id ?? null}
                                        select_options={$slct.person_obj_kv}
                                        allow_null={$ae_loc.administrator_access}
                                        on_open={load_person_options_for_session_poc}
                                        on_success={() =>
                                            events_func.load_ae_obj_id__event_session({
                                                api_cfg: $ae_api,
                                                event_session_id: $lq__event_session_obj.id
                                            })}>
                                        {#if $lq__event_session_obj.poc_person_id}
                                            <a
                                                href="/core/person/{$lq__event_session_obj.poc_person_id}"
                                                class="text-primary-500 hover:text-primary-700 inline-flex items-center gap-1 text-xs hover:underline"
                                                title="Open linked person record">
                                                <Link size="1em" />
                                                Re-link {pres_mgmt_loc.current.label__session_poc_name}
                                            </a>
                                        {:else}
                                            <span class="inline-flex items-center gap-1 text-xs opacity-60">
                                                <Unlink size="1em" />
                                                Assign {pres_mgmt_loc.current.label__session_poc_name}
                                            </span>
                                        {/if}
                                    </Element_ae_obj_field_editor>

                                    <button
                                        type="button"
                                        onclick={load_person_options_for_session_poc}
                                        class="btn btn-sm preset-tonal-surface group opacity-40 hover:opacity-100"
                                        title="Force refresh person list">
                                        <RefreshCw size="1em" class="text-xs" />
                                    </button>
                                </div>
                            {/if}
                        </div>
                    </li>

                </ul>
            {:else}
                <div class="bg-surface-200-800 h-5 w-1/2 animate-pulse rounded-full"></div>
            {/if}
        </div>
    </div>

    <!-- Description: collapsed by default in view mode (can be long).
         In edit mode, show the editor directly — no collapse needed when staff are updating it. -->
    {#if $lq__event_session_obj?.description || $ae_loc.edit_mode}
        <div class="border-surface-200-800 bg-surface-50-900 rounded-lg border px-4 py-3">
            {#if $ae_loc.edit_mode}
                <Element_ae_obj_field_editor
                    display_block={true}
                    object_type="event_session"
                    object_id={$lq__event_session_obj?.id}
                    field_name="description"
                    field_type="textarea"
                    edit_label="Description"
                    current_value={$lq__event_session_obj?.description ?? ''}
                    placeholder="Session description..."
                    textarea_rows={4}
                    on_success={() =>
                        events_func.load_ae_obj_id__event_session({
                            api_cfg: $ae_api,
                            event_session_id: $lq__event_session_obj?.id
                        })}>
                    <span class="text-xs font-bold tracking-wide uppercase opacity-40">
                        Description
                    </span>
                </Element_ae_obj_field_editor>
            {:else}
                <button
                    type="button"
                    class="focus-visible:ring-primary-500 flex w-full items-center justify-between gap-2 rounded text-left focus-visible:ring-2"
                    onclick={() => (desc_expanded = !desc_expanded)}
                    aria-expanded={desc_expanded}>
                    <span class="text-xs font-bold tracking-wide uppercase opacity-40"
                        >Description</span>
                    <span class="shrink-0 text-xs opacity-40">
                        {#if desc_expanded}
                            <ChevronUp size="1em" />
                            <span class="sr-only">Collapse description</span>
                        {:else}
                            <ChevronDown size="1em" />
                            <span class="sr-only">Expand description</span>
                        {/if}
                    </span>
                </button>
                {#if desc_expanded}
                    <p class="mt-2 text-sm leading-relaxed whitespace-pre-wrap">
                        {$lq__event_session_obj?.description}
                    </p>
                {/if}
            {/if}
        </div>
    {/if}
</section>
