<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 {
    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 { liveQuery } from "dexie";
// import { Modal } from 'flowbite-svelte';

// import { ae_util } from '$lib/ae_utils/ae_utils';
import { db_journals } from "$lib/ae_journals/db_journals";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/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';

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

// interface Props {
//     data: any;
// }

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

// let tmp_journal_obj_changed: boolean = $state(false);
// let tmp_journal_obj: key_val = $state({});


let ae_acct = data[$slct.account_id];
if (log_lvl) {
    console.log(`ae_acct = `, ae_acct);
}

// $journals_sess.entry_li = [];
// $journals_slct.journal_id = ae_acct.slct.journal_id;

let show_menu__all_journals: boolean = $state(false);

let lq__journal_obj = $derived(liveQuery(async () => {
    if (log_lvl) {
        console.log(`lq__journal_obj: journal_id = ${$journals_slct?.journal_id}`);
    }

    let results = await db_journals.journal
        .get($journals_slct?.journal_id ?? ''); // null or undefined does not reset things like '' does
    if (log_lvl) {
        console.log(`lq__journal_obj: results = `, results);
    }
    // tmp_journal_obj = { ...results };

    // 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 };
            if (log_lvl) {
                console.log(`Session slct stored version has changed for ID = ${$journals_slct.journal_id}`, $journals_slct.journal_obj);
            }
        } else {
            if (log_lvl) {
                console.log(`Session slct stored version has not changed for ID = ${$journals_slct.journal_id}`);
            }
        }
    }

    return results;
}));

// $effect(() => {
//     if ($lq__journal_obj) {
//         tmp_journal_obj = { ...$lq__journal_obj };
//         console.log('tmp_journal_obj:', tmp_journal_obj);
//     }
// });

// $effect(() => {
//     if (tmp_journal_obj) {
//         tmp_journal_obj_changed = JSON.stringify(tmp_journal_obj) != JSON.stringify($lq__journal_obj);
//     }
// });

// async function handle_update_journal() {
//     if (tmp_journal_obj.name && tmp_journal_obj.type_code) {
//         try {
//             let data_kv = {
//                 // account: $slct.account_id,
//                 name: tmp_journal_obj.name,
//                 description: tmp_journal_obj.description ?? '', // Ensure description is at least an empty string
//                 type_code: tmp_journal_obj.type_code,
//                 passcode: tmp_journal_obj.passcode,
//                 private_passcode: tmp_journal_obj.private_passcode,
//                 passcode_timeout: tmp_journal_obj.passcode_timeout,
//                 auth_key: tmp_journal_obj.auth_key, // The Journal Entry encryption password

//                 cfg_json: tmp_journal_obj.cfg_json

//             };
//             journals_func.update_ae_obj__journal({
//                 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('Journal updated:', results);
//                 }
//                 // $journals_slct.journal_id = results?.journal_id_random;
//             }).catch((error) => {
//                     console.error('Error updating journal:', error);
//                     alert('Failed to update journal.');
//             }).finally(() => {
//                 if ($journals_slct.journal_id) {
//                     $journals_sess.show__modal_new__journal_obj = false;
//                     // goto(`/journals/${$journals_slct.journal_id}`);
//                 }
//             });
//             // console.log('New journal updated:', result);
//             // $journals_sess.show__modal_new__journal_obj = false;
//             // goto(`/journals/${result.journal_id_random}`);
//         } catch (error) {
//             console.error('Error updating journal:', error);
//             alert('Failed to update journal.');
//         }
//     } else {
//         alert('Please provide both name and type for the journal.');
//     }
// }

</script>


<!-- Svelte layout for a Journal ID page and children -->
<section
    class="
        ae_journals__journal
        mx-auto
        flex flex-col grow gap-1
        items-center
        min-h-full
        max-h-max
        min-w-full
        max-w-max
        space-y-2
        "
    >



<div
    class="
        flex flex-row flex-wrap
        gap-1
        items-center justify-between
        border-gray-400
        border-b
        py-2
        w-full
        hover:bg-slate-100 hover:dark:bg-slate-700

        relative transition-all
        "
    >

    <button
        type="button"
        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.account_name}"
        >
        <!-- <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
        </span>

    </button>


    <div
        class="
            absolute top-12 left-0
            p-4 z-50 w-80
            space-y-0.5
            bg-white dark:bg-gray-800
            border border-gray-500
            shadow-xl rounded-lg
            min-w-72
            max-w-fit
            "
        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>

        <!-- List of recent entries here... -->
        <!-- $journals_loc.entry_view_history_li -->
        {#if $journals_loc?.entry_view_history_li?.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
                    w-full
                    text-sm
                    border border-neutral-400-600
                    p-1
                    "
                >
                <option value="" disabled selected>
                    Recent Entries...
                </option>
                {#each $journals_loc.entry_view_history_li as entry (entry.id)}
                    <option value={entry.id}>
                        {entry.name}
                    </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. -->
    <!-- <button
        type="button"
        onclick={() => {
            tmp_journal_obj = {
                name: $lq__journal_obj?.name,
                description: $lq__journal_obj?.description,
                type_code: $lq__journal_obj?.type_code,
                passcode: $lq__journal_obj?.passcode,
                passcode_timeout: $lq__journal_obj?.passcode_timeout,
                auth_key: $lq__journal_obj?.auth_key,
                cfg_json: $lq__journal_obj?.cfg_json
            };
            $journals_sess.show__modal_edit__journal_obj = true;
        }}
        class:hidden={!$ae_loc.edit_mode}
        class="
            btn btn-sm
            variant-ghost-warning
            hover:variant-filled-warning
            transition
            "
        title="Edit Journal meta and configuration (name, type, passcode, categories, etc.: {$lq__journal_obj?.name})"
        >
        <Pencil />
        <span class="hidden md:inline">
            Edit Journal
        </span>
    </button> -->
    <Journal_entry_obj_qry
            log_lvl={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.qry__category_code) {
                    data_kv.category_code = $journals_loc.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_random;
                    // $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="overflow-auto"> -->
{@render children()}
<!-- </div> -->


</section>


<!-- {#if $journals_sess.show__modal_edit__journal_obj}
<Journal_obj_id_edit
    log_lvl={log_lvl}
    lq__journal_obj={lq__journal_obj}
    show={$journals_sess.show__modal_edit__journal_obj}
    />
{/if} -->

