<script lang="ts">
    interface Props {
        log_lvl?: number;
        hide__launcher_link?: boolean;
        hide__launcher_link_legacy?: boolean;
        lq__event_location_obj: any;
    }

    let {
        log_lvl = 0,
        hide__launcher_link = false,
        hide__launcher_link_legacy = true,
        lq__event_location_obj
    }: Props = $props();

    console.log(`ae_events_pres_mgmt location_view.svelte`);

    import { liveQuery } from 'dexie';

    // const dispatch = createEventDispatcher();

    import type { key_val } from '$lib/stores/ae_stores';
    // import { ae_util } from '$lib/ae_utils/ae_utils';
    import Element_ae_crud from '$lib/elements/element_ae_crud.svelte';
    import Element_data_store from '$lib/elements/element_data_store_v3.svelte';

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

    import { core_func } from '$lib/ae_core/ae_core_functions';
    import { db_events } from '$lib/ae_events/db_events';
    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,
        events_trig_kv
    } from '$lib/stores/ae_events_stores';
    import { events_func } from '$lib/ae_events_functions';

    // Exports
    // export let event_location_id: string;
    // export let event_location_obj: key_val;
    // export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'

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

    let lq__event_presentation_obj = $derived(
        liveQuery(async () => {
            let results = await db_events.presentation.get(
                $events_slct.event_presentation_id
            );
            return results;
        })
    );

    $events_sess.pres_mgmt.location__updated_on = null;
    $effect(() => {
        if ($lq__event_location_obj) {
            if (log_lvl > 1) {
                console.log(
                    `$lq__event_location_obj:`,
                    $lq__event_location_obj
                );
            }

            if ($events_loc.pres_mgmt.show_content__location_qr) {
                if (
                    $lq__event_location_obj.updated_on ==
                    $events_sess.pres_mgmt.location__updated_on
                ) {
                    if (log_lvl > 1) {
                        console.log('Updated on is the same.');
                    }
                } else {
                    if (log_lvl) {
                        console.log('Updated on is different.');
                    }
                    // FUTURE USE: Generate a QR code for the object ID.
                    // ae_promises.generate_qr_code_obj_id = core_func.generate_qr_code({api_cfg: $ae_api, account_id: $slct.account_id, qr_type: 'obj', qr_id: $lq__event_location_obj?.event_location_id, obj_type: 'event_location', obj_id: $lq__event_location_obj?.event_location_id});

                    // Generate a QR code for the URL.
                    let qr_id_url = `${$lq__event_location_obj?.event_location_id}_url`;

                    // URL for this page (be sure to URL encode it):
                    let url_str = `${$ae_loc.url_origin}/events/${$lq__event_location_obj?.event_id}/location/${$lq__event_location_obj?.event_location_id}`;
                    url_str = encodeURI(url_str);

                    ae_promises.generate_qr_code_url =
                        core_func.generate_qr_code({
                            api_cfg: $ae_api,
                            account_id: $slct.account_id,
                            qr_type: 'str',
                            qr_id: qr_id_url,
                            str: url_str
                        });

                    $events_sess.pres_mgmt.location__updated_on =
                        $lq__event_location_obj?.updated_on;
                }
            } else {
                if (log_lvl) {
                    console.log('Clearing the URL.');
                }
                ae_promises.generate_qr_code_url = null;
                // Resetting the updated_on value helps with the QR code come back when switched back on.
                $events_sess.pres_mgmt.location__updated_on = null;
            }
        }
    });
</script>

{#if $lq__event_location_obj}
    <section class="p-2">
        <!-- {#await ae_promises.generate_qr_code_url}
    Generating...
{:then result}
    {#if ae_promises.generate_qr_code_url && $ae_loc.trusted_access}
        <span class="float-right m-1 p-1 flex flex-col items-center justify-center outline outline-gray-200 *:hover:inline">
            <img
                class="qr_code qr_type_url h-32 w-32 hover:h-48 hover:w-48"
                style=""
                src={result}
                alt="URL QR code"
                />
            <span>
                <span class="fas fa-link"></span>
                <span>Location URL</span>
            </span>
            <div class="hidden">
                This QR is a link back to this page.
            </div>
        </span>
    {/if}
{/await} -->

        <ul class="space-y-2 px-4">
            <li class:hidden={!$ae_loc.manager_access || !$ae_loc.edit_mode}>
                <Element_ae_crud
                    api_cfg={$ae_api}
                    object_type={'event_location'}
                    object_id={$lq__event_location_obj?.event_location_id}
                    field_name={'external_id'}
                    field_type={'text'}
                    field_value={$lq__event_location_obj?.external_id}
                    allow_null={true}
                    hide_edit_btn={!$ae_loc.trusted_access ||
                        !$ae_loc.edit_mode}
                    outline_element={false}
                    show_crud={false}
                    display_inline={true}
                    display_block_edit={true}
                    class_li={''}
                    on:ae_crud_updated={(e) => {
                        console.log(`ae_crud_updated:`, e.detail);

                        events_func
                            .load_ae_obj_id__event_location({
                                api_cfg: $ae_api,
                                event_location_id:
                                    $lq__event_location_obj?.event_location_id,
                                log_lvl: 1
                            })
                            .then(function (load_results) {});
                    }}
                >
                    <strong class="text-sm">External ID:</strong>
                    {$lq__event_location_obj.external_id}
                </Element_ae_crud>
            </li>

            <li
                class:hidden={!$ae_loc.administrator_access ||
                    !$ae_loc.edit_mode}
            >
                <Element_ae_crud
                    api_cfg={$ae_api}
                    object_type={'event_location'}
                    object_id={$lq__event_location_obj?.event_location_id}
                    field_name={'code'}
                    field_type={'text'}
                    field_value={$lq__event_location_obj?.code}
                    allow_null={true}
                    hide_edit_btn={!$ae_loc.administrator_access ||
                        !$ae_loc.edit_mode}
                    outline_element={false}
                    show_crud={false}
                    display_inline={true}
                    display_block_edit={true}
                    class_li={''}
                    on:ae_crud_updated={(e) => {
                        console.log(`ae_crud_updated:`, e.detail);

                        events_func
                            .load_ae_obj_id__event_location({
                                api_cfg: $ae_api,
                                event_location_id:
                                    $lq__event_location_obj?.event_location_id,
                                log_lvl: 1
                            })
                            .then(function (load_results) {});
                    }}
                >
                    <strong class="text-sm">Code:</strong>
                    {$lq__event_location_obj.code}
                </Element_ae_crud>
            </li>

            <li>
                <Element_ae_crud
                    api_cfg={$ae_api}
                    object_type={'event_location'}
                    object_id={$lq__event_location_obj?.event_location_id}
                    field_name={'name'}
                    field_type={'text'}
                    field_value={$lq__event_location_obj?.name}
                    allow_null={false}
                    hide_edit_btn={!$ae_loc.trusted_access ||
                        !$ae_loc.edit_mode}
                    outline_element={false}
                    show_crud={false}
                    display_inline={true}
                    display_block_edit={true}
                    class_li={''}
                    on:ae_crud_updated={(e) => {
                        console.log(`ae_crud_updated:`, e.detail);

                        events_func
                            .load_ae_obj_id__event_location({
                                api_cfg: $ae_api,
                                event_location_id:
                                    $lq__event_location_obj?.event_location_id,
                                log_lvl: 1
                            })
                            .then(function (load_results) {});
                    }}
                >
                    <strong class="text-sm">Name (room or area):</strong>
                    {$lq__event_location_obj.name}
                </Element_ae_crud>

                {#if !$events_loc.pres_mgmt?.hide__location_code}
                    <Element_ae_crud
                        api_cfg={$ae_api}
                        object_type={'event_location'}
                        object_id={$lq__event_location_obj?.event_location_id}
                        field_name={'code'}
                        field_type={'text'}
                        field_value={$lq__event_location_obj?.code}
                        allow_null={false}
                        hide_edit_btn={!$ae_loc.trusted_access ||
                            !$ae_loc.edit_mode}
                        outline_element={false}
                        show_crud={false}
                        display_inline={true}
                        display_block_edit={false}
                        class_li={''}
                        on:ae_crud_updated={(e) => {
                            console.log(`ae_crud_updated:`, e.detail);

                            events_func
                                .load_ae_obj_id__event_location({
                                    api_cfg: $ae_api,
                                    event_location_id:
                                        $lq__event_location_obj?.event_location_id,
                                    log_lvl: 1
                                })
                                .then(function (load_results) {});
                        }}
                    >
                        <span
                            class="text-sm text-gray-500 bg-yellow-100 p-1 rounded-md border border-yellow-200"
                            title="Location code {$lq__event_location_obj.code}"
                        >
                            <strong class="text-sm">code:</strong>
                            <span class="fas fa-barcode"></span>
                            {$lq__event_location_obj.code}
                        </span>
                    </Element_ae_crud>
                {/if}

                <!-- BEGIN: Legacy link -->
                <a
                    data-sveltekit-preload-data="false"
                    href="/event/{$lq__event_location_obj?.event_id}/launcher/{$lq__event_location_obj?.event_location_id}"
                    class:hidden={hide__launcher_link_legacy}
                    class="btn btn-sm preset-tonal-secondary hover:preset-filled-secondary-500"
                    title="Launcher: {$lq__event_location_obj?.name} {$lq__event_location_obj?.event_location_id}"
                >
                    <span class="fas fa-paper-plane m-1"></span>
                    {@html $lq__event_location_obj?.name
                        ? $lq__event_location_obj?.name
                        : ae_snip.html__not_set}
                </a>
                <!-- END: Legacy link -->

                <a
                    data-sveltekit-preload-data="false"
                    href="/events/{$lq__event_location_obj?.event_id}/launcher/{$lq__event_location_obj?.event_location_id}"
                    class:hidden={hide__launcher_link}
                    class="btn btn-sm preset-tonal-secondary hover:preset-filled-secondary-500"
                    title="Launcher: {$lq__event_location_obj?.name} {$lq__event_location_obj?.event_location_id}"
                >
                    <span class="fas fa-plane m-1"></span>
                    <!-- {@html $lq__event_location_obj?.name ? $lq__event_location_obj?.name : ae_snip.html__not_set} -->
                </a>
            </li>

            {#if $ae_loc.administrator_access}
                <li>
                    <strong class="text-sm">Location passcode:</strong>
                    <span class="fas fa-key"></span>
                    {@html $lq__event_location_obj.passcode
                        ? $lq__event_location_obj.passcode
                        : ae_snip.html__not_set}
                    <Element_ae_crud
                        api_cfg={$ae_api}
                        object_type={'event_location'}
                        object_id={$lq__event_location_obj?.event_location_id}
                        field_name={'passcode'}
                        field_type={'text'}
                        field_value={$lq__event_location_obj?.passcode}
                        allow_null={true}
                        hide_edit_btn={!$ae_loc.trusted_access ||
                            !$ae_loc.edit_mode}
                        outline_element={false}
                        show_crud={false}
                        display_inline={true}
                        display_block_edit={false}
                        class_li={''}
                        on:ae_crud_updated={(e) => {
                            console.log(`ae_crud_updated:`, e.detail);

                            events_func
                                .load_ae_obj_id__event_location({
                                    api_cfg: $ae_api,
                                    event_location_id:
                                        $lq__event_location_obj?.event_location_id,
                                    log_lvl: 1
                                })
                                .then(function (load_results) {});
                        }}
                    ></Element_ae_crud>
                </li>
            {/if}

            <li>
                <div>
                    <Element_ae_crud
                        api_cfg={$ae_api}
                        object_type={'event_location'}
                        object_id={$lq__event_location_obj?.event_location_id}
                        field_name={'description'}
                        field_type={'textarea'}
                        field_value={$lq__event_location_obj.description}
                        allow_null={false}
                        hide_edit_btn={!$ae_loc.trusted_access ||
                            !$ae_loc.edit_mode}
                        outline_element={false}
                        show_crud={false}
                        display_inline={true}
                        display_block_edit={true}
                        textarea_rows={15}
                        class_li={''}
                        on:ae_crud_updated={(e) => {
                            console.log(`ae_crud_updated:`, e.detail);

                            events_func.load_ae_obj_id__event_location({
                                api_cfg: $ae_api,
                                event_location_id:
                                    $lq__event_location_obj?.event_location_id,
                                log_lvl: 1
                            });
                        }}
                    >
                        <strong class="text-sm"> Location description: </strong>

                        {#if $lq__event_location_obj.description}
                            <button
                                type="button"
                                onclick={() => {
                                    console.log('Show/Hide Description');
                                    $events_loc.pres_mgmt.show_content__location_description =
                                        !$events_loc.pres_mgmt
                                            .show_content__location_description;
                                }}
                                class="btn btn-sm preset-tonal-surface hover:preset-filled-surface-500 text-xs"
                            >
                                {#if $events_loc.pres_mgmt.show_content__location_description}
                                    <span class="fas fa-eye-slash mx-1"></span>
                                    <span>Hide Description</span>
                                {:else}
                                    <span class="fas fa-eye mx-1"></span>
                                    <span>Show</span>
                                {/if}
                            </button>

                            <pre
                                class="whitespace-pre-wrap p-2 bg-gray-100 rounded-md"
                                class:hidden={!$events_loc.pres_mgmt
                                    .show_content__location_description}>{$lq__event_location_obj.description}</pre>
                        {:else}
                            {@html ae_snip.html__not_set}
                        {/if}
                    </Element_ae_crud>
                </div>
            </li>
        </ul>

        <div class="m-1 flex flex-col flex-wrap gap-1 items-center">
            {#if $ae_loc.trusted_access}
                <!-- Message if they have agreed -->
                <Element_data_store
                    ds_code="events__pres_mgmt__location_page_authorized_info"
                    ds_name="Default: Events - Pres Mgmt Location Authorized Info"
                    ds_type="html"
                    for_type="event"
                    for_id={$lq__event_presentation_obj?.event_id}
                    class_li="w-fit max-w-(--breakpoint-lg) flex flex-col gap-1"
                    show_edit={false}
                    show_edit_btn={true}
                />
            {:else}
                Not authorized
            {/if}
        </div>
    </section>
{/if}

<style lang="postcss">
    /* Use the div.ae_quick_modal_container to block background clicks when using the section.ae_quick_popover. */
    div.ae_quick_modal_container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 100;
        background-color: hsla(0, 0%, 50%, 0.75);
        /* padding: 1rem; */
        /* border: solid thick red; */
    }

    /* The section.ae_quick_popover should be above the rest of the content and centered on the page. */
    section.ae_quick_popover {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 100;
        background-color: hsla(0, 0%, 97%, 0.97);
        /* margin-top: 1rem;
    margin-bottom: 2rem; */
        /* padding: 1rem;
    padding-top:4rem; */
        /* padding-bottom: 4rem; */
        border: solid thin hsla(0, 0%, 0%, 0.9);
        border-radius: 0.5rem;
        box-shadow: 0 0 1rem hsla(0, 0%, 0%, 0.5);

        min-height: 30%;
        /* max-height: 100vh; */
        min-width: 80%;

        /* overflow-y: auto; */
    }
</style>
