<script lang="ts">
    import { run } from 'svelte/legacy';

    // Imports (external and then internal)
    import { browser } from '$app/environment';
    // import { liveQuery } from "dexie";
    // import { Clipboard } from "flowbite-svelte";

    import { ae_util } from '$lib/ae_utils/ae_utils';

    // Import components and elements
    // import Element_input_files_tbl from '$lib/element_input_files_tbl.svelte';

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

    // import { api } from '$lib/api';
    import {
        ae_snip,
        ae_loc,
        ae_sess,
        ae_api,
        ae_trig,
        slct,
        slct_trigger
    } from '$lib/stores/ae_stores';
    import {
        events_loc,
        events_sess,
        events_slct,
        events_trigger
    } from '$lib/stores/ae_events_stores';
    import { events_func } from '$lib/ae_events_functions';
    // import { db_events } from "$lib/db_events";
    import MyClipboard from '$lib/app_components/e_app_clipboard.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 = $events_loc.pres_mgmt.label__session_poc_type;
    let poc_name = $events_loc.pres_mgmt.label__session_poc_name;

    run(() => {
        if (
            browser &&
            ae_tmp.biography === null &&
            $lq__event_session_obj?.poc_kv_json &&
            $lq__event_session_obj?.poc_kv_json[poc_type]?.biography
        ) {
            ae_tmp.biography =
                $lq__event_session_obj?.poc_kv_json[poc_type].biography;
            console.log(`ae_tmp.biography:`, ae_tmp.biography);
        }
    });

    // $: if ($lq__event_session_obj?.poc_kv_json) {
    //     lq__event_session_obj.poc_kv_json = JSON.parse(lq__event_session_obj.poc_kv_json);
    // }

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

<section class={class_li}>
    {#if $lq__event_session_obj}
        {#if $lq__event_session_obj.poc_person_id_random && $ae_loc.trusted_access}
            <span class="float-right">
                <!-- A button to copy the access link to the clipboard. -->
                <!-- Example: /events/CHs3F44Xq76/session/Wh8UnJlbIA0?person_id=fV1dl_IJ0yY&person_pass=abc123 -->
                <!-- {#if clipboard_success}Copied!{:else}Copy Access Link{/if} -->
                <!-- <span class="fas fa-copy mx-1"></span> -->
                <MyClipboard
                    value={encodeURI(
                        `${$ae_loc.url_origin}/events/${$lq__event_session_obj.event_id}/session/${$events_slct.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">
            <!-- Session {$events_loc.pres_mgmt.label__session_poc_name} Profile:<br> -->
            <strong
                >{$lq__event_session_obj.poc_person_full_name} ({$lq__event_session_obj.poc_person_primary_email})</strong
            >
        </h2>

        <!-- {$events_loc.pres_mgmt.label__session_poc_type} -->
        <!-- {$events_loc.pres_mgmt.label__session_poc_name} -->

        <!-- Ask for bio here: -->
        <!-- The session POC biography. There should be a character counter. -->
        <div class:hidden={$events_loc.pres_mgmt?.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">
                    <span class="fas fa-book"></span>
                    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_loc.auth__kv.session[
                            $lq__event_session_obj?.event_session_id_random
                        ]}
                    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>Biography length: </p> -->
            <p>
                The biography should be plain text only and be at most 100
                words.
            </p>
            <!-- <p>1,250 characters is roughly 250 words</p> -->
            <!-- <p>1,375 characters is roughly 250 to 300 words</p> -->

            <div class="flex flex-wrap gap-2 p-1 items-center">
                <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={() => {
                        console.log('*** Save button clicked ***');

                        let event_session_data = {
                            poc_kv_json: $lq__event_session_obj.poc_kv_json
                        };
                        console.log('event_session_data:', event_session_data);

                        // Check if poc_type exists in the event_session_data.poc_kv_json
                        if (!event_session_data.poc_kv_json[poc_type]) {
                            event_session_data.poc_kv_json[poc_type] = {};
                        }

                        event_session_data.poc_kv_json[poc_type]['biography'] =
                            ae_tmp.biography;
                        event_session_data.poc_kv_json[poc_type][
                            'biography_updated_on'
                        ] = new Date().toISOString();

                        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_random,
                                data_kv: event_session_data,
                                log_lvl: log_lvl
                            })
                            .then(function (update_result) {
                                // console.log(update_result);
                                // return update_result;
                            });
                    }}
                >
                    {#await ae_promises.update__event_session_obj}
                        <span class="fas fa-spinner fa-spin mx-1"></span>
                    {:then}
                        {#if ae_tmp.biography == $lq__event_session_obj.biography}
                            <span class="fas fa-check mx-1"></span>
                        {:else}
                            <span class="fas fa-save mx-1"></span>
                        {/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>
