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

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

// *** Import other supporting libraries
// import * as icons from '@lucide/svelte';
import {
        Brain,
        House, Library,
        RefreshCw,
        Satellite
    } from '@lucide/svelte';

// *** Import Aether specific variables and functions
import type { key_val } from '$lib/ae_stores';
// import { ae_util } from '$lib/ae_utils/ae_utils';
// import { api } from '$lib/api';
import { ae_loc, ae_sess, ae_api, slct } from '$lib/ae_stores';
import { journals_loc, journals_slct, journals_trig } from '$lib/ae_journals/ae_journals_stores';
// import { journals_func } from '$lib/ae_journals/ae_journals_functions';
import Element_data_store from '$lib/element_data_store_v2.svelte';
import Help_tech from '$lib/e_app_help_tech.svelte';

// *** Setup Svelte properties
interface Props {
    data: any;
    children: any;
}
let { data, children }: Props = $props();

$journals_loc.qry__enabled = 'enabled';
$journals_loc.qry__hidden = 'not_hidden';
$journals_loc.qry__limit = 15;
$journals_loc.qry__offset = 0;

// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
$slct.account_id = data.account_id;
if (log_lvl) {
    console.log(`$slct.account_id = `, $slct.account_id);
}
let ae_acct = data[$slct.account_id];
// console.log(`ae_acct = `, ae_acct);

// if (browser) {
//     console.log(`Browser: ${browser}`);
//     journals_func.handle_db_save_ae_obj_li__journal({
//         obj_type: 'journal',
//         obj_li: [ae_acct.slct.journal_obj_li],
//     });
// }

$journals_slct.journal_id = ae_acct.slct.journal_id;
// $journals_slct.journal_obj = ae_acct.slct.journal_obj;
$journals_slct.journal_obj_li = ae_acct.slct.journal_obj_li;

// let ae_promises: key_val = {};


let nav_y_height = $state(0);

let box: any;
let xLeft = $state(0);
let xScroll = $state(0);
let xWidth = $state(0);
let yTop = $state(0);
let yScroll = $state(0);
let yHeight = $state(0);

let scroll_y = $state(0);

function parse_scroll() {
    // console.log(`parse_scroll() called`);
    xLeft = box.scrollLeft;
    xScroll = box.scrollWidth;
    xWidth = box.clientWidth;
    yTop = box.scrollTop;
    yHeight = box.clientHeight;
    yScroll = box.scrollHeight;
    // console.log(`parse_scroll() called: ${yTop}`);
}

function scroll_container() {
    return document.getElementById('ae_main_content') || document.documentElement || document.body;
}

</script>


<svelte:head>
	<title>Journals - {$journals_loc.title ?? 'Æ loading...'}</title>
</svelte:head>


{#if $ae_loc.user_id && $ae_loc.person_id && $ae_loc.trusted_access}
<!-- These are needed: h-full overflow-auto -->
<div
    id="ae_main_content"
    bind:clientHeight={$ae_loc.iframe_height}
    bind:this={box}
    onscroll={parse_scroll}
    class:iframe={$ae_loc?.iframe}
    class="
        ae_journals
        h-full max-h-full max-w-7xl
        overflow-auto
        flex flex-col gap-1
        m-auto

        bg-gray-50 dark:bg-gray-900
        text-gray-800 dark:text-gray-200
        "
    >

<!-- class:hidden={yTop > 200} -->
<nav
    bind:clientHeight={nav_y_height}
    class:opacity-0={yTop > 250}
    class="
        submenu
        z-20
        hover:opacity-100
        absolute top-0 left-0 right-0
        w-full max-w-7xl
        min-h-12
        p-1 px-2 pb-2 m-auto

        flex flex-col sm:flex-row sm:flex-wrap
        items-center justify-between
        gap-1

        border-b-2 rounded-b-lg

        bg-gray-200 dark:bg-gray-800

        transition-all duration-1000
        "
    >
    <span class="justify-self-start">

        <!-- Be sure to explain what &AElig; (Aether) means in the title text or similar! -->
        <Satellite
            size="1.5em"
            class="mx-1 inline-block text-gray-500"
            />
        <abbr title="Aether - Journals Module">
            Æ
            Journals
        </abbr>
    </span>
    <a
        href="/"
        class="btn btn-sm preset-tonal-surface border border-surface-500 hover:preset-filled-success-500"
        >
        <House />
        <span class="hidden md:inline">
            Home
        </span>
    </a>
    <!-- <a href="/about" class="btn btn-sm">About</a> -->
    <!-- <a href="/settings" class="btn btn-sm">Settings</a> -->
    <button

        onclick={() => {
            if ($ae_loc.edit_mode) {
                // Confirm before clearing
                if (!confirm("Are you sure you want to clear IndexedDB databases, localStorage, and sessionStorage? This will also reload the page.")) {
                    return;
                }

                console.log("Clearing IndexedDB, localStorage, sessionStorage, and reloading the page...");

                // Clear Indexed DB
                indexedDB.deleteDatabase('ae_archives_db'); // Archives module
                indexedDB.deleteDatabase('ae_core_db');
                indexedDB.deleteDatabase('ae_events_db'); // Events module
                indexedDB.deleteDatabase('ae_journals_db'); // Journals module
                indexedDB.deleteDatabase('ae_posts_db'); // Posts module
                indexedDB.deleteDatabase('ae_sponsorships_db'); // Sponsorships module

                // Clear localStorage and sessionStorage
                // Clearing the localStorage will force it to be re-created.
                localStorage.clear();
                sessionStorage.clear();

                goto('/', {invalidateAll: true});

                // window.location.reload(true);
            } else {
                // Confirm before clearing
                if (!confirm("Are you sure you want to clear IndexedDB databases and some caches? This will also reload the page.")) {
                    return;
                }

                console.log("Clearing IndexedDB, localStorage, sessionStorage, and reloading the page...");

                // Clear Indexed DB
                indexedDB.deleteDatabase('ae_archives_db'); // Archives module
                indexedDB.deleteDatabase('ae_core_db');
                indexedDB.deleteDatabase('ae_events_db'); // Events module
                indexedDB.deleteDatabase('ae_journals_db'); // Journals module
                indexedDB.deleteDatabase('ae_posts_db'); // Posts module
                indexedDB.deleteDatabase('ae_sponsorships_db'); // Sponsorships module

                window.location.reload(true);
            }

            // This does not seem to work fast enough or something?
            // goto('/', {invalidateAll: true});

            // The page does usually seem to reload correctly?
            // window.location.reload(true); // true only works with Firefox
            // alert('Local and Session Storage cleared and Indexed DBs deleted. You will probably want to refresh the page.');
        }}
        class="btn btn-sm preset-tonal-surface border border-surface-500 hover:preset-filled-warning-500"
        title="Clear App Data & Settings: Clear IndexedDB and reload. If in edit mode localStorage and sessionStorage will also be cleared."
        >
        <!-- <span class="fas fa-eraser mx-1"></span> -->
        <!-- <span class="fas fa-sync mx-1"></span> -->
        <RefreshCw />
        <span class="hidden md:inline">Clear & Reload</span>
    </button>

    <Help_tech
        e_class=""
        e_class_form_hidden=""
        e_class_form_showing="min-w-full"
        btn_class=""
        show_btn_class="btn-info"
        additional_kv={{
            'test': true,
        }}
        >
    </Help_tech>
</nav>


<!-- Add overflow-auto to section element to have the main nav sort of sticky at top -->
<section
    class:iframe={$ae_loc?.iframe}
    class:pt-12={nav_y_height <= 50}
    class:pt-20={nav_y_height > 50 && nav_y_height <= 100}
    class:pt-32={nav_y_height > 100 && nav_y_height <= 150}
    class:pt-40={nav_y_height > 150 && nav_y_height <= 200}
    class="
        main_content
        grow
        px-1 md:px-2
        pb-48
        "
    >
    {@render children()}
</section>


<div
    class:hidden={yTop < 500}
    class="
        z-20
        hover:opacity-100
        fixed bottom-48 right-1

        flex flex-col gap-1 items-end justify-end
        "
    >

    <!-- Scroll to top button -->
    <button
        type="button"
        class="
            ae_btn_success_outlined


            btn btn-sm btn-secondary
            preset-tonal-surface

            transition-all duration-500
            "
        class:hidden={yTop < 500}
        class:opacity-80={yTop > 750}
        class:opacity-0={yTop < 750}
        class:ae_btn_warning_filled={yTop > 1500}
        onclick={() => {
            log_lvl = 1;
            if (log_lvl) {
                console.log(`Scroll to top button clicked. scroll_y: ${scroll_y} scrollTop: ${scroll_container().scrollTop}`, scroll_container());
                // document.getElementById('ae_idaa')?.scrollTo(0, 0);
                // document.documentElement?.scrollTo(0, 0);
                // document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
                // document.body.scrollTop = 0; // For Safari
            }

            console.log('Not Safari, using smooth scroll to top');
            document.getElementById('ae_main_content')?.scrollTo({
                top: 0,
                behavior: 'smooth'
            });

            window.parent.postMessage({'scroll_to': 0}, "*"); // This should be
        }}
        title="Scroll to top"
        >
        <span class="fas fa-arrow-up"></span>
        Scroll to Top
    </button>

    <!-- Scroll to bottom button -->
    <button
        type="button"
        class="
            ae_btn_success_outlined

            btn btn-sm btn-secondary
            preset-tonal-surface

            transition-all duration-500
            "
        class:hidden={yTop < 500}
        class:opacity-80={yTop > 750}
        class:opacity-0={yTop < 750}
        class:ae_btn_warning_filled={yTop > 1500}
        onclick={() => {
            log_lvl = 1;
            if (log_lvl) {
                console.log(`Scroll to bottom button clicked. scroll_y: ${scroll_y} scrollTop: ${scroll_container().scrollTop}`, scroll_container());
                // document.getElementById('ae_idaa')?.scrollTo(0, 0);
                // document.documentElement?.scrollTo(0, 0);
                // document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
                // document.body.scrollTop = 0; // For Safari
            }

            console.log('Not Safari, using smooth scroll to bottom');
            document.getElementById('ae_main_content')?.scrollTo({
                top: scroll_y,
                behavior: 'smooth'
            });

            window.parent.postMessage({'scroll_to': scroll_y}, "*"); // This should be
        }}
        title="Scroll to bottom"
        >
        <span class="fas fa-arrow-down"></span>
        Scroll to Bottom
    </button>

</div>


<footer
    class:opacity-80={yTop < 250}
    class:opacity-0={yTop > 250}
    class="
        footer
        z-20
        hover:opacity-100
        absolute bottom-0 left-0 right-0
        w-full max-w-7xl
        p-1 m-auto

        flex flex-row flex-wrap
        items-center justify-between
        sm:flex-row md:items-center md:justify-between
        gap-1

        border-t-2 border-gray-200 dark:border-gray-600
        rounded-t-lg
        bg-gray-200 dark:bg-gray-800

        text-xs hover:text-base

        transition-all duration-1000
        "
    class:ae_debug={$ae_loc?.debug}
    >

    <Element_data_store
        ds_code="hub__site__appshell_footer"
        ds_type="html"
        class_li="grow flex flex-row justify-between"
        />

</footer>


</div>

{:else}
<section class="main_content grow px-1 md:px-2 pb-28 flex flex-col gap-1 items-center">
    <p class="text-center">
        You are not logged in as a user. You must be signed in to access the journals module.
    </p>
</section>
{/if}
