<script lang="ts">
interface Props {
    /** @type {import('./$types').PageData} */
    data: any;
}

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

let log_lvl: number = 0;

// *** Import Svelte specific
import { onMount, onDestroy, untrack } from 'svelte';

// *** Import other supporting libraries
import { Modal } from 'flowbite-svelte';
import { liveQuery } from 'dexie';

// *** Import Aether specific variables and functions
// import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
// import { core_func } from '$lib/ae_core/ae_core_functions';
import { db_archives, type Archive } from '$lib/ae_archives/db_archives';
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,
    idaa_trig,
    idaa_prom
} from '$lib/stores/ae_idaa_stores';
import { archives_func } from '$lib/ae_archives/ae_archives_functions';

import Archive_obj_id_edit from './ae_idaa_comp__archive_obj_id_edit.svelte';
import Archive_view from './ae_idaa_comp__archive_obj_id_view.svelte';

import Archive_content_obj_li from './ae_idaa_comp__archive_content_obj_li.svelte';
import Archive_content_obj_id_edit from './ae_idaa_comp__archive_content_obj_id_edit.svelte';
import Modal_media_player from './ae_idaa_comp__modal_media_player.svelte';
import Help_tech from '$lib/app_components/e_app_help_tech.svelte';
import { page } from '$app/state';

// let ae_promises: key_val = {};
// let ae_tmp: key_val = {};
// let ae_triggers: key_val = {};

let archive_content_edit_dirty = $state(false);

// *** Quickly pull out data from parent(s)
let ae_acct = $derived(data[data.account_id]);
$effect(() => {
    if (log_lvl) {
        console.log(`ae_acct = `, ae_acct);
    }
});

// For some reason data.params.archive_id (or whatever param) is not being passed to this page when loaded by a link from another page. This seems to be a bug with Svelte or SvelteKit. Hopefully fixed in a future version 5? 2024-11-06
// SVELTE 5 FIX: Use page.params directly for robust reactivity
$idaa_slct.archive_id = page.params.archive_id;
// $idaa_slct.archive_obj = ae_acct.slct.archive_obj;

// Load single archive with content — gated on auth.
// WHY $effect and not +page.ts: +page.ts runs during SvelteKit link prefetch,
// causing private IDAA data to be written to IDB before Novi auth runs.
// $effect only runs post-mount, after the layout has completed Novi verification.
$effect(() => {
    if (!$idaa_loc.novi_verified && !$ae_loc.trusted_access) return;
    const archive_id = $idaa_slct.archive_id;
    if (!archive_id) return;
    untrack(() => {
        archives_func.load_ae_obj_id__archive({
            api_cfg: $ae_api,
            archive_id: archive_id,
            inc_content_li: true,
            enabled: 'enabled',
            hidden: 'all',
            limit: 99,
            log_lvl: log_lvl
        }).then((results) => {
            if (!results) {
                console.warn(
                    `IDAA Archives [archive_id] $effect: Archive ${archive_id} not found via API or Cache.`
                );
            }
        });
    });
});

// *** Functions and Logic
let lq__archive_obj = $derived(
    liveQuery(async () => {
        if (log_lvl) {
            console.log(
                `lq__archive_obj: archive_id = ${$idaa_slct?.archive_id}`
            );
        }
        let results = await db_archives.archive.get(
            $idaa_slct?.archive_id ?? ''
        ); // null or undefined does not reset things like '' does

        // Check if results are different than the current $idaa_slct.archive_obj
        if ($idaa_slct.archive_obj && results) {
            if (
                JSON.stringify($idaa_slct.archive_obj) !==
                JSON.stringify(results)
            ) {
                $idaa_slct.archive_obj = { ...results };
                if (log_lvl) {
                    console.log(
                        `$idaa_slct.archive_obj = `,
                        $idaa_slct.archive_obj
                    );
                }
            } else {
                if (log_lvl) {
                    console.log(
                        `Archive object has not changed for archive_id: ${$idaa_slct.archive_id}`
                    );
                }
            }
        }

        return results as Archive;
    })
);

// Reactive Archive Content list using Dexie LiveQuery
let lq__archive_content_obj_li = $derived.by(() => {
    // SVELTE 5 REACTIVITY: Track the archive_id store synchronously
    const archive_id = $idaa_slct.archive_id;

    return liveQuery(async () => {
        if (!archive_id) return [];

        // Fetch the parent archive and its contents in parallel
        // Dexie will automatically track these table accesses and re-run this query if they change.
        const [parent_archive, results] = await Promise.all([
            db_archives.archive.get(archive_id),
            db_archives.content.where('archive_id').equals(archive_id).toArray()
        ]);

        if (!results || results.length === 0) {
            if (log_lvl)
                console.log(
                    'lq__archive_content_obj_li: No content records found in cache.'
                );
            return [];
        }

        // Determine sort mode from the parent archive configuration
        const sort_mode = parent_archive?.cfg_json?.content_group_sort ?? 'ASC';
        const is_desc = sort_mode === 'DESC';

        if (log_lvl) {
            console.log(
                `lq__archive_content_obj_li: Sorting ${results.length} items using ${sort_mode} mode.`
            );
        }

        // Apply multi-step in-memory sort to handle mixed directions (e.g. Group DESC + Sort ASC)
        results.sort((a, b) => {
            const groupA = a.group ?? '';
            const groupB = b.group ?? '';

            if (is_desc) {
                // MODE: Newest First (DESC) - Typically used for years or chronological groupings

                // 1. Group (DESC) - e.g. Year "2024" should appear before "2023"
                if (groupA !== groupB) return groupB.localeCompare(groupA);

                // 2. Original Datetime (DESC) - Newer items within the same group first
                const dateA = a.original_datetime
                    ? new Date(a.original_datetime).getTime()
                    : 0;
                const dateB = b.original_datetime
                    ? new Date(b.original_datetime).getTime()
                    : 0;
                if (dateA !== dateB) return dateB - dateA;
            } else {
                // MODE: Standard (ASC) - Typically used for Parts, Chapters, or alphabetical groupings

                // 1. Group (ASC) - e.g. "Part 1" before "Part 2"
                if (groupA !== groupB) return groupA.localeCompare(groupB);
            }

            // 3. Priority (DESC) - Starred items always at the top of their subgroup
            const prioA = a.priority ? 1 : 0;
            const prioB = b.priority ? 1 : 0;
            if (prioA !== prioB) return prioB - prioA;

            // 4. Sort (ASC) - Manual Sort order "1" should remain above "2" even in DESC mode
            const sortA = a.sort ?? 0;
            const sortB = b.sort ?? 0;
            if (sortA !== sortB) return sortA - sortB;

            // 5. Fallback: Original Datetime ASC (if in Standard mode and manual sorts are equal)
            if (!is_desc) {
                const dateA = a.original_datetime
                    ? new Date(a.original_datetime).getTime()
                    : 0;
                const dateB = b.original_datetime
                    ? new Date(b.original_datetime).getTime()
                    : 0;
                if (dateA !== dateB) return dateA - dateB;
            }

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

        return results;
    });
});

let lq__archive_content_obj = $derived(
    liveQuery(async () => {
        if (log_lvl) {
            console.log(
                `lq__archive_content_obj: archive_content_id = ${$idaa_slct?.archive_content_id}`
            );
        }
        // if ($idaa_slct.archive_content_id) {
        let results = await db_archives.content.get(
            $idaa_slct.archive_content_id ?? ''
        ); // null or undefined does not reset things like '' does

        // Check if results are different than the current $idaa_slct.archive_content_obj
        if ($idaa_slct.archive_content_obj && results) {
            if (
                JSON.stringify($idaa_slct.archive_content_obj) !==
                JSON.stringify(results)
            ) {
                $idaa_slct.archive_content_obj = { ...results };
                if (log_lvl) {
                    console.log(
                        `$idaa_slct.archive_content_obj = `,
                        $idaa_slct.archive_content_obj
                    );
                }
            } else {
                if (log_lvl) {
                    console.log(
                        `Archive content object has not changed for archive_content_id: ${$idaa_slct.archive_content_id}`
                    );
                }
            }
        }

        return results;
        // }
    })
);

$effect(() => {
    if ($idaa_trig.archive_content_li) {
        $idaa_trig.archive_content_li = false;

        if (log_lvl) {
            console.log(`Triggered: $idaa_trig.archive_content_li`);
        }

        if (
            $idaa_loc.archives.qry__enabled !== 'all' ||
            $idaa_loc.archives.qry__hidden !== 'all'
        ) {
            console.log(`Deleting disabled or hidden archive content.`);
            // let results = db_archives.content
            //     .where('enable')
            //     .notEqual(true)
            //     .delete();
            let results = db_archives.content.clear();
            console.log(`Deleted ${results} disabled archive content.`);
        }
        // if ($idaa_loc.archives.qry__hidden !== 'all') {
        //     console.log(`Deleting hidden archive content.`);
        //     let results = db_archives.content
        //         .clear();
        //     console.log(`Deleted ${results} hidden archive content.`);

        // }
        // let results = db_archives.content
        //     .where('enable')
        //     .equals('false')
        //     .delete();
        // console.log(`Deleted ${results} disabled archive content.`);

        $idaa_prom.load__archive_content_obj_li =
            archives_func.load_ae_obj_li__archive_content({
                api_cfg: $ae_api,
                for_obj_type: 'archive',
                for_obj_id: $idaa_slct.archive_id,
                enabled: $idaa_loc.archives.qry__enabled,
                hidden: $idaa_loc.archives.qry__hidden,
                limit: $idaa_loc.archives.qry__limit,
                order_by_li: $idaa_loc.archives.qry__order_by_li,
                try_cache: true,
                log_lvl: log_lvl
            });
    }
});

onMount(() => {
    console.log('Browser environment detected.');

    // NOTE: Use data[data.account_id].slct.archive_id (from load / URL params),
    // NOT $idaa_slct.archive_id (the store). The store is updated by a $effect that runs
    // after this synchronous block — reading it here sends the old/null value.
    let message = {
        archive_id: data[data.account_id]?.slct?.archive_id ?? null
    };
    window.parent.postMessage(message, '*');

    if ($ae_loc?.iframe) {
        console.log(
            'In iframe, sending message to parent window to scroll to top as well'
        );
        window.parent.postMessage({ scroll_to: 0 }, '*'); // This should be in pixels
    }
});

onDestroy(() => {
    log_lvl = 1;
    if (log_lvl) {
        console.log(
            `Destroying archives page for archive_id: ${$idaa_slct?.archive_id}`
        );
    }

    let message = { archive_id: null };
    window.parent.postMessage(message, '*');

    // $idaa_slct.archive_id = null;
    // $idaa_slct.archive_obj = null;
});
</script>

<svelte:head>
    <title>
        IDAA Archives:
        {$lq__archive_obj?.name
            ? ae_util.shorten_string({
                  string: $lq__archive_obj?.name,
                  max_length: 20,
                  begin_length: 10,
                  end_length: 4
              })
            : ''}
        - Novi - {$ae_loc?.title}
    </title>
</svelte:head>

<!-- <h1>Archives {$lq__archive_obj?.name} - {$lq__archive_content_obj_li?.length}</h1> -->

<div
    class="ae_header archive__header flex w-full flex-row flex-wrap items-center justify-evenly gap-2">
    <h2
        class="
            archive__name
            h3
            flex max-w-full
            min-w-1/2 flex-row items-center justify-center gap-2
            text-2xl
            font-bold
            ">
        <span class="ae_icon fas fa-archive text-neutral-800/80"></span>
        <!-- <span class="ae_icon fas fa-file-archive"></span> -->
        {$lq__archive_obj?.name ?? 'Archive'}
        {#if $ae_loc.trusted_access && $ae_loc.edit_mode}
            ({$lq__archive_content_obj_li?.length ?? '0'}×)
        {/if}
        {#await $idaa_prom.load__archive_content_obj_li}
            <span class="fas fa-spinner fa-spin"></span>
        {:then}
            <!-- done -->
        {/await}
    </h2>

    <div
        class="
            flex max-w-full min-w-1/4 flex-row items-center
            justify-evenly
            gap-2
        ">
        <span
            class="float-right flex flex-row flex-wrap items-center justify-end gap-1">
            {#if $lq__archive_obj?.topic_name}
                <span class="badge badge-info preset-tonal-tertiary"
                    ><span class="fas fa-user-md m-1"></span>
                    {$lq__archive_obj?.topic_name}</span>
            {/if}
            {#if $ae_loc.trusted_access && $lq__archive_obj?.hide}
                <span class="badge badge-warning"
                    ><span class="fas fa-exclamation-triangle m-1"></span> Hidden</span>
            {/if}
            {#if $ae_loc.administrator_access && !$lq__archive_obj?.enable}
                <span class="badge badge-warning preset-tonal-warning"
                    ><span class="fas fa-exclamation-triangle m-1"></span> Not enabled</span>
            {/if}
        </span>
    </div>

    <Help_tech
        e_class=""
        e_class_h1="novi_m0"
        e_class_h2="novi_m0"
        btn_class="novi_btn"
        show_btn_class="absolute top-0 right-0 float-right z-10"
        additional_kv={{
            novi_uuid: $idaa_loc.novi_uuid,
            novi_email: $idaa_loc.novi_email,
            novi_full_name: $idaa_loc.novi_full_name
        }}></Help_tech>
</div>

<div
    class="
        border-b-surface-300-700 mb-2 flex w-full flex-row
        items-center
        justify-center gap-2 border-b
        p-1 pb-2
        ">
    <a
        href="/idaa/archives"
        class="novi_btn btn btn-secondary btn-sm
        preset-tonal-tertiary border-tertiary-500 hover:preset-filled-tertiary-500
        border
        transition
        ">
        <!-- <span class="fas fa-arrow-left m-1"></span> Back to Archives -->
        <span class="fas fa-times m-1"></span> View Other Archives
    </a>
</div>

<Archive_view {lq__archive_obj} {lq__archive_content_obj_li} />

<Archive_content_obj_li {lq__archive_content_obj_li} />

<!-- Modal: Archive edit ID -->
<Modal
    title="{$lq__archive_obj?.name} - {$lq__archive_obj?.id}"
    bind:open={$idaa_sess.archives.show__modal_edit__archive_id}
    autoclose={false}
    placement="top-center"
    size="xl"
    class="top-center relative mx-auto flex w-full flex-col divide-y divide-gray-200 rounded-lg border-gray-200 bg-white text-gray-800 shadow-md dark:divide-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200">
    {#snippet header()}
        <div class="flex w-full flex-row items-center justify-between">
            <h3 class="text-lg font-semibold">
                {#if $ae_loc.trusted_access}
                    <!-- <div class="ae_options"> -->
                    <button
                        type="button"
                        onclick={() => {
                            // const url = new URL(location);
                            // url.searchParams.set('event_id', $lq__archive_obj?.event_id);
                            // history.pushState({}, '', url);

                            $idaa_sess.archives.show__modal_view__archive_id =
                                $idaa_slct.archive_id;
                            $idaa_sess.archives.show__modal_edit__archive_id = false;
                        }}
                        class="novi_btn btn btn-sm preset-tonal-warning border-warning-500 hover:preset-filled-warning-500 border transition"
                        title={`View meeting: ${$lq__archive_obj?.name}`}>
                        <span class="fas fa-eye m-1"></span> View
                    </button>
                    <!-- </div> -->
                {/if}

                <span class="text-sm text-gray-500"> Edit Archive: </span>
                {$lq__archive_obj?.name}
            </h3>
        </div>
    {/snippet}

    <Archive_obj_id_edit {lq__archive_obj} />

    {#snippet footer()}
        <button
            type="button"
            class="btn btn-sm btn-secondary"
            onclick={() => {
                $idaa_sess.archives.show__modal_view__archive_id = false;
                $idaa_sess.archives.show__modal_edit__archive_id = false;
            }}>
            <span class="fas fa-times"></span>
            Close
        </button>
    {/snippet}
</Modal>

<Modal
    bind:open={$idaa_sess.archives.show__modal_edit__archive_content_id}
    autoclose={false}
    placement="top-center"
    size="xl"
    class="top-center relative mx-auto flex w-full flex-col divide-y divide-gray-200 rounded-lg border-gray-200 bg-white text-gray-800 shadow-md dark:divide-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200">
    {#snippet header()}
        <div class="flex w-full flex-row items-center justify-between">
            <h3 class="text-lg font-semibold">
                {#if $ae_loc.trusted_access && (!$idaa_slct.archive_content_id || archive_content_edit_dirty)}
                    <!-- Hidden in edit mode when nothing has changed — no unsaved changes to cancel -->
                    <button
                        type="button"
                        onclick={() => {
                            // $idaa_sess.archives.show__modal_view__archive_content_id = $idaa_slct.archive_content_id;
                            $idaa_slct.archive_content_id = null;
                            $idaa_slct.archive_content_obj = {};

                            $idaa_sess.archives.show__modal_edit__archive_content_id = false;
                        }}
                        class="novi_btn btn btn-sm preset-tonal-warning border-warning-500 hover:preset-filled-warning-500 border transition"
                        title={`View meeting: ${$lq__archive_content_obj?.name}`}>
                        <span class="fas fa-eye m-1"></span> Cancel
                    </button>
                {/if}

                <span class="text-sm text-gray-500"> Edit Content: </span>
                {$idaa_slct.archive_content_obj?.name ?? 'New Archive Content'}
            </h3>
        </div>
    {/snippet}

    <Archive_content_obj_id_edit {lq__archive_content_obj} bind:obj_changed={archive_content_edit_dirty} />

    {#snippet footer()}
        <button
            type="button"
            class="btn btn-sm btn-secondary"
            onclick={() => {
                $idaa_sess.archives.show__modal_view__archive_content_id = false;
                $idaa_sess.archives.show__modal_edit__archive_content_id = false;
            }}>
            <span class="fas fa-times"></span>
            Close
        </button>
    {/snippet}
</Modal>

<!-- Showing and hiding a modal like this seems to cause an issue with where it is rendered on the page. The <Modal> should be moved back here and the actual "player" left mostly separate. 2025-07-10 -->
<Modal_media_player {lq__archive_content_obj} />
