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

let { data, children } = $props();

// *** Import Svelte specific
import { goto } from '$app/navigation';

// *** Import other supporting libraries
import { FilePlus, Notebook, SquareLibrary, X } from '@lucide/svelte';

import { liveQuery } from 'dexie';

import { db_journals } from '$lib/ae_journals/db_journals';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import {
    journals_loc,
    journals_slct
} from '$lib/ae_journals/ae_journals_stores';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';

import Journal_entry_obj_qry from './../ae_comp__journal_entry_obj_qry.svelte';

// NOTE: Derived from data.account_id (prop) instead of $slct.account_id (store)
// to prevent circular dependency loops during hydration.
let ae_acct = $derived(data[data.account_id]);
$effect(() => {
    if (log_lvl) {
        console.log(`ae_acct = `, ae_acct);
    }
});

let show_menu__all_journals: boolean = $state(false);

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

<!-- Svelte layout for a Journal ID page and children -->
<section
    class="
        ae_journals__journal
        mx-auto
        flex min-h-0 w-full max-w-none
        min-w-0
        flex-col
        items-stretch
        gap-1
        space-y-2
        ">
    <div
        class="
        relative flex w-full
        flex-row
        flex-wrap items-center
        justify-between
        gap-1
        border-b
        border-gray-400
        py-2 transition-all

        hover:bg-slate-100 hover:dark:bg-slate-700
        ">
        <!-- If middle click then open the all journals page in a new tab. Otherwise show/hide the menu. -->
        <button
            type="button"
            onmousedown={(event) => {
                if (event.button === 1) {
                    // Middle click - open in new tab
                    // window.open('/journals', '_blank');
                    window.open('/journals');
                    // } else {
                    //     // Left click - toggle menu
                    //     event.preventDefault(); // Prevent default middle-click behavior
                    //     show_menu__all_journals = !show_menu__all_journals;
                }
            }}
            onclick={() => {
                show_menu__all_journals = !show_menu__all_journals;
            }}
            class="
            btn btn-sm
            preset-tonal-tertiary
            preset-outlined-tertiary-600-400
            hover:preset-outlined-tertiary-700-300
            hover:preset-filled-tertiary-300-700
            transition-all
            "
            title={`View all journals menu: "${$ae_loc?.user?.name}"
Middle-click to open in new tab`}>
            <!-- <BookHeart /> -->
            <!-- <Library /> -->
            {#if show_menu__all_journals}
                <X class="text-orange-500" />
            {:else}
                <SquareLibrary class="text-gray-500" />
            {/if}
            <span class="hidden md:inline">
                Journals
                <!-- for {$ae_loc?.user?.name} -->
            </span>
        </button>

        <div
            class="
            absolute top-12 left-0
            z-50 w-80 max-w-fit
            min-w-72
            space-y-0.5 rounded-lg
            border border-gray-500
            bg-white p-4
            shadow-xl
            dark:bg-gray-800
            "
            class:hidden={!show_menu__all_journals}>
            <a
                href="/journals"
                class="
                btn btn-sm
                preset-tonal-tertiary
                preset-outlined-tertiary-600-400
                hover:preset-outlined-tertiary-700-300
                hover:preset-filled-tertiary-300-700
                transition-all
                "
                title="View all journals for this account: {$ae_loc.account_name}">
                <!-- <BookHeart /> -->
                <!-- <Library /> -->
                <SquareLibrary class="text-blue-500" />
                <span class=""> All Journals </span>
            </a>

            <!-- $journals_slct?.journal_id &&  -->
            <!-- List of recent entries here... -->
            <!-- $journals_loc.entry_view_history_li -->
            {#if $journals_loc.entry_view_history_kv && Object.keys($journals_loc.entry_view_history_kv).length > 0}
                <select
                    bind:value={$journals_slct.journal_entry_id}
                    onchange={() => {
                        if ($journals_slct.journal_entry_id) {
                            goto(
                                `/journals/${$journals_slct?.journal_id}/entry/${$journals_slct.journal_entry_id}`
                            );
                        }
                    }}
                    class="
                    form-select
                    border-neutral-400-600
                    w-full
                    border p-1
                    text-sm
                    ">
                    <option value="" disabled selected>
                        {Object.keys($journals_loc.entry_view_history_kv)
                            .length}&times; Recent Entries...
                    </option>
                    <!-- loop through each key value -->
                    {#each Object.entries($journals_loc.entry_view_history_kv as Record<string, { id: string; name: string; url: string }>).reverse() as [journal_entry_id, journal_entry_obj] (journal_entry_id)}
                        <option value={journal_entry_obj.id}>
                            {(journal_entry_obj?.name ||
                                journal_entry_obj?.id) ??
                                'NONE'}
                        </option>
                    {/each}
                </select>
            {/if}
        </div>

        {#if $journals_slct?.journal_entry_id}
            <a
                href="/journals/{$journals_slct?.journal_id}"
                class="
            btn btn-sm
            preset-tonal-tertiary
            preset-outlined-tertiary-600-400
            hover:preset-outlined-tertiary-700-300
            hover:preset-filled-tertiary-300-700
            transition-all
            "
                title="View all journal entries for this journal: {$lq__journal_obj?.name}">
                <Notebook />
                <!-- <Bookmark /> -->
                <!-- <BookHeart class="m-1" /> -->
                <!-- <BookImage class="m-1" /> -->
                <!-- <BookOpenText class="m-1" /> -->
                <span class="hidden lg:inline">Back:</span>
                <span class="font-bold">
                    {$lq__journal_obj?.name || 'Journal'}
                </span>
            </a>
        {:else}
            <!-- Edit Journal button. Creates a modal to edit the journal. -->
            <Journal_entry_obj_qry
                {log_lvl}
                lq__journal_obj={$lq__journal_obj} />
        {/if}

        <!-- Add default journal entry -->
        <span class="flex flex-row flex-wrap items-center justify-center gap-2">
            <!-- <span class="text-sm text-gray-500 hidden md:inline">
            New entry:
        </span> -->
            <button
                type="button"
                onclick={() => {
                    // $journals_sess.show__modal_new__journal_entry_obj = true;

                    let data_kv = {
                        category_code: null
                    };
                    if ($journals_loc.entry.qry__category_code) {
                        data_kv.category_code =
                            $journals_loc.entry.qry__category_code;
                    }
                    if (log_lvl) {
                        console.log(
                            'Creating new journal entry with data_kv:',
                            data_kv
                        );
                    }
                    journals_func
                        .create_ae_obj__journal_entry({
                            api_cfg: $ae_api,
                            journal_id: $lq__journal_obj?.journal_id ?? '',
                            data_kv: data_kv,
                            log_lvl: log_lvl
                        })
                        .then((results) => {
                            if (log_lvl) {
                                console.log(
                                    'New journal entry created:',
                                    results
                                );
                            }
                            $journals_slct.journal_entry_id =
                                results?.journal_entry_id;
                            // $journals_loc.entry.edit = true;
                            $journals_loc.entry.edit_kv[
                                $journals_slct.journal_entry_id
                            ] = 'current';
                            // alert(`Journal entry created successfully! ${$journals_slct.journal_entry_id}`);
                        })
                        .catch((error) => {
                            console.error(
                                'Error updating journal entry:',
                                error
                            );
                            alert('Failed to update journal entry.');
                        })
                        .finally(() => {
                            if ($journals_slct.journal_entry_id) {
                                goto(
                                    `/journals/${$lq__journal_obj?.journal_id}/entry/${$journals_slct.journal_entry_id}`
                                );
                            } else {
                                alert('Failed to create new journal entry.');
                            }
                        });
                }}
                class="
                btn btn-sm
                preset-tonal-tertiary
                preset-outlined-tertiary-600-400
                hover:preset-outlined-tertiary-700-300
                hover:preset-filled-tertiary-300-700
                transition-all
                "
                title="Create a new journal entry for this journal: {$lq__journal_obj?.name}">
                <FilePlus />
                <!-- <span class="fas fa-plus m-1"></span> -->
                <span class="hidden sm:inline"> New Entry </span>
            </button>
        </span>
    </div>

    <div class="w-full min-w-0">
        {@render children?.()}
    </div>
</section>
