<script lang="ts">
interface Props {
    lq__archive_content_obj_li: any;
}

let { lq__archive_content_obj_li }: Props = $props();

// *** Import Svelte specific
import { goto, invalidate, pushState, replaceState } from '$app/navigation';

// *** Import Aether specific variables and functions
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { api } from '$lib/ae_api/api';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { idaa_loc, idaa_sess, idaa_slct } from '$lib/stores/ae_idaa_stores';
import { archives_func } from '$lib/ae_archives/ae_archives_functions';

import AE_Comp_Hosted_Files_Download_Button from '$lib/elements/ae_comp__hosted_files_download_button.svelte';

let creating = $state(false); // true while create API call is in-flight

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

// This should be moved to a better location. Turn into a function?
let file_icons: any = $state({});
file_icons['ac3'] = 'file-audio';
file_icons['aac'] = 'file-audio';
file_icons['csv'] = 'file-csv';
file_icons['doc'] = 'file-word';
file_icons['docx'] = 'file-word';
file_icons['gif'] = 'file-image';
file_icons['htm'] = 'file-code';
file_icons['html'] = 'file-code';
file_icons['jpeg'] = 'file-image';
file_icons['jpg'] = 'file-image';
file_icons['key'] = 'file-powerpoint';
file_icons['m4a'] = 'file-audio';
file_icons['mkv'] = 'file-video';
file_icons['mov'] = 'file-video';
file_icons['mp3'] = 'file-audio';
file_icons['mp4'] = 'file-video';
file_icons['mp4'] = 'file-video';
file_icons['pdf'] = 'file-pdf';
file_icons['png'] = 'file-image';
file_icons['ppt'] = 'file-powerpoint';
file_icons['pptx'] = 'file-powerpoint';
file_icons['txt'] = 'file-alt';
file_icons['wav'] = 'file-audio';
file_icons['webp'] = 'file-image';
file_icons['xls'] = 'file-excel';
file_icons['xlsx'] = 'file-excel';
file_icons['zip'] = 'file-archive';
</script>

<section
    class="archive_list flex w-full flex-col items-center justify-center gap-2">
    {#if $ae_loc.trusted_access && $ae_loc.edit_mode}
        <div
            class="mb-2 flex w-full max-w-(--breakpoint-lg) flex-row items-center justify-center px-2">
            <button
                type="button"
                disabled={creating}
                onclick={() => {
                    creating = true;

                    archives_func
                        .create_ae_obj__archive_content({
                            api_cfg: $ae_api,
                            archive_id: $idaa_slct.archive_id,
                            data_kv: {
                                name: 'New Archive Content',
                                enable: true,
                                // NOTE: Pre-populate timezone from the parent archive so staff
                                // don't have to re-select it for every piece of content.
                                original_timezone:
                                    $idaa_slct.archive_obj?.original_timezone ??
                                    null
                            }
                        })
                        .then((result) => {
                            const archive_content_id =
                                result?.id || result?.archive_content_id;
                            if (archive_content_id) {
                                $idaa_slct.archive_content_id =
                                    archive_content_id;
                                $idaa_slct.archive_content_obj = result;
                                $idaa_sess.archives.show__modal_view__archive_content_id = false;
                                $idaa_sess.archives.show__modal_edit__archive_content_id =
                                    archive_content_id;
                            } else {
                                creating = false;
                                alert('Failed to create archive content.');
                            }
                        })
                        .catch((err) => {
                            console.error(
                                'Error creating archive content:',
                                err
                            );
                            creating = false;
                            alert('Failed to create archive content.');
                        })
                        .finally(() => {
                            creating = false;
                        });
                }}
                class="
                    novi_btn
                    btn btn-sm
                    preset-tonal-warning preset-outlined-warning-200-800 hover:preset-filled-warning-200-800
                    transition
                "
                title="Create new archive content item">
                {#if creating}
                    <span class="fas fa-spinner fa-spin m-1"></span> Creating...
                {:else}
                    <span class="fas fa-plus m-1"></span> Create New Archive Content
                {/if}
            </button>
        </div>
    {/if}

    {#if $lq__archive_content_obj_li && $lq__archive_content_obj_li.length}
        <!-- <div class="ae_group">
    <span class="ae_label">Group:</span>
    <span class="ae_value">{current_group}</span> -->

        {#each $lq__archive_content_obj_li as idaa_archive_content_obj, index (idaa_archive_content_obj.archive_content_id)}
            {#if idaa_archive_content_obj.group && idaa_archive_content_obj.group != $lq__archive_content_obj_li[index - 1]?.group}
                <!-- NOTE: m-auto is needed for the Novi site centering -->
                <div
                    class="
            ae_row archive_content__group
            m-auto
            flex w-full max-w-(--breakpoint-lg) flex-row items-center justify-center rounded-lg
            bg-white p-2
            ">
                    <button
                        type="button"
                        class="novi_btn novi_margin_sm btn btn-md btn-info preset-tonal-secondary hover:preset-filled-secondary-500 w-96 transition"
                        onclick={() => {
                            if (
                                $idaa_sess.archives
                                    .show_list__archive_content_li_group ==
                                idaa_archive_content_obj.group
                            ) {
                                $idaa_sess.archives.show_list__archive_content_li_group =
                                    null;
                            } else {
                                $idaa_sess.archives.show_list__archive_content_li_group =
                                    idaa_archive_content_obj.group;
                            }
                        }}>
                        {#if $idaa_sess.archives.show_list__archive_content_li_group == idaa_archive_content_obj.group}
                            <span class="fas fa-caret-down"></span>
                            <!-- <span class="fas fa-minus"></span> -->
                            <span class="ae_label text-xs">Hide:</span>
                        {:else}
                            <span class="fas fa-caret-right"></span>
                            <!-- <span class="fas fa-plus"></span> -->
                            <span class="ae_label text-xs">Show:</span>
                        {/if}
                        <!-- <span class="fas fa-caret-down"></span> -->
                        <!-- <span class="ae_label">Show:</span> -->
                        <span class="ae_value text-lg font-bold"
                            >{idaa_archive_content_obj.group}</span>
                    </button>
                </div>
            {/if}

            {#if $idaa_sess.archives.show_list__archive_content_li_group == idaa_archive_content_obj.group}
                <div
                    class="archive archive_content_obj container mb-2 flex w-full max-w-(--breakpoint-lg) flex-col items-center justify-center space-y-2 rounded-lg border bg-white p-2"
                    class:hidden={(idaa_archive_content_obj.hide ||
                        !idaa_archive_content_obj?.enable) &&
                        !$ae_loc.edit_mode}
                    class:dim={idaa_archive_content_obj.hide &&
                        $ae_loc.edit_mode}
                    class:dim_warning={!idaa_archive_content_obj?.enable &&
                        $ae_loc.edit_mode}>
                    <header class="ae_header flex flex-row items-center gap-2">
                        <h3 class="archive__name h4">
                            <span class="archive__name"
                                >{@html idaa_archive_content_obj.name}</span>
                        </h3>

                        {#if idaa_archive_content_obj.original_location}
                            —
                            <h4 class="h5">
                                <!-- <span class="ae_label">Location:</span> -->
                                <span class="ae_value"
                                    >{idaa_archive_content_obj.original_location}</span>
                            </h4>
                        {/if}
                    </header>

                    {#if idaa_archive_content_obj.description}<pre
                            class="archive__description rounded-lg bg-white p-2 text-sm font-normal text-wrap whitespace-pre-wrap shadow-md">{@html idaa_archive_content_obj.description}</pre>{/if}

                    <div
                        class="ae_options flex flex-row flex-wrap items-center justify-center gap-2">
                        {#if idaa_archive_content_obj?.hosted_file_id}
                            <button
                                type="button"
                                disabled={!$ae_loc.authenticated_access}
                                onclick={() => {
                                    $idaa_slct.archive_content_id =
                                        idaa_archive_content_obj?.archive_content_id;
                                    $idaa_slct.archive_content_obj =
                                        idaa_archive_content_obj;

                                    const url = new URL(location.href);
                                    url.searchParams.set(
                                        'archive_content_id',
                                        idaa_archive_content_obj?.archive_content_id
                                    );
                                    pushState(url, {});
                                    // replaceState(url, {});

                                    let message = {
                                        archive_content_id:
                                            $idaa_slct?.archive_content_id
                                    };
                                    window.parent.postMessage(message, '*');

                                    // handle_load_post_comment_obj_li({archive_id: $idaa_slct.archive_id, try_cache: false});

                                    // const url = new URL(location);
                                    // url.searchParams.set('archive_id', idaa_archive_content_obj?.archive_id);
                                    // history.pushState({}, '', url);

                                    // let message = {'archive_id': idaa_archive_content_obj?.archive_id};
                                    // window.parent.postMessage(message, "*");

                                    $idaa_sess.archives.show__modal_view__archive_content_id =
                                        $idaa_slct.archive_content_id;
                                    $idaa_sess.archives.show__modal_edit__archive_content_id = false;
                                }}
                                class="novi_btn btn btn-md btn-secondary preset-tonal-primary border-primary-500 hover:preset-filled-primary-500 border transition"
                                title={`Play/View: ${idaa_archive_content_obj?.name}`}>
                                <span
                                    class="fas fa-play m-1 text-neutral-800/80"
                                ></span>
                                {#if file_icons[idaa_archive_content_obj.file_extension] == 'file-audio' || file_icons[idaa_archive_content_obj.file_extension] == 'file-video'}
                                    Play
                                {:else}
                                    View
                                {/if}
                                <span
                                    class="fas fa-{ae_util.file_extension_icon(
                                        idaa_archive_content_obj?.file_extension
                                    )}"></span>
                            </button>

                            {#if $ae_loc.trusted_access && idaa_archive_content_obj?.hosted_file_id}
                                <AE_Comp_Hosted_Files_Download_Button
                                    hosted_file_id={idaa_archive_content_obj.hosted_file_id}
                                    hosted_file_obj={idaa_archive_content_obj}
                                    max_filename={30}
                                    classes="novi_btn btn btn-sm lg:btn-md preset-tonal-primary hover:preset-filled-primary-500 min-w-72 lg:min-w-96"
                                    linked_to_type="archive_content"
                                    linked_to_id={idaa_archive_content_obj.archive_content_id} />
                            {/if}
                        {:else}
                            <span
                                class="text-sm text-gray-500 italic"
                                title="No file linked.">
                                <span
                                    class="fas fa-exclamation-triangle text-warning"
                                ></span>
                                No file linked.
                                <span
                                    class="fas fa-exclamation-triangle text-warning"
                                ></span>
                            </span>
                        {/if}

                        {#if $ae_loc.trusted_access && $ae_loc.edit_mode}
                            <button
                                type="button"
                                disabled={!$ae_loc.trusted_access}
                                onclick={() => {
                                    $idaa_slct.archive_content_id =
                                        idaa_archive_content_obj.archive_content_id;
                                    $idaa_slct.archive_content_obj =
                                        idaa_archive_content_obj;

                                    $idaa_sess.archives.show__modal_view__archive_content_id = false;
                                    $idaa_sess.archives.show__modal_edit__archive_content_id =
                                        $idaa_slct.archive_content_id;
                                }}
                                class="novi_btn btn btn-sm preset-tonal-warning hover:preset-filled-warning-500 transition"
                                title={`Edit archive content: ${idaa_archive_content_obj?.name}`}>
                                <span class="fas fa-edit m-1"></span> Edit Content
                            </button>
                        {/if}
                    </div>

                    <section class="ae_section archive_content__content">
                        {#if idaa_archive_content_obj?.description}
                            <div
                                class="archive_content__description ae_description">
                                <div
                                    class="ae_label archive_content__description text-sm">
                                    Description:
                                </div>
                                <div
                                    class="ae_value archive_content__description">
                                    {@html idaa_archive_content_obj?.description}
                                </div>
                            </div>
                        {/if}

                        {#if idaa_archive_content_obj?.content_html}
                            <div
                                class="archive_content__content_html ae_content_html">
                                <div
                                    class="ae_label archive_content__content_html text-sm">
                                    Content:
                                </div>
                                <div
                                    class="ae_value archive_content__content_html">
                                    {@html idaa_archive_content_obj?.content_html}
                                </div>
                            </div>
                        {/if}

                        <div
                            class="ae_group"
                            class:hidden={!idaa_archive_content_obj?.original_datetime &&
                                !idaa_archive_content_obj?.original_timezone}>
                            <span class="ae_label text-sm"
                                >Original date/time:</span>
                            {#if idaa_archive_content_obj.original_datetime}
                                <span
                                    class="ae_value ae_prop prop_original_datetime font-semibold"
                                    >{ae_util.iso_datetime_formatter(
                                        idaa_archive_content_obj.original_datetime,
                                        'datetime_12_long'
                                    )}</span>
                            {/if}
                            {#if idaa_archive_content_obj.original_timezone}
                                <span class="ae_label text-sm">Timezone:</span>
                                <span class="ae_value font-semibold"
                                    >{idaa_archive_content_obj.original_timezone}</span>
                            {/if}
                        </div>
                    </section>

                    <section
                        class="ae_meta mt-2 flex flex-col items-center justify-center gap-1 text-sm text-gray-500 sm:flex-row"
                        class:hidden={!$ae_loc.administrator_access}>
                        <span
                            class="archive_content__archive_content_type"
                            class:hidden={!idaa_archive_content_obj.archive_content_type}>
                            Type: {idaa_archive_content_obj.archive_content_type}
                        </span>
                        <span class="ae_group">
                            <span class="archive_content__created_on">
                                Created on: {ae_util.iso_datetime_formatter(
                                    idaa_archive_content_obj.created_on,
                                    'datetime_12_long'
                                )}
                            </span>
                            <span
                                class="archive_content__updated_on"
                                class:hidden={!idaa_archive_content_obj.updated_on}>
                                Updated on: {ae_util.iso_datetime_formatter(
                                    idaa_archive_content_obj.updated_on,
                                    'datetime_12_long'
                                )}
                            </span>
                        </span>
                    </section>
                </div>
            {/if}
        {/each}

        <!-- </div> -->
    {:else}
        <p>No archive content available to show.</p>
    {/if}
</section>
<!-- {/if} -->
