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

// *** Import Svelte specific
import { untrack } from 'svelte';
import { browser } from '$app/environment';
import { afterNavigate } 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 {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { core_func } from '$lib/ae_core/ae_core_functions';
import { idaa_loc, idaa_sess, idaa_slct } from '$lib/stores/ae_idaa_stores';
import Element_data_store from '$lib/elements/element_data_store.svelte';

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

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

// 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: 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();
    // });
});

// NOTE: Fires after every client-side navigation within the IDAA module.
// Scrolls the parent Novi page to show the top of the iframe so the user
// doesn't land in the middle of new content after clicking a post/meeting/archive.
// The individual detail pages also send scroll_to on load — this catches the
// cases they miss (e.g. navigating back to the list view).
afterNavigate(() => {
    if ($ae_loc?.iframe) {
        window.parent.postMessage({ scroll_to: 0 }, '*');
    }
});

// let iframe = $derived(data.url.searchParams.get('iframe'));

// $effect(() => {
//     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');
//         // data_struct['iframe'] = false;
//         // WHY: The root layout sets sys_menu.hide=true when iframe=true, but never
//         // restores it. We restore it here so the system bar reappears when the URL
//         // param is explicitly set to false (e.g. admin toggling embed mode off).
//         untrack(() => {
//             $ae_loc.sys_menu.hide = false;
//         });
//     }
// });

// When in iframe mode, the sys bar is hidden by default (it's nav chrome the host page
// doesn't need). However, trusted admins should still get the menu — they can't update
// the iframe src to pass show_menu=true, so we watch for trusted_access and unhide it.

// let show_menu = $derived(data.url.searchParams.get('show_menu'));
// $effect(() => {
//     if (browser && $ae_loc.iframe && $ae_loc.trusted_access && show_menu === 'true') {
//         // WHY the guard: ae_loc is a tracked dep here (reads above). Writing
//         // $ae_loc.sys_menu.hide re-notifies this effect every run — infinite loop.
//         // untrack() does NOT help: it prevents new dep reads but the store still
//         // notifies already-subscribed effects after the write.
//         // The idempotent write guard breaks the cycle: run 2 finds the value
//         // already false, skips the write, no further re-queue.
//         if ($ae_loc.sys_menu.hide !== false) {
//             $ae_loc.sys_menu.hide = false;
//         }
//     }
// });

$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>
    <!-- FontAwesome 5 — used throughout IDAA module. Scoped here so it does not load on non-IDAA routes. -->
    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
        integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
        crossorigin="anonymous"
        referrerpolicy="no-referrer" />
    {#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}
    style="scrollbar-gutter: stable;"
    class="
        ae_idaa
        m-auto flex h-full max-h-fit
        max-w-6xl flex-col gap-1
        overflow-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-surface-500 hover:preset-filled-success-500 border">
            <House />
            <span class="hidden md:inline"> Home </span>
        </a>
    </nav>

    <!-- static position-static -->
    <section
        class="
        module_main_content main_content

        flex
        grow flex-col items-center
        justify-start gap-2 px-1 pb-28 md:px-2
        ">
        {@render children?.()}
    </section>

    <!-- The footer for the IDAA section of the site -->
    <!-- WHY the account_id guard: the outer IDAA layout renders before the inner (idaa) layout
         completes Novi UUID verification. Without it, element_data_store fires immediately with
         no account_id in the headers → 403. The footer is IDAA-specific content so it should
         only load once the member's identity is established. -->
    {#if $ae_loc.account_id}
        <section
            class="module_footer footer_content lg:text-md xl:text-md flex min-h-7 px-1 py-0.5 text-sm text-slate-400 transition hover:text-slate-800 sm:text-sm 2xl:text-lg"
            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>
    {/if}
</div>
<!-- </AppShell> -->

<!-- bottom-4 -->
<button
    type="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>
