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

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

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_loc, ae_api } from '$lib/stores/ae_stores';
import { db_journals } from '$lib/ae_journals/db_journals';
import { journal_entry_filter_list } from '$lib/ae_journals/ae_journals_search_helpers';
import {
    journals_loc,
    journals_sess,
    journals_slct
} 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
interface JournalPageAccount {
    api?: unknown;
    loc?: {
        person_id?: string | null;
    };
    slct: {
        journal_id: string | null;
        journal_entry_id?: string | null;
    };
}

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

interface JournalSearchParams {
    v: number;
    str: string;
    cat: string;
    limit: number;
    enabled: 'enabled' | 'all' | 'not_enabled';
    hidden: 'hidden' | 'all' | 'not_hidden';
    journal_id: string | null;
    remote_first: boolean;
}

let search_id_li: Array<string> = $state([]);
let search_debounce_timer: ReturnType<typeof setTimeout> | null = 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 ?? '');
    })
);

// 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,
    remote_first: $journals_loc.entry.qry__remote_first
});

// 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(
    (() => {
        const ids = search_id_li;
        const params = search_params;
        const journal_id = $lq__journal_obj?.journal_id;

        return liveQuery(async () => {
            if (
                params.remote_first &&
                (!Array.isArray(ids) || ids.length === 0)
            ) {
                return null;
            }

            // 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);
            }

            if (!journal_id) return null;

            // SCENARIO 2: Fallback to broad journal search (Default view)
            if (log_lvl)
                console.log(
                    `Journal Page LQ: Broad search for journal: ${journal_id}`
                );

            const results = await db_journals.journal_entry
                .where('journal_id')
                .equals(journal_id)
                .toArray();

            return journal_entry_filter_list(results, params) ?? [];
        });
    })()
);

// 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: JournalSearchParams) {
    // 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';
    });

    if (remote_first) {
        untrack(() => {
            search_id_li = [];
        });
    }

    const qry_str = params.str;
    const cat_code = params.cat;
    const order_by_li = {
        group: 'DESC',
        priority: 'DESC',
        sort: 'DESC',
        updated_on: 'DESC',
        created_on: 'DESC'
    };

    let local_ids: string[] = [];

    // 3. FAST PATH: Local IDB Search (SWR)
    // Broad views still need the local IDB set so "All" remains complete.
    // Remote-first is only used to skip the local fast path for text searches.
    if (!remote_first || !qry_str) {
        try {
            if (journal_id) {
                const local_results = await db_journals.journal_entry
                    .where('journal_id')
                    .equals(journal_id)
                    .toArray();

                const filtered_results =
                    journal_entry_filter_list(local_results, params) ?? [];

                local_ids = filtered_results
                    .map((entry) => entry.id || entry.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,
            order_by_li,
            log_lvl: 0
        });

        if (current_search_id === last_search_id) {
            const api_results = (results || []) as Array<{
                id?: string;
                journal_entry_id?: string | null;
            }>;
            const api_ids = api_results
                .map((entry) => entry.id || entry.journal_entry_id)
                .filter((entry): entry is string => Boolean(entry));
            const display_ids =
                !qry_str && local_ids.length > 0 ? local_ids : api_ids;

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

            untrack(() => {
                $journals_sess.entry_li = api_results;
                search_id_li = display_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';

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

<svelte:head>
    <title>{title_journal} - OSIT's AE Journals</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}
