<script lang="ts">
let log_lvl: number = 2;

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

// *** Import other supporting libraries
// import * as icons from '@lucide/svelte';
import {
        Brain,
        House, Library,
        RefreshCw,
        Satellite
    } from '@lucide/svelte';
// import { AppBar } from '@skeletonlabs/skeleton-svelte';
// import type {
//     ModalComponent
//     } from '@skeletonlabs/skeleton-svelte';


// *** Import Aether specific variables and functions
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { core_func } from '$lib/ae_core/ae_core_functions';
import { idaa_loc, idaa_sess, idaa_slct } from '$lib/ae_idaa_stores';
import Element_data_store from '$lib/element_data_store_v2.svelte';

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

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

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


if (browser) {
    add_activity_log(
        {
            action: 'idaa_root_layout',
            action_with: 'browser',
        }
    );
}

function add_activity_log(
        {
            action = 'idaa_root_layout',
            action_with = 'none',
        }: {
            action?: string,
            action_with?: string,
        }
    ) {

    let last_cache_refresh_iso = new Date($ae_loc?.last_cache_refresh);

    let activity_description = `
        ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? 'no-email'}
        allow=${$ae_loc?.allow_access}
        last_cache_refresh=${last_cache_refresh_iso.toLocaleString()}
        data_route=${data?.route.toString() ?? 'unknown'}
    `;

    let data_kv = {
        external_client_id: data?.route.id,
        name: `IDAA: ${$idaa_loc.novi_full_name ?? 'none'} ${$idaa_loc.novi_email ?? ''}`,
        description: activity_description ?? null,
        object_type: 'idaa', // archive, post, event
        // object_id_random: data?.route,
        url_root: data?.url.origin,
        // url_full_path: data?.url.href,
        url_full_path: data?.url.pathname,
        url_params: data?.url.searchParams.toString(),
        action: action,
        action_with: action_with ?? 'none',
        meta_json: {
            allow_access: $ae_loc?.allow_access,
            last_cache_refresh: $ae_loc?.last_cache_refresh,
            last_cache_refresh_iso: last_cache_refresh_iso.toISOString(),
            last_cache_refresh_locale: last_cache_refresh_iso.toLocaleString(),
            access_level: $ae_loc?.access_level,
            iframe: $ae_loc?.iframe,
            // site_access_key: $ae_loc?.site_access_key,
            // site_domain_access_key: $ae_loc?.site_domain_access_key,
            // site_domain: $ae_loc?.site_domain,
            // extra_data: extra_data ?? '',
            // log_lvl: log_lvl,
        }
    };

    core_func.create_ae_obj__activity_log({
        api_cfg: $ae_api,
        account_id: $ae_loc.account_id,
        data_kv: data_kv,
        log_lvl: log_lvl
    });
}

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);

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}`);
}


let is_safari = $state(/^((?!chrome|android).)*safari/i.test(navigator.userAgent));

let hide_scroll_btn = $state(true); // This is to hide the scroll to top button initially
let scroll_y = $state(0);

function go_top() {
    // document.body.scrollIntoView();
    scroll_container().scrollIntoView();
}

function scroll_container() {
    // console.log('Element', document.getElementById('ae_idaa__recovery_meetings'))
    // return document.documentElement || document.body;
    return document.getElementById('ae_idaa') || document.documentElement || document.body;
}

// function handle_on_scroll() {
//     if (!scroll_container()) {
//         return;
//     }
//     console.log(`Scroll position: ${scroll_container().scrollTop}`);

//     let show_on_px = 500; // The scroll position at which the button will be shown

//     if (scroll_container().scrollTop > show_on_px) {
//         hide_scroll_btn = false;
//     } else {
//         hide_scroll_btn = true;
//     }
// }

$effect(() => {
    // console.log(`idaa_root_layout.svelte`);
    // if (scroll_y) {
    //     console.log(`Scroll position: ${scroll_y}`);
    //     // handle_on_scroll();
    // }

    // if (yTop) {
    //     console.log(`Scroll container top diff: ${yTop}`);
    // }

    //  else {
        // hide_scroll_btn = true; // Hide the button if scroll_y is 0
    // }
    // if (log_lvl > 1) {
    //     console.log(`idaa_root_layout.svelte: data:`, data);
    // }

    // If the browser is Safari, we need to handle the scroll differently
    if (is_safari) {
        console.log('Safari detected, using special scroll handling');
        $ae_loc.browser_type = 'safari';
    }

    // // Initial scroll position
    // scroll_y = scroll_container().scrollTop;

    // // Set up the scroll event listener
    // window.addEventListener('scroll', () => {
    //     scroll_y = scroll_container().scrollTop;
    //     handle_on_scroll();
    // });
});

// if (browser) {
//     $idaa_loc.novi_uuid = data.params.uuid;
//     $idaa_loc.novi_email = decodeURIComponent(data.params.email);
//     $idaa_loc.novi_full_name = decodeURIComponent(data.params.full_name);
//     // $idaa_loc.novi_admin_li = novi_admin_li;
//     // $idaa_loc.novi_trusted_li = novi_trusted_li;
//     console.log(`$idaa_loc.novi_uuid:`, $idaa_loc.novi_uuid);
// }

let iframe = data.url.searchParams.get('iframe');
if (browser && iframe == 'true') {
    console.log('Use iframe layout!');
    // data_struct['iframe'] = iframe;
    $ae_loc.iframe = true;

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

    // $ae_loc.app_cfg.show_element__access_type = false;
    // $ae_loc.app_cfg.show_element__cfg = false;
} else if (browser && iframe == 'false') {
    // data_struct['iframe'] = false;
    $ae_loc.iframe = false;

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

$effect(() => {
    if ($ae_loc.iframe && $ae_loc.iframe_height && $ae_loc.iframe_height_modal_body) {
        if (log_lvl > 1) {
            console.log('Getting new dimensions for iframe with modal:', $ae_loc.iframe_height, $ae_loc.iframe_height_modal_body);
        }

        let iframe_height = 0;

        if ($ae_loc.iframe_height > $ae_loc.iframe_height_modal_body) {
            iframe_height = $ae_loc.iframe_height;
        } else {
            iframe_height = $ae_loc.iframe_height_modal_body;

            // console.log($ae_loc.modal_dimensions);

            if ($ae_loc.modal_dimensions && $ae_loc.modal_dimensions.header_height) {
                iframe_height = iframe_height + $ae_loc.modal_dimensions.header_height;
            }
            if ($ae_loc.modal_dimensions && $ae_loc.modal_dimensions.footer_height) {
                iframe_height = iframe_height + $ae_loc.modal_dimensions.footer_height;
            }
            // iframe_height = iframe_height + 50; // Just in case
        }

        if (log_lvl > 1) {
            console.log(`Suggested new iframe_height with modal: ${iframe_height}`);
        }
        if (iframe_height > 4096) {
            console.warn('iframe_height is getting too large, setting to 4096px');
            iframe_height = 4096; // Limit the height to a maximum of 4096px
        }
        window.parent.postMessage({'iframe_height': iframe_height}, "*"); // This should be in pixels
    } else if ($ae_loc.iframe && $ae_loc.iframe_height) {
        if (log_lvl > 1) {
            console.log('Suggested new iframe_height:', $ae_loc.iframe_height);
        }

        let iframe_height = 0;
        iframe_height = $ae_loc.iframe_height;

        if (iframe_height > 4096) {
            console.warn('iframe_height is getting too large, setting to 4096px');
            iframe_height = 4096; // Limit the height to a maximum of 4096px
        }
        window.parent.postMessage({'iframe_height': iframe_height}, "*"); // This should be in pixels
    }
});

</script>

<svelte:head>
	<title>IDAA - {$idaa_loc?.title ?? 'Æ loading...'}</title>
    {#if $ae_loc.iframe}
    <!-- <meta name="robots" content="noindex, nofollow" /> -->
    <link href="https://assets-staging.noviams.com/novi-core-assets/css/fontawesome.css" rel="stylesheet" />
    <link href="https://assets-staging.noviams.com/novi-core-assets/css/c/idaa/idaa.css" rel="stylesheet" />
    {/if}
</svelte:head>

<!-- <svelte:window onscroll={handle_on_scroll} /> -->
<!-- <svelte:window bind:scrollY={scroll_y} /> -->
<!-- h-full max-h-full  -->
<div
    id="ae_idaa"
    bind:clientHeight={$ae_loc.iframe_height}
    bind:this={box}
    onscroll={parse_scroll}
    class:iframe={$ae_loc?.iframe}
    class="
        ae_idaa
        h-full max-h-fit max-w-6xl overflow-auto
        flex flex-col gap-1
        m-auto
        "
    >

<nav
    class="
        module_header
        submenu
        flex flex-row flex-wrap
        items-center justify-between
        gap-1
        border-b-2
        p-1
        px-2
        pb-2
        "
    >
    <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 - IDAA Module">
            Æ
            IDAA
        </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>
</nav>

<section
    class="
        module_main_content main_content
        grow
        px-1 md:px-2 pb-28
        flex flex-col gap-2 items-center justify-start
        "
    >

    {@render children?.()}

</section>


<section
    class="module_footer footer_content flex text-sm sm:text-sm lg:text-md xl:text-md 2xl:text-lg text-slate-400 hover:text-slate-800 transition px-1 py-0.5 min-h-7"
    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"
        />

</section>


</div>
<!-- </AppShell> -->

<!-- bottom-4 -->
<button
    class="ae_idaa__recovery_meetings__scroll_top_btn btn btn-sm btn-secondary preset-tonal-surface fixed top-1/2 right-1 z-50 opacity-75 hover:opacity-100"
    class:hidden={yTop < 750}
    class:ae_btn_warning_outlined={is_safari}
    class:ae_btn_success_outlined={!is_safari}
    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
        }
        // var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
        if (is_safari) {
            console.log('Safari detected, not using smooth scroll to top.');
            document.getElementById('ae_idaa')?.scrollTo(0, 0);

            if ($ae_loc?.iframe) {
                // If in iframe, we need to send a message to the parent window to scroll to top
                console.log('In Safari iframe, sending message to parent window to scroll to top as well');
                window.parent.postMessage({'scroll_to': 0}, "*"); // This should be in pixels
            }
        } else {
            console.log('Not Safari, using smooth scroll to top');
            document.getElementById('ae_idaa')?.scrollTo({
                top: 0,
                behavior: 'smooth'
            });

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