<script lang="ts">
// Imports (external and then internal)
import { ae_util } from '$lib/ae_utils/ae_utils';

// Import storage, functions, and libraries
import type { key_val } from '$lib/stores/ae_stores';

import {
    ae_loc,
    ae_api
} from '$lib/stores/ae_stores';
import {
    events_sess
} 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/db_events";
import MyClipboard from '$lib/app_components/e_app_clipboard.svelte';
import { BookOpen, Check, LoaderCircle, Save } from '@lucide/svelte';
// export let event_session_id: string;

interface Props {
    log_lvl?: number;
    // Exports
    class_li?: string;
    // export let lq__event_obj: any;
    lq__event_session_obj: any;
}

let {
    log_lvl = 0,
    class_li = 'outline',
    lq__event_session_obj
}: Props = $props();
// export let event_session_obj_poc_profile: any|key_val;

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

ae_tmp.biography = null;

let poc_type = $derived(pres_mgmt_loc.current.label__session_poc_type ?? 'poc');
let poc_name = $derived(pres_mgmt_loc.current.label__session_poc_name ?? 'Point of Contact');

// Initialise biography from the POC kv_json on first available data.
// WHY: biography lives inside poc_kv_json keyed by poc_type — not a top-level column.
// We only seed the local draft once (when null) so the textarea doesn't overwrite in-progress edits.
$effect(() => {
    const kv = lq__event_session_obj?.poc_kv_json;
    if (ae_tmp.biography === null && kv && kv[poc_type]?.biography) {
        ae_tmp.biography = kv[poc_type].biography;
    }
});

let clipboard_success = $state(false);
</script>

<section class={class_li}>
    {#if lq__event_session_obj}
        {#if lq__event_session_obj.poc_person_id && $ae_loc.trusted_access}
            <span class="float-right">
                <MyClipboard
                    value={encodeURI(
                        `${$ae_loc.url_origin}/events/${lq__event_session_obj.event_id}/session/${lq__event_session_obj.event_session_id}?person_id=${lq__event_session_obj.poc_person_id}&person_pass=${lq__event_session_obj.poc_person_passcode}&session_id=${lq__event_session_obj.event_session_id}`
                    )}
                    btn_text="Copy Access Link"
                    btn_title="Copy the POC (moderator/champion) access link to the clipboard."
                    btn_class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500 m-1"
                ></MyClipboard>
            </span>
        {/if}

        <h2 class="h3">
            <strong
                >{lq__event_session_obj.poc_person_full_name} ({lq__event_session_obj.poc_person_primary_email})</strong>
        </h2>

        <div class:hidden={pres_mgmt_loc.current.hide__session_poc_biography}>
            <div class="label event_session__biography required space-y-4">
                <MyClipboard
                    value={ae_tmp.biography?.trim()}
                    btn_text="Copy Biography Text"
                    btn_title="Copy the session POC biography text to the clipboard."
                    btn_class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500 float-right m-1"
                ></MyClipboard>

                <label for="session_poc__biography" class="label">
                    <BookOpen size="1em" />
                    Session {poc_name} Biography
                    <span class="text-sm text-gray-500">
                        (75 to 100 words or 600 character limit)
                    </span>
                </label>

                <textarea
                    name="biography"
                    id="session_poc__biography"
                    disabled={!$ae_loc.trusted_access &&
                        !events_auth_loc.current.auth__kv.session[
                            lq__event_session_obj?.event_session_id
                        ]}
                    class="textarea ae_value event_session__biography font-mono"
                    class:preset-tonal-error={ae_tmp.biography &&
                    ae_tmp.biography.length > 600
                        ? true
                        : false}
                    required
                    rows="8"
                    cols="70"
                    bind:value={ae_tmp.biography}
                    placeholder="Enter brief biography here"></textarea>
            </div>
            <p>
                Biography length: {ae_tmp.biography
                    ? ae_util.number_w_commas(ae_tmp.biography.length)
                    : 0} characters;
                {ae_tmp.biography
                    ? ae_util.number_w_commas(
                          ae_util.count_words(ae_tmp.biography)
                      )
                    : 0} estimated words
            </p>
            <p>
                The biography should be plain text only and be at most 100
                words.
            </p>

            <div class="flex flex-wrap items-center gap-2 p-1">
                <button
                    type="button"
                    class="btn btn-md preset-tonal-primary hover:preset-filled-primary-500"
                    disabled={ae_tmp.biography ==
                        lq__event_session_obj.biography}
                    onclick={() => {
                        // poc_kv_json may be null if no POC data has been saved yet — initialize before writing.
                        const kv: key_val = { ...(lq__event_session_obj.poc_kv_json ?? {}) };
                        if (!kv[poc_type]) kv[poc_type] = {};
                        kv[poc_type]['biography'] = ae_tmp.biography;
                        kv[poc_type]['biography_updated_on'] = new Date().toISOString();

                        let event_session_data = { poc_kv_json: kv };

                        ae_promises.update__event_session_obj = events_func
                            .update_ae_obj__event_session({
                                api_cfg: $ae_api,
                                event_session_id:
                                    lq__event_session_obj?.event_session_id,
                                data_kv: event_session_data,
                                log_lvl: log_lvl
                            })
                            .then(function (update_result) {});
                    }}>
                    {#await ae_promises.update__event_session_obj}
                        <LoaderCircle size="1em" class="mx-1 animate-spin" />
                    {:then}
                        {#if ae_tmp.biography == lq__event_session_obj.biography}
                            <Check size="1em" class="mx-1" />
                        {:else}
                            <Save size="1em" class="mx-1" />
                        {/if}
                    {/await}
                    Save Biography
                </button>

                {#if lq__event_session_obj.poc_kv_json?.[poc_type]?.biography_updated_on}
                    <span class="text-sm text-gray-500">
                        Last saved: {ae_util.iso_datetime_formatter(
                            lq__event_session_obj.poc_kv_json?.[poc_type]?.biography_updated_on,
                            'datetime_12_long'
                        )}
                    </span>
                {/if}
            </div>
        </div>
    {:else}
        Not ready
    {/if}
</section>
