<script lang="ts">
/** @type {import('./$types').LayoutData} */
export let data;
// console.log(`ae_ Svelte root +layout data:`, data);

import { onMount } from 'svelte';
import '../app.postcss';

import { AppShell, AppBar, initializeStores } from '@skeletonlabs/skeleton';
// Initialize the stores for Drawer, Modal, and Toast so they work throughout the app.
initializeStores();
import { Drawer, Modal, getDrawerStore } from '@skeletonlabs/skeleton';
import type {
    // DrawerSettings, DrawerComponent, DrawerStore,
    ModalSettings, ModalComponent, ModalStore
    } from '@skeletonlabs/skeleton';
const drawerStore = getDrawerStore();

// import ModalComponentEditSponsorshipObj from './sponsorships/10_edit_modal__sponsorship_obj.svelte';

const modalRegistry: Record<string, ModalComponent> = {
	// Set a unique modal ID, then pass the component reference
	// modalComponentEditSponsorshipObj: { ref: ModalComponentEditSponsorshipObj },
	// modalComponentTwo: { ref: ModalComponentTwo },
	// ...
};


// Highlight JS
import hljs from 'highlight.js/lib/core';
import 'highlight.js/styles/github-dark.css';
import type { Writable } from 'svelte/store';
import { get } from 'svelte/store';
import { page } from "$app/stores";
import { localStorageStore, storeHighlightJs } from '@skeletonlabs/skeleton';
import xml from 'highlight.js/lib/languages/xml'; // for HTML
import css from 'highlight.js/lib/languages/css';
import javascript from 'highlight.js/lib/languages/javascript';
import typescript from 'highlight.js/lib/languages/typescript';

hljs.registerLanguage('xml', xml); // for HTML
hljs.registerLanguage('css', css);
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('typescript', typescript);
storeHighlightJs.set(hljs);

// Floating UI for Popups
import { computePosition, autoUpdate, flip, shift, offset, arrow } from '@floating-ui/dom';
import { storePopup } from '@skeletonlabs/skeleton';
storePopup.set({ computePosition, autoUpdate, flip, shift, offset, arrow });


import { api } from '$lib/api';
import { ae_loc, ae_sess, ae_api, slct, slct_trigger } from '$lib/ae_stores';
import type { key_val } from '$lib/ae_stores';
// console.log($ae_loc, $ae_sess, $ae_api);


import Element_access_type from '$lib/element_access_type.svelte';
import Element_app_cfg from '$lib/element_app_cfg.svelte';




onMount(() => {
    console.log('Root: +layout.svelte');
	if ($ae_loc.iframe) {
        console.log('Use iframe layout!');

        document.getElementsByTagName('html')[0].classList.add('iframe');
        document.getElementsByTagName('html')[0].classList.remove('dark');
        document.getElementsByTagName('html')[0].classList.remove('light');

        $ae_loc.hub.show_element__access_type = false;
        $ae_loc.hub.show_element__cfg = false;
    } else if ($ae_loc.trusted_access) {
        $ae_loc.hub.show_element__access_type = true;
        $ae_loc.hub.show_element__cfg = true;
    } else {
        $ae_loc.hub.show_element__access_type = true;
        $ae_loc.hub.show_element__cfg = false;
    }
});


// $ae_loc = data;

// const ae_loc_test_store: Writable<string> = localStorageStore('ae_loc_test', {'test': 'This is a test'});
// // Subscribe to the store
// ae_loc_test_store.subscribe(() => {});

// // Update the value
// ae_loc_test_store.update(() => {});

// // Set the value
// ae_loc_test_store.set(() => {});

// // // Read the value
// get(ae_loc_test_store);

// // // Read value with automatic subscription
// $ae_loc_test_store

let data_store_obj_get_promises: key_val = {};
// let get_ds_hub_page_access_code_li_json_promise = handle_get_data_store_obj_w_code({code: 'hub__page__access_code_li_json', data_type: 'json', trigger: 'set_access_code_li'});
// let get_ds_hub_site_header_promise = handle_get_data_store_obj_w_code({code: 'hub_site_header'});
// let get_ds_hub_site_footer_promise = handle_get_data_store_obj_w_code({code: 'hub_site_footer'});


async function handle_get_data_store_obj_w_code({ code=null, data_type='text', trigger=null }) {
    console.log(`*** handle_get_data_store_obj_w_code() *** code=${code}`);

    if (!code) {
        console.log('No code provided.');
        return;
    }
    // let get_item_result = window.localStorage.getItem(code);
    // localStorage.getItem(code);

    // if ($ae_loc_test_store) {
    //     $ae_loc.ds[code] = $ae_loc_test_store;
    // } else {
    //     console.log('Get local storage item miss.');
    // }

    data_store_obj_get_promises[code] = api.get_data_store_obj_w_code({
        api_cfg: $ae_api,
        data_store_code: code,
        data_type: data_type,
        log_lvl: 0
        })
    .then(function (get_data_store_result) {
        if (get_data_store_result) {

            if (data_type == 'text') {
                // console.log(get_data_store_result.text);
                $ae_loc.ds[code] = get_data_store_result.text;
            } else if (data_type == 'json') {
                // console.log(get_data_store_result.json);
                $ae_loc.ds[code] = get_data_store_result.json;
            }

            // console.log(`Code: ${$ae_loc.ds[code]}`);
            // console.log(`Code:`, $ae_loc.ds[code]);

            if (trigger) {
                $slct_trigger = trigger;
            }
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });
}

$slct_trigger = 'set_access_code_li';
$: if ($slct_trigger == 'set_access_code_li' && !$ae_loc.ds['hub__page__access_code_li_json']) {
    console.log(`$ae_loc.ds['hub__page__access_code_li_json'] = `, $ae_loc.ds['hub__page__access_code_li_json']);
    $slct_trigger = null; // Reset the trigger to prevent loops

    $ae_loc.page_access_code_li = $ae_loc.ds['hub__page__access_code_li_json'];
    $ae_loc = $ae_loc; // Trigger Svelte just in case
    console.log($ae_loc);
}


// let ae_site_domain_obj_get_promise;
// $slct_trigger = 'lookup_fqdn';
// $: if ($slct_trigger == 'lookup_fqdn' && data.url.host) {
//     $slct_trigger = null; // Reset the trigger to prevent loops
//     // $ae_loc.url_host = data.url.host; // Use this to look up? sub.example.com:123
//     $ae_loc.fqdn = data.url.host; // Use this to look up? sub.example.com:123
//     // $ae_loc.url_hostname = data.url.hostname; // sub.example.com
//     // $ae_loc.url_origin = data.url.origin; // Use this to look up? https://sub.example.com:123
//     // $ae_loc.site_domain = data.url.origin;
//     console.log(`$ae_loc = `, $ae_loc);

//     handle_load_ae_obj_id__site_domain({fqdn: $ae_loc.fqdn, try_cache: false});
// }


// async function handle_load_ae_obj_id__site_domain({fqdn, try_cache=false}) {
//     console.log(`*** handle_load_ae_obj_id__site_domain() *** fqdn=${fqdn}`);

//     let params = {};

// 	// $ae_loc.hub.site_domain_id_qry_status = 'loading';
//     ae_site_domain_obj_get_promise = api.get_ae_obj_id_crud({
//         api_cfg: $ae_api,
//         no_account_id: true,
//         obj_type: 'site_domain',
//         obj_id: fqdn, // NOTE: This is the FQDN, not normally the ID.
//         use_alt_table: true, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
//         use_alt_base: true, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
//         params: params,
//         log_lvl: 2
//         })
//     .then(function (site_domain_obj_get_result) {
//         if (site_domain_obj_get_result) {
//             $slct.site_domain_obj = site_domain_obj_get_result;
//             console.log(`site_domain object:`, $slct.site_domain_obj);

//             $ae_loc.account_id = $slct.site_domain_obj.account_id_random;
//             $ae_loc.site_id = $slct.site_domain_obj.site_id_random;
//             $ae_loc.site_domain_id = $slct.site_domain_obj.site_domain_id_random;
//         }
//     })
//     .catch(function (error) {
//         console.log('No results returned or failed.', error);
//     });

//     return ae_site_domain_obj_get_promise;
// }
</script>


<svelte:head>
	<title>{data.ae_loc.title}</title>
    <link rel="stylesheet" href="{data.ae_loc.site_style_href}">
    <!-- <link rel="manifest" href="/manifest.json"> -->
</svelte:head>


<!-- regionFooter="flex justify-end space-x-2" -->

<Modal components={modalRegistry}
    regionBackdrop=''
    regionBody=''
    regionHeader='modal-header card-header text-2xl font-bold'
    regionFooter='modal-footer flex justify-between space-x-2'
    />


<!-- <Drawer>
	{#if $drawerStore.id === 'example-1'}
		(show 'example-1' contents)
	{:else if $drawerStore.id === 'example-2'}
		(show 'example-2' contents)
    {:else if $drawerStore.id === 'sponsorships__edit'}
		(show 'sponsorships__edit__sponsorship_obj' contents)
        <section class="sponsorships_editing">
        </section>
	{:else}
		(fallback contents)
	{/if}
</Drawer> -->


<!-- App Shell -->
<AppShell
    regionPage={($ae_loc.iframe ? 'iframe' : '')}
    slotHeader={($ae_loc.iframe ? 'iframe' : '')}
    slotFooter={($ae_loc.iframe ? 'iframe' : '')}
    >

    <svelte:fragment slot="header">
        <!-- App Bar -->
        <AppBar gridColumns="grid-cols-3" slotDefault="place-self-center" slotTrail="place-content-end">
            <svelte:fragment slot="lead">
                {#if $ae_loc.ds['hub__page__appshell_header_lead']}
                    {@html $ae_loc.ds['hub__page__appshell_header_lead']}
                {:else}
                    <a href="/" class="text-xl">
                        <span class="fas fa-home"></span> &AElig; Home
                    </a>
                {/if}

            </svelte:fragment>
            <!-- OSIT's Aether App -->
            {@html $ae_loc.ds['hub__site__appshell_header']}
            <svelte:fragment slot="trail">
                {#if $ae_loc.ds['hub__page__appshell_header_trail']}
                    {@html $ae_loc.ds['hub__page__appshell_header_trail']}
                {:else}
                    <a
                        class="btn btn-sm variant-ghost-surface"
                        href="/testing"
                        >
                        Testing X
                    </a>

                    <a
                        class="btn btn-sm variant-ghost-surface"
                        class:active={$page.url.pathname==='/sponsorships'}
                        href="/sponsorships">Sponsorships</a>

                    <a
                        class="btn btn-sm variant-ghost-surface"
                        class:active={$page.url.pathname==='/events_speakers'}
                        href="/events_speakers">Speakers</a>
                {/if}
            </svelte:fragment>
        </AppBar>


        <!-- <AppBar>
            <svelte:fragment slot="lead">
                <strong class="text-xl uppercase">Skeleton</strong>
            </svelte:fragment>
            <svelte:fragment slot="trail">
                <a
                    class="btn btn-sm variant-ghost-surface"
                    href="https://discord.gg/EXqV7W8MtY"
                    target="_blank"
                    rel="noreferrer"
                >
                    Discord
                </a>
                <a
                    class="btn btn-sm variant-ghost-surface"
                    href="https://twitter.com/SkeletonUI"
                    target="_blank"
                    rel="noreferrer"
                >
                    Twitter
                </a>
                <a
                    class="btn btn-sm variant-ghost-surface"
                    href="https://github.com/skeletonlabs/skeleton"
                    target="_blank"
                    rel="noreferrer"
                >
                    GitHub
                </a>
            </svelte:fragment>
        </AppBar> -->
    </svelte:fragment>


    <!-- Page Route Content -->
    <slot />


    <svelte:fragment slot="footer">
        <div class="flex justify-between space-x-2 text-slate-400 hover:text-slate-800 transition">
            {@html $ae_loc.ds['hub__site__appshell_footer']}
        </div>
    </svelte:fragment>


</AppShell>


{#if $ae_loc.hub.show_element__access_type}
<Element_access_type />
{/if}


<span
    class:hidden={!$ae_loc.hub.show_element__cfg}
    >
<!-- {#if $ae_loc.hub.show_element__cfg} -->
<Element_app_cfg set_theme_mode={true} set_theme_name={true} />
<!-- {/if} -->
</span>


<style lang="postcss">
</style>
