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

// *** Import Svelte specific
import { untrack } from 'svelte';
// import { browser } from '$app/environment';

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

// *** Import Aether specific variables and functions
import type { key_val } from '$lib/stores/ae_stores';
import { ae_loc, ae_sess, ae_api, slct } from '$lib/stores/ae_stores';
import Element_data_store from '$lib/elements/element_data_store.svelte';
import {
    EVENTS_MODULE_TITLE,
    events_sess,
    events_slct
} from '$lib/stores/ae_events_stores';

interface Props {
    /** @type {import('./$types').LayoutData} */
    data: any;
    children?: import('svelte').Snippet;
}

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

// Use effects for store initializations to prevent render-phase updates
$effect(() => {
    untrack(() => {
        $events_sess.qry__enabled = 'enabled';
        $events_sess.qry__hidden = 'not_hidden';
        $events_sess.qry__limit = 15;
        $events_sess.qry__offset = 0;
    });
});

// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
let ae_acct = $derived(data[data.account_id]);

$effect(() => {
    if (ae_acct) {
        untrack(() => {
            $events_slct.event_id = ae_acct.slct.event_id;
            $events_slct.event_obj_li = ae_acct.slct.event_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_x = $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
    );
}

function clear_idb() {
    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
}

function clear_local() {
    // localStorage.removeItem('ae_loc');
    // localStorage.removeItem('ae_idaa_loc');
    // localStorage.removeItem('ae_journals_loc');
    // localStorage.removeItem('ae_events_loc');

    $ae_loc.allow_access = false;
    $ae_loc.authenticated_access = false;
    $ae_loc.edit_mode = false;

    // $ae_loc.ver = '';

    localStorage.clear();
    // window.localStorage.clear();
}

function clear_sess() {
    // sessionStorage.removeItem('ae_sess');
    // sessionStorage.removeItem('ae_idaa_sess');
    // sessionStorage.removeItem('ae_journals_sess');
    // sessionStorage.removeItem('ae_events_sess');

    sessionStorage.clear();
}
</script>

<svelte:head>
    <title>
        &AElig;: Events - {EVENTS_MODULE_TITLE}
    </title>
</svelte:head>

<!-- WARNING: Add these when ready to better enabled dark mode! -->
<!-- bg-gray-50 dark:bg-gray-900 -->
<!-- text-gray-800 dark:text-gray-200 -->
<div
    id="ae_main_content"
    bind:clientHeight={$ae_loc.iframe_height}
    bind:this={box}
    onscroll={parse_scroll}
    class:iframe={$ae_loc?.iframe}
    class="
        ae_events
        container m-auto flex h-full min-h-full
        w-full max-w-7xl
        min-w-full flex-col gap-1
        overflow-auto [scrollbar-gutter:stable]

        bg-gray-50 text-gray-800
        dark:bg-gray-900 dark:text-gray-200
        ">
    {#if !$ae_sess?.disable_sys_nav && !$ae_loc?.iframe}
        <nav
            bind:clientHeight={nav_y_height}
            class:hidden={yTop > 600}
            class:opacity-0={yTop > 250}
            class="
                submenu
                absolute
                top-0
                right-0
                left-0 z-20 m-auto flex
                min-h-12 w-full
                max-w-7xl flex-col
                items-center justify-between gap-1

                rounded-b-lg border-b-2
                border-primary-200 dark:border-primary-800
                bg-primary-200/10 dark:bg-primary-800/10
                text-primary-900 dark:text-primary-100
                backdrop-blur-sm
                p-1 px-2
                transition-all duration-1000

                hover:opacity-100 sm:flex-row

                sm:flex-wrap md:min-h-14

                print:hidden
                ">
            <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 dark:text-gray-400" />
                <abbr title="Aether - Events Module" class="text-gray-500 dark:text-gray-400 font-semibold"> Æ Events </abbr>
            </span>
            {#if !$ae_sess?.disable_sys_header && $ae_loc.account_id}
                <Element_data_store
                    ds_code="hub__site__appshell_header"
                    ds_type="html" />
            {/if}
            <a
                href="/"
                class="btn btn-sm preset-tonal-surface border-surface-300-700 hover:border-surface-600-400 hover:preset-filled-primary-300-700 border">
                <House
                    size="1.5em"
                    class="mx-1 inline-block text-gray-500 dark:text-gray-400" />
                <span class="hidden md:inline text-gray-500 dark:text-gray-400"> Home </span>
            </a>
        </nav>
    {/if}

    <section
        class:iframe={$ae_loc?.iframe}
        class:pt-0={!!$ae_sess?.disable_sys_nav || $ae_loc?.iframe}
        class:pt-12={!$ae_sess?.disable_sys_nav &&
            nav_y_height > 0 &&
            nav_y_height <= 50}
        class:pt-20={!$ae_sess?.disable_sys_nav &&
            nav_y_height > 50 &&
            nav_y_height <= 100}
        class:pt-32={!$ae_sess?.disable_sys_nav &&
            nav_y_height > 100 &&
            nav_y_height <= 150}
        class:pt-40={!$ae_sess?.disable_sys_nav &&
            nav_y_height > 150 &&
            nav_y_height <= 200}
        class="
        main_content
        flex
        grow flex-col items-center
        justify-start
        gap-1 px-1 pb-[25vh]
        md:px-2
        lg:px-4
        ">
        <!-- Page Route Content -->
        {@render children?.()}
    </section>

    <div
        class:hidden={yTop < 500}
        class="
        fixed
        right-1
        bottom-40
        z-20 flex flex-col

        items-end justify-end gap-1 hover:opacity-100 print:hidden
        ">
        <!-- 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={() => {
                document.getElementById('ae_main_content')?.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });

                window.parent.postMessage({ scroll_to: 0 }, '*'); // This should be
            }}
            title="Scroll to top">
            <ArrowUp size="1em" aria-hidden="true" />
            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={() => {
                document.getElementById('ae_main_content')?.scrollTo({
                    top: yScroll,
                    behavior: 'smooth'
                });

                window.parent.postMessage({ scroll_to: scroll_y }, '*');
            }}
            title="Scroll to bottom">
            <ArrowDown size="1em" aria-hidden="true" />
            Scroll to Bottom
            <!-- yTop={yTop} yScroll={yScroll} yHeight={yHeight} scroll_y={scroll_y} scrollTop={scroll_container().scrollTop} total={scroll_container().scrollTop + yHeight} -->
        </button>
    </div>

    {#if !$ae_sess?.disable_sys_footer && $ae_loc.account_id}
        <footer
            class:hidden={yTop > 300}
            class:opacity-80={yTop < 250}
            class:opacity-0={yTop > 250}
            class="
        footer absolute right-0
        bottom-0
        left-0 z-20 m-auto flex
        w-full max-w-7xl
        flex-row flex-wrap
        items-center justify-between gap-1

        rounded-t-lg border-t-2
        border-primary-200 dark:border-primary-800
        bg-primary-200/10 dark:bg-primary-800/10
        text-primary-700 dark:text-primary-400
        backdrop-blur-sm
        p-1
        text-xs

        transition-all duration-1000 hover:text-base
        hover:opacity-100
        sm:flex-row md:items-center

        md:justify-between

        print:hidden
        "
            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>
    {/if}
</div>
