<script lang="ts">
// let log_lvl: number = 0;

// *** Import Svelte specific
import { goto } from '$app/navigation';

// *** Import other supporting libraries

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

interface Props {
    lq__archive_obj_li: any;
}

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

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

// Local Sort State
let qry_sort_mode = $state('priority_sort'); // 'priority_sort', 'updated_desc', 'name_asc'

let sorted_archive_obj_li = $derived.by(() => {
    const list = [...($lq__archive_obj_li ?? [])];
    if (!list.length) return [];

    list.sort((a, b) => {
        if (qry_sort_mode === 'priority_sort') {
            const prioA = a.priority ? 1 : 0;
            const prioB = b.priority ? 1 : 0;
            if (prioA !== prioB) return prioB - prioA;

            const sortA = a.sort ?? 0;
            const sortB = b.sort ?? 0;
            if (sortA !== sortB) return sortB - sortA;
        } else if (qry_sort_mode === 'updated_desc') {
            // SORT: Most recently updated or created at the top (Refactored 2026-02-16)
            // ROBUSTNESS: Ensure fallback to created_on then to 0 to prevent NaN comparison issues
            const date_a =
                new Date(a.updated_on ?? a.created_on ?? 0).getTime() || 0;
            const date_b =
                new Date(b.updated_on ?? b.created_on ?? 0).getTime() || 0;
            return date_b - date_a;
        }

        // Default fallback: Name
        return (a.name ?? '').localeCompare(b.name ?? '');
    });

    return list;
});
</script>

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

                    archives_func
                        .create_ae_obj__archive({
                            api_cfg: $ae_api,
                            account_id: $ae_loc.account_id,
                            data_kv: { name: 'New Archive', enable: true }
                        })
                        .then((result) => {
                            const archive_id = result?.id || result?.archive_id;
                            if (archive_id) {
                                $idaa_slct.archive_id = archive_id;
                                // NOTE: Set the edit modal flag before navigating so the detail page
                                // opens with the edit form already visible — saves an extra click.
                                $idaa_sess.archives.show__modal_edit__archive_id = true;
                                goto(`/idaa/archives/${archive_id}`);
                            } else {
                                creating = false;
                                alert('Failed to create archive.');
                            }
                        })
                        .catch((err) => {
                            console.error('Error creating archive:', err);
                            creating = false;
                            alert('Failed to create archive.');
                        });
                }}
                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">
                {#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
                {/if}
            </button>
        {/if}

        <div class="flex flex-row items-center gap-2">
            <span class="text-xs font-bold tracking-widest uppercase opacity-50"
                >Sort By:</span>
            <select
                bind:value={qry_sort_mode}
                class="select variant-filled-surface border-surface-500/20 w-fit rounded-lg border p-1 text-sm">
                <option value="priority_sort">Priority & Order</option>
                <option value="name_asc">Name (A-Z)</option>
                <option value="updated_desc">Recently Updated</option>
            </select>
        </div>
    </div>

    {#if sorted_archive_obj_li && sorted_archive_obj_li.length}
        {#each sorted_archive_obj_li as idaa_archive_obj, index (idaa_archive_obj.archive_id)}
            <div
                class="archive archive_obj container mb-2 flex w-full max-w-(--breakpoint-lg) flex-col items-center justify-center space-y-2 rounded border p-2"
                class:hidden={(idaa_archive_obj?.hide ||
                    !idaa_archive_obj?.enable) &&
                    !$ae_loc.trusted_access}
                class:dim={idaa_archive_obj.hide}
                class:bg-warning-100={!idaa_archive_obj?.enable}
                class:text-warning-900={!idaa_archive_obj?.enable}>
                <header
                    class="ae_header flex w-full flex-row items-center justify-between gap-2">
                    <h3 class="archive__name h3">
                        <span class="fas fa-archive m-1 text-neutral-800/80"
                        ></span>
                        <span class="archive__name"
                            >{@html idaa_archive_obj.name}</span>
                    </h3>

                    {#if idaa_archive_obj.original_location}
                        <!-- &mdash; -->
                        <h4 class="h4">
                            <!-- <span class="ae_label">Location:</span> -->
                            <span class="ae_value"
                                >{idaa_archive_obj.original_location}</span>
                        </h4>
                    {/if}
                </header>

                {#if idaa_archive_obj.description}<pre
                        class="archive__description word-break novi_text_wrap max-w-(--breakpoint-md) rounded-lg bg-white p-2 text-sm font-normal text-wrap whitespace-pre-wrap shadow-md">{@html idaa_archive_obj.description}</pre>{/if}

                <div
                    class="ae_options flex flex-row items-center justify-center gap-2">
                    <a
                        href="/idaa/archives/{idaa_archive_obj?.archive_id}"
                        class="
                    novi_btn btn-secondary
                    btn btn-md preset-filled-primary-200-800
                    transition
                    "
                        title={`View: ${idaa_archive_obj?.name}`}>
                        <!-- <span class="fas fa-envelope-open m-1"></span> -->
                        <span class="fas fa-box-open m-1 text-neutral-800/80"
                        ></span>
                        Open

                        {#if idaa_archive_obj?.archive_content_count}
                            <span
                                class="ae_badge ae_info archive__archive_content_count">
                                <span class="fas fa-content"></span>
                                {idaa_archive_obj?.archive_content_count == 1
                                    ? `${idaa_archive_obj?.archive_content_count} content`
                                    : `${idaa_archive_obj?.archive_content_count} contents`}
                            </span>
                        {/if}
                    </a>
                </div>

                <section
                    class="ae_section ae_footer ae_meta archive__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 &&
                        !$ae_loc.edit_mode}>
                    <div class="ae_group">
                        {#if !idaa_archive_obj.updated_on}
                            <span class="archive__created_on">
                                <span class="ae_label">Created on:</span>
                                <span class="ae_value"
                                    >{ae_util.iso_datetime_formatter(
                                        idaa_archive_obj.created_on,
                                        'datetime_12_long'
                                    )}</span>
                            </span>
                        {:else}
                            <span class="archive__updated_on">
                                <span class="ae_label">Updated on:</span>
                                <span class="ae_value"
                                    >{ae_util.iso_datetime_formatter(
                                        idaa_archive_obj.updated_on,
                                        'datetime_12_long'
                                    )}</span>
                            </span>
                        {/if}
                    </div>
                </section>
            </div>
        {/each}
    {:else}
        No archives found at this time
    {/if}
</section>
<!-- {/if} -->
