<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 { 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/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_v3.svelte';
    import {
        events_loc,
        events_sess,
        events_slct,
        events_trigger,
        events_trig_kv
    } 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_loc.qry__enabled = 'enabled';
            $events_loc.qry__hidden = 'not_hidden';
            $events_loc.qry__limit = 15;
            $events_loc.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_loc.title ?? 'Æ loading...'}
    </title>
</svelte:head>

{#if $events_loc?.ver && $events_loc?.ver !== $events_sess?.ver}
    <div class="fixed inset-0 bg-pink-100/80 z-40">
        <button
            type="button"
            class="
            fixed top-16 left-0 right-0 z-50 p-4 m-8 sm:mx-16 md:mx-32
            btn btn-lg rounded-2xl
            preset-tonal-warning hover:preset-filled-success-200-800
            border-4 border-warning-300 dark:border-warning-700
            transition-all
            "
            onclick={async () => {
                // Clear the IndexedDB
                clear_idb();

                // // Clear localStorage and sessionStorage
                // clear_local();
                // // clear_sess();

                // alert('The page will now reload. You may need to sign in again.');
                // // location.reload();
                // // window.location.reload(true);
                // goto('/');

                localStorage.clear();
                sessionStorage.clear();

                alert(
                    'The page will now reload. You may need to sign in again.'
                );

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

                location.reload();
            }}
            title="A new version of One Sky IT's Aether Events module is available. Click to reload the page and use the latest version."
        >
            <span class="fas fa-sync-alt fa-spin m-1"></span>
            <span class="m-4 sm:mx-8 text-wrap">
                New Events Module Version Available!<br />
                Click to Reload<br />
                <div class="italic text-base">
                    You may need to sign in again.
                </div>
            </span>
            <span class="fas fa-sync-alt fa-spin m-1"></span>

            <!-- <span class="text-xs">
            $events_loc.ver=${$events_loc?.ver}<br>
            $events_sess.ver=${$events_sess?.ver}
        </span> -->
        </button>
    </div>
{/if}

<!-- 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
        min-h-full h-full min-w-full w-full max-w-7xl
        overflow-auto container
        flex flex-col gap-1
        m-auto

        bg-gray-50 dark:bg-gray-900
        text-gray-800 dark:text-gray-200
        "
>
    {#if !$ae_sess?.disable_sys_nav}
        <nav
            bind:clientHeight={nav_y_height}
            class:hidden={yTop > 600}
            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 md:min-h-20
        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 - Events Module"> Æ Events </abbr>
            </span>
            {#if !$ae_sess?.disable_sys_header}
                <Element_data_store
                    ds_code="hub__site__appshell_header"
                    ds_type="html"
                />
            {/if}
            <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>
        </nav>
    {/if}

    <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 lg:px-4
        pb-48
        flex flex-col gap-1
        items-center
        justify-start
        "
    >
        <!-- Page Route Content -->
        {@render children?.()}
    </section>

    <div
        class:hidden={yTop < 500}
        class="
        z-20
        hover:opacity-100
        fixed bottom-40 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={() => {
                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={() => {
                document.getElementById('ae_main_content')?.scrollTo({
                    top: yScroll,
                    behavior: 'smooth'
                });

                window.parent.postMessage({ scroll_to: scroll_y }, '*');
            }}
            title="Scroll to bottom"
        >
            <span class="fas fa-arrow-down"></span>
            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}
        <footer
            class:hidden={yTop > 300}
            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>
    {/if}
</div>
