<script lang="ts">
    interface Props {
        log_lvl?: number;
        lq__journal_obj: any;
    }

    let { log_lvl = $bindable(0), lq__journal_obj }: Props = $props();

    import {
        ArrowDown01,
        ArrowDown10,
        ArrowDownUp,
        BetweenVerticalEnd,
        BetweenVerticalStart,
        BookHeart,
        BookImage,
        Bookmark,
        BookOpenText,
        BriefcaseBusiness,
        Check,
        Copy,
        Expand,
        Eye,
        EyeOff,
        Flag,
        FlagOff,
        FilePlus,
        Fingerprint,
        Globe,
        Library,
        MessageSquareWarning,
        Minus,
        Notebook,
        Pencil,
        Plus,
        RemoveFormatting,
        SquareLibrary,
        Shapes,
        Share2,
        ShieldCheck,
        ShieldMinus,
        Siren,
        Skull,
        Tags,
        Target,
        ToggleLeft,
        ToggleRight,
        Trash2,
        TypeOutline,
        X
    } from '@lucide/svelte';

    import {
        ae_snip,
        ae_loc,
        ae_sess,
        ae_api,
        ae_trig,
        slct,
        slct_trigger
    } from '$lib/stores/ae_stores';
    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';

    // Debounced Search Logic (Refactored 2026-01-27)
    let search_debounce_timer: any = null;
    let last_search_id = 0;

    $effect(() => {
        // Reactive dependencies
        const s_search_text = $journals_loc.entry.qry__search_text;
        const s_category_code = $journals_loc.entry.qry__category_code;
        const s_enabled = $journals_loc.entry.qry__enabled;
        const s_hidden = $journals_loc.entry.qry__hidden;
        const s_journal_id = $lq__journal_obj?.journal_id;
        const s_trigger = $journals_trig.journal_entry_qry;

        if (search_debounce_timer) clearTimeout(search_debounce_timer);

        // Auto-search if text is cleared or long enough, or if category changes
        const should_search = s_trigger || 
                            s_search_text.length === 0 || 
                            s_search_text.length >= 3 || 
                            s_category_code !== '';

        if (should_search && s_journal_id) {
            search_debounce_timer = setTimeout(() => {
                $journals_trig.journal_entry_qry = false;
                handle_search_refresh();
            }, 400);
        }

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

    async function handle_search_refresh() {
        const current_search_id = ++last_search_id;
        const qry_str = $journals_loc.entry.qry__search_text;
        const category_code = $journals_loc.entry.qry__category_code;

        if (log_lvl) console.log(`[Journal Search #${current_search_id}] text="${qry_str}" cat="${category_code}"`);

        try {
            const results = await journals_func.qry__journal_entry({
                api_cfg: $ae_api,
                journal_id: $lq__journal_obj?.journal_id ?? '',
                qry_str: qry_str,
                qry_category_code: category_code,
                enabled: $journals_loc.entry.qry__enabled ?? 'enabled',
                hidden: $journals_loc.entry.qry__hidden ?? 'not_hidden',
                log_lvl: 0
            });

            if (current_search_id === last_search_id) {
                $journals_prom.load__journal_entry_obj_li = results;

                if (!qry_str && !category_code) {
                    // Reset to default view if everything cleared
                    $journals_sess.entry_li = null;
                } else {
                    $journals_sess.entry_li = results || [];
                    $journals_sess = { ...$journals_sess };
                }
                
                if (log_lvl) console.log(`[Journal Search #${current_search_id}] Done. Found ${results?.length ?? 0} results.`);
            }
        } catch (error) {
            if (current_search_id === last_search_id) {
                console.error('Journal search failed:', error);
            }
        }
    }
</script>

<!-- Search input form -->
<span class="flex flex-row flex-wrap items-center justify-center gap-1">
    <span class="text-sm text-gray-500 hidden lg:inline"> Search: </span>
    <input
        disabled={false}
        type="text"
        placeholder="Search Journal Entries"
        bind:value={$journals_loc.entry.qry__search_text}
        onkeyup={(event) => {
            if (event.key === 'Enter') {
                $journals_trig.journal_entry_qry = true;
            }
        }}
        title={`Search for Entries in "${$lq__journal_obj?.name}. Press Enter to search.`}
        autocomplete="off"
        class="
            input input-sm input-bordered
            w-44 md:w-52
            text-sm
            "
        class:bg-red-200={$journals_sess.entry_li == null}
        class:dark:bg-red-800={$journals_sess.entry_li == null}
    />
    <!-- Clear search text button -->
    <button
        type="button"
        class:hidden={!$journals_loc.entry.qry__search_text && !$journals_loc.entry.qry__category_code}
        onclick={() => {
            console.log(`TESTING - 1 - Cleared search query: ${$journals_loc.entry.qry__search_text}`);
            $journals_loc.entry.qry__search_text = '';
            $journals_loc.entry.qry__category_code = '';
            console.log(`TESTING - 2 - Cleared search query: ${$journals_loc.entry.qry__search_text}`);
            $journals_trig.journal_entry_qry = true;
        }}
        class="
            btn btn-sm
            preset-tonal-tertiary
            preset-outlined-tertiary-100-900
            hover:preset-filled-tertiary-100-900
            transition-all
            "
        title="Clear search query text"
    >
        <RemoveFormatting size="1.25em" class="text-neutral-800/60 dark:text-neutral-50/60" />
        <span class="hidden md:inline"> Clear </span>

        {#await $journals_prom.load__journal_entry_obj_li}
            <span class="text-sm text-gray-500 italic"> Loading... </span>
        {:then load_result}
            {#if load_result === null}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold">
                    No entries found - null
                </span>
            {:else if load_result?.length === 0}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold">
                    No entries found
                </span>
            {:else if $journals_sess.entry_li?.length === 0}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
                    Enter to search
                </span>
            {:else}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
                    {load_result?.length ?? 0} found
                </span>
            {/if}
        {:catch error}
            <span class="text-xs text-red-600/80 dark:text-red-400/80 italic">
                Error loading entries.
            </span>
        {/await}
    </button>
</span>

<!-- Give list of categories to base the new entry on -->
<span class="flex flex-row items-center gap-2">
    <span class="text-sm text-gray-500 hidden md:inline"> Category: </span>
    <select
        class="
            btn btn-sm
            preset-tonal-tertiary
            preset-outlined-tertiary-100-900
            hover:preset-filled-tertiary-100-900
            transition-all
            "
        bind:value={$journals_loc.entry.qry__category_code}
        onchange={(event) => {
            $journals_loc.entry.qry__category_code = (event.target as HTMLInputElement).value;
            $journals_trig.journal_entry_qry = true;
            console.log('Selected category:', $journals_loc.entry.qry__category_code);
        }}
        title="Select a category for the new journal entry"
    >
        <option value="">Select Category</option>
        {#each $lq__journal_obj?.cfg_json?.category_li as category}
            <option value={category.code}>{category.name}</option>
        {/each}
    </select>
</span>
