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

interface Props {
    data: any;
}

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

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

// *** Import other supporting libraries
import { liveQuery } from 'dexie';

// *** 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 { db_journals } from '$lib/ae_journals/db_journals';
import {
    journals_loc,
    journals_sess,
    journals_slct,
    journals_prom,
    journals_trig
} from '$lib/ae_journals/ae_journals_stores';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';

import AeCompJournalObjIdView from './../ae_comp__journal_obj_id_view.svelte';
import Journal_entry_obj_li_wrapper from './../ae_comp__journal_entry_obj_li_wrapper.svelte';
import AeCompModalJournalExport from '../ae_comp__modal_journal_export.svelte';
import AeCompModalJournalImport from '../ae_comp__modal_journal_import.svelte';

// Variables
let ae_acct = $derived(data[data.account_id]);
let show_export_modal = $state(false);
let show_import_modal = $state(false);

let search_id_li: Array<string> = $state([]);
let search_debounce_timer: any = null;
let last_search_id = 0;
let last_executed_key = ''; // Search Guard Key

function handle_import_complete() {
    // Trigger a refresh of the journal entry list
    if ($journals_loc.entry.search_version === undefined)
        $journals_loc.entry.search_version = 0;
    $journals_loc.entry.search_version++;
}

$effect(() => {
    if (!ae_acct) return;
    untrack(() => {
        $journals_slct.journal_id = ae_acct.slct.journal_id;
        $journals_slct.journal_entry_id = null;
    });
});

let lq__journal_obj = $derived(
    liveQuery(async () => {
        return await db_journals.journal.get($journals_slct?.journal_id ?? '');
    })
);

// Stable LiveQuery Pattern (Aether UI V3)
// Re-wrapped in $derived to ensure the observable instance remains stable
// unless the underlying dependencies (ids, search context) change.
// Important: keep the `liveQuery` closure free of transient reactive
// references — capture stable values (ids, search keys) so the observable
// isn't recreated unnecessarily on every render. Use `search_id_li` or
// other plain arrays/values as explicit dependencies.
let lq__journal_entry_obj_li = $derived(
    liveQuery(async () => {
        const ids = search_id_li;
        const journal_id = $lq__journal_obj?.journal_id;
        const search_text = $journals_loc.entry.qry__search_text;
        const cat_code = $journals_loc.entry.qry__category_code;

        // SCENARIO 1: Specific IDs provided (Search Results)
        if (Array.isArray(ids) && ids.length > 0) {
            if (log_lvl)
                console.log(`Journal Page LQ: bulkGet ${ids.length} IDs`);
            const results = await db_journals.journal_entry.bulkGet(ids);
            return results.filter((item) => item !== undefined);
        }

        // SCENARIO 2: Fallback to broad search (Default view)
        if (journal_id && !search_text && !cat_code) {
            if (log_lvl)
                console.log(
                    `Journal Page LQ: Fallback search for journal: ${journal_id}`
                );
            return await db_journals.journal_entry
                .where('journal_id')
                .equals(journal_id)
                .reverse()
                .sortBy('tmp_sort_1');
        }

        return [];
    })
);

// Standardized Reactive Search Pattern (Aether UI V3)
// 1. Isolate dependencies into a stable derived object
let search_params = $derived({
    v: $journals_loc.entry.search_version,
    str: ($journals_loc.entry.qry__search_text ?? '').toLowerCase().trim(),
    cat: $journals_loc.entry.qry__category_code,
    limit: $journals_loc.entry.qry__limit,
    enabled: $journals_loc.entry.qry__enabled,
    hidden: $journals_loc.entry.qry__hidden,
    journal_id: $journals_slct.journal_id,
    person_id: $ae_loc.person_id,
    remote_first: $journals_loc.entry.qry__remote_first
});

// 2. Controlled effect for triggering searches
$effect(() => {
    // Establishes reactive dependency on search_params
    const params = search_params;

    if (search_debounce_timer) clearTimeout(search_debounce_timer);
    search_debounce_timer = setTimeout(() => {
        // Execution MUST be untracked to prevent circular triggers
        untrack(() => {
            handle_search_refresh(params);
        });
    }, 250);

    return () => {
        if (search_debounce_timer) clearTimeout(search_debounce_timer);
    };
});

async function handle_search_refresh(params: any) {
    // 1. Guard: Check if criteria actually changed
    const qry_key = JSON.stringify(params);
    if (qry_key === last_executed_key) return;
    last_executed_key = qry_key;

    const current_search_id = ++last_search_id;
    const journal_id = params.journal_id;
    const remote_first = params.remote_first;

    if (log_lvl)
        console.log(
            `[Journal Search #${current_search_id}] Refreshing entries (remote=${remote_first}, journal=${journal_id})...`
        );

    // 2. Setup State
    untrack(() => {
        $journals_sess.entry.qry__status = 'loading';
    });

    const qry_str = params.str;
    const cat_code = params.cat;

    let local_ids: string[] = [];

    // 3. FAST PATH: Local IDB Search (SWR)
    // We skip this ONLY if remote_first is checked AND we have search text
    if (!remote_first) {
        try {
            if (journal_id) {
                let local_results = await db_journals.journal_entry
                    .where('journal_id')
                    .equals(journal_id)
                    .filter((entry) => {
                        if (cat_code && entry.category_code !== cat_code)
                            return false;
                        if (qry_str) {
                            const name = (entry.name ?? '').toLowerCase();
                            const content = (entry.content ?? '').toLowerCase();
                            return (
                                name.includes(qry_str) ||
                                content.includes(qry_str)
                            );
                        }
                        return true;
                    })
                    .toArray();

                local_results.sort((a, b) => {
                    const dateA = a.updated_on
                        ? new Date(a.updated_on).getTime()
                        : 0;
                    const dateB = b.updated_on
                        ? new Date(b.updated_on).getTime()
                        : 0;
                    return dateB - dateA;
                });

                local_ids = local_results
                    .map((e) => e.id || e.journal_entry_id)
                    .filter(Boolean);

                if (current_search_id === last_search_id) {
                    if (log_lvl)
                        console.log(
                            `[Journal Search #${current_search_id}] Fast Path found ${local_ids.length} items locally.`
                        );
                    untrack(() => {
                        search_id_li = local_ids;
                        if (local_ids.length > 0)
                            $journals_sess.entry.qry__status = 'done';
                    });
                }
            }
        } catch (e) {
            if (log_lvl) console.warn('Journal Fast Path failed.', e);
        }
    }

    // 4. REVALIDATE: API Request
    try {
        const results = await journals_func.qry__journal_entry({
            api_cfg: $ae_api,
            journal_id: journal_id,
            person_id: null,
            qry_str: qry_str || null,
            qry_category_code: cat_code || null,
            enabled: params.enabled,
            hidden: params.hidden,
            limit: params.limit,
            log_lvl: 0
        });

        if (current_search_id === last_search_id) {
            const api_results = results || [];
            const api_ids = api_results
                .map((e: any) => e.id || e.journal_entry_id)
                .filter(Boolean);

            // Protect UI cache if API returns empty during revalidation
            if (
                api_ids.length === 0 &&
                local_ids.length > 0 &&
                !remote_first &&
                !qry_str
            ) {
                untrack(() => {
                    $journals_sess.entry.qry__status = 'done';
                });
                return;
            }

            untrack(() => {
                $journals_sess.entry_li = api_results;
                search_id_li = api_ids;
                $journals_sess.entry.qry__status = 'done';
            });
            if (log_lvl)
                console.log(
                    `[Journal Search #${current_search_id}] Revalidation Complete. Found ${api_ids.length} items.`
                );
        }
    } catch (error) {
        if (current_search_id === last_search_id) {
            console.error('Journal revalidation failed:', error);
            untrack(() => {
                $journals_sess.entry.qry__status = 'error';
                if (search_id_li.length === 0 && local_ids.length > 0) {
                    search_id_li = local_ids;
                }
            });
        }
    }
}

if (browser) {
    window.parent.postMessage(
        { journal_id: $journals_slct?.journal_id ?? null },
        '*'
    );
}

import { LoaderCircle } from '@lucide/svelte';
</script>

<svelte:head>
    <title>
        Æ Journals: {$lq__journal_obj?.name ?? ''} - {$ae_loc?.title}
    </title>
</svelte:head>

{#if $lq__journal_obj === undefined}
    <div
        class="flex flex-col items-center justify-center p-20 text-center opacity-50">
        <LoaderCircle size="3em" class="mx-auto mb-4 animate-spin" />
        <p class="text-xl">Loading Journal...</p>
    </div>
{:else if $ae_loc.person_id == $lq__journal_obj?.person_id}
    <AeCompJournalObjIdView
        {lq__journal_obj}
        {lq__journal_entry_obj_li}
        on_show_export={() => (show_export_modal = true)}
        on_show_import={() => (show_import_modal = true)} />

    <Journal_entry_obj_li_wrapper
        {lq__journal_obj}
        {lq__journal_entry_obj_li}
        show_found_header={false}
        {log_lvl} />

    <AeCompModalJournalExport
        bind:open={show_export_modal}
        entries={$lq__journal_entry_obj_li ?? []}
        journal={$lq__journal_obj}
        on_close={() => (show_export_modal = false)} />

    <AeCompModalJournalImport
        bind:open={show_import_modal}
        on_close={() => (show_import_modal = false)}
        on_import_complete={handle_import_complete} />
{: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.
        </p>
    </section>
{/if}
