<script lang="ts">
/** @type {import('./$types').PageData} */
let log_lvl: number = $state(0);

// *** Import Svelte specific
import { untrack } from 'svelte';
import { browser } from '$app/environment';

// *** Import other supporting libraries
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_journals } from '$lib/ae_journals/db_journals';
import { ae_loc } from '$lib/stores/ae_stores';
import {
    journals_loc,
    journals_slct
} from '$lib/ae_journals/ae_journals_stores';

import Journal_entry_view from './../../../ae_comp__journal_entry_obj_id_view.svelte';
// import Element_data_store from '$lib/elements/element_data_store.svelte';
import AeCompModalJournalExport from '../../../ae_comp__modal_journal_export.svelte';

interface Props {
    data: {
        account_id: string;
        [key: string]: unknown;
    };
}

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

interface JournalPageAccount {
    slct: {
        journal_id: string | null;
        journal_entry_id?: string | null;
    };
}

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

// Variables
// *** Quickly pull out data from parent(s)
let ae_acct = $derived(data[data.account_id] as JournalPageAccount);
let show_export_modal = $state(false);

$effect(() => {
    if (!ae_acct) return;
    if (log_lvl) console.log(`ae_acct = `, ae_acct);
    untrack(() => {
        $journals_slct.journal_id = ae_acct.slct.journal_id;
    });
});
let lq__journal_obj = $derived(
    liveQuery(async () => {
        let results = await db_journals.journal.get(
            $journals_slct?.journal_id ?? ''
        ); // null or undefined does not reset things like '' does

        // Check if results are different than the current session version stored under $journals_slct
        if ($journals_slct.journal_obj && results) {
            if (
                JSON.stringify($journals_slct.journal_obj) !==
                JSON.stringify(results)
            ) {
                $journals_slct.journal_obj = { ...results };
            }
        }

        return results;
    })
);

$effect(() => {
    if (log_lvl) {
        console.log(
            `lq__journal_obj: journal_id = ${$journals_slct?.journal_id}`
        );
        console.log(`lq__journal_obj: results = `, lq__journal_obj);
        if ($journals_slct.journal_obj && lq__journal_obj) {
            if (
                JSON.stringify($journals_slct.journal_obj) !==
                JSON.stringify(lq__journal_obj)
            ) {
                console.log(
                    `Session slct stored version has changed for ID = ${$journals_slct.journal_id}`,
                    $journals_slct.journal_obj
                );
            } else {
                console.log(
                    `Session slct stored version has not changed for ID = ${$journals_slct.journal_id}`
                );
            }
        }
    }
});

let lq__journal_obj_li = $derived(
    liveQuery(async () => {
        let results = await db_journals.journal
            .where('person_id')
            .equals($ae_loc.person_id)
            .sortBy('tmp_sort_2');

        // Check if results are different than the current session version stored under $journals_slct
        if (
            $journals_slct.journal_obj_li &&
            JSON.stringify($journals_slct.journal_obj_li) !==
                JSON.stringify(results)
        ) {
            $journals_slct.journal_obj_li = [...results];
        }

        return results;
    })
);

$effect(() => {
    if (log_lvl) {
        console.log(`lq__journal_obj_li: person_id = ${$ae_loc.person_id}`);
        console.log(`lq__journal_obj_li: results = `, lq__journal_obj_li);
        if (
            $journals_slct.journal_obj_li &&
            JSON.stringify($journals_slct.journal_obj_li) !==
                JSON.stringify(lq__journal_obj_li)
        ) {
            console.log(
                `Session slct li stored version has changed for ID = ${$ae_loc.person_id}`,
                $journals_slct.journal_obj_li
            );
        } else {
            if (log_lvl > 1) {
                console.log(
                    `Session slct li stored version has not changed for ID = ${$ae_loc.person_id}`
                );
            }
        }
    }
});

// For some reason data.params.journal_entry_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
// NOTE: This must remain reactive (in an effect) so it updates on same-route navigation.
$effect(() => {
    if (!ae_acct) return;
    untrack(() => {
        $journals_slct.journal_entry_id = ae_acct.slct.journal_entry_id;
        // $journals_slct.journal_entry_obj = ae_acct.slct.journal_entry_obj;
    });
});

let lq__journal_entry_obj = $derived(
    liveQuery(async () => {
        let results = await db_journals.journal_entry.get(
            $journals_slct.journal_entry_id ?? ''
        ); // null or undefined does not reset things like '' does

        // Check if results are different than the current session version stored under $journals_slct
        if ($journals_slct.journal_entry_obj && results) {
            if (
                JSON.stringify($journals_slct.journal_entry_obj) !==
                JSON.stringify(results)
            ) {
                $journals_slct.journal_entry_obj = { ...results };
            }
        }

        return results;
    })
);

$effect(() => {
    if (log_lvl) {
        console.log(
            `lq__journal_entry_obj: journal_entry_id = ${$journals_slct?.journal_entry_id}`
        );
        console.log(`lq__journal_entry_obj: results = `, lq__journal_entry_obj);
        if ($journals_slct.journal_entry_obj && lq__journal_entry_obj) {
            if (
                JSON.stringify($journals_slct.journal_entry_obj) !==
                JSON.stringify(lq__journal_entry_obj)
            ) {
                console.log(
                    `Session slct stored version has changed for ID = ${$journals_slct.journal_entry_id}`,
                    $journals_slct.journal_entry_obj
                );
            } else {
                console.log(
                    `Session slct stored version has not changed for ID = ${$journals_slct.journal_entry_id}`
                );
            }
        }
    }
});

$effect(() => {
    if (browser && $lq__journal_entry_obj?.journal_entry_id) {
        // Start with the current KV or convert the LI to a KV if needed
        let history_kv = {
            ...($journals_loc?.entry_view_history_kv ?? {})
        };

        // Add or update the current entry
        const entry_id = $lq__journal_entry_obj?.journal_entry_id ?? 'NONE';
        history_kv[entry_id] = {
            id: entry_id,
            name:
                $lq__journal_entry_obj?.name ??
                ae_util.iso_datetime_formatter(
                    $lq__journal_entry_obj?.created_on,
                    'datetime_iso_12_no_seconds'
                ),
            url: `/journals/${$lq__journal_entry_obj?.journal_id ?? 'NONE'}/entry/${entry_id}`
        };

        console.log(`history_kv (before limiting) = `, history_kv);

        // // Convert KV to array, sort by most recent (last updated), and limit to 15
        // let history_li = Object.values(history_kv);

        // console.log(`history_li (before limiting) = `, history_li);

        // // If you want to keep the most recent 15, you can use the order of insertion.
        // // To do this, remove the oldest if over 15.
        // if (history_li.length > 15) {
        //     // Remove the oldest entries (by insertion order)
        //     // Get the keys in insertion order
        //     const keys = Object.keys(history_kv);
        //     const keys_to_remove = keys.slice(0, history_li.length - 15);
        //     for (const key of keys_to_remove) {
        //         delete history_kv[key];
        //     }
        // }

        // Only update if changed
        if (
            JSON.stringify(history_kv) !==
            JSON.stringify($journals_loc?.entry_view_history_kv)
        ) {
            $journals_loc.entry_view_history_kv = history_kv;
            console.log(
                `$journals_loc.entry_view_history_kv = `,
                $journals_loc.entry_view_history_kv
            );
        } else {
            if (log_lvl > 1) {
                console.log(
                    `$journals_loc.entry_view_history_kv has not changed.`
                );
            }
        }

        // log_lvl = 1;
    }
});

const title_entry = $derived(
    $lq__journal_entry_obj?.name
        ? $lq__journal_entry_obj.name.length > 50
            ? $lq__journal_entry_obj.name.slice(0, 50) + '…'
            : $lq__journal_entry_obj.name
        : 'Entry'
);
const title_journal = $derived(
    $lq__journal_obj?.name
        ? $lq__journal_obj.name.length > 30
            ? $lq__journal_obj.name.slice(0, 30) + '…'
            : $lq__journal_obj.name
        : 'Journal'
);
</script>

<svelte:head>
    <title>{title_entry} - {title_journal} - OSIT's AE Journals</title>
</svelte:head>

{#if $ae_loc.person_id == $lq__journal_obj?.person_id || $lq__journal_entry_obj?.public}
    <section
        class="
        ae_journals__journal_entry
        mx-auto
        flex w-full max-w-none min-w-0
        grow
        flex-col
        items-stretch
        gap-1
        space-y-2 px-2
        md:px-4
        ">
        <!-- {#if $lq__journal_entry_obj} -->
        <Journal_entry_view
            {lq__journal_obj}
            {lq__journal_obj_li}
            {lq__journal_entry_obj}
            on_show_export={() => (show_export_modal = true)} />
        <!-- {/if} -->
    </section>

    <AeCompModalJournalExport
        bind:open={show_export_modal}
        entries={$lq__journal_entry_obj ? [$lq__journal_entry_obj] : []}
        journal={$lq__journal_obj}
        on_close={() => (show_export_modal = false)} />
{:else}
    <section
        class="main_content flex grow flex-col items-center gap-1 px-1 pb-28 md:px-2">
        <p class="text-center">
            You must be logged in as the owner to view this Journal Entry.
        </p>
    </section>
{/if}
