<script lang="ts">
	import Icon from "$lib/components/atoms/icon.svelte";
	import Footer from "$lib/components/molecules/footer/footer.svelte";
	import Navbar from "$lib/components/molecules/navbar/navbar.svelte";
	import { currencyVM } from "$lib/domains/currency/view/currency.vm.svelte";
	import { svTrpcApiStore, trpcApiStore } from "$lib/stores/api";
	import { sessionInfo, sessionUserInfo } from "$lib/stores/session.info";
	import { trpc, trpcRaw } from "$lib/trpc/trpc";
	import { onMount } from "svelte";
	import UpIcon from "~icons/material-symbols/keyboard-double-arrow-up-rounded";
	import type { LayoutData } from "./$types";

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

	sessionUserInfo.set(data.user);
	sessionInfo.set(data.session);

	svTrpcApiStore.set(trpc());

	// let invert = $derived(page.url.pathname === "/");

	let showScrollTop = $state(false);

	function scrollToTop() {
		window.scrollTo({ top: 0, behavior: "smooth" });
	}

	function handleScroll() {
		showScrollTop = window.scrollY > 200; // Show button when scrolled down 200px
	}

	onMount(() => {
		trpcApiStore.set(trpcRaw());

		currencyVM.loadCachedSelection();
		setTimeout(() => {
			currencyVM.getCurrencies();
		}, 500);

		// Add scroll event listener
		window.addEventListener("scroll", handleScroll);
		return () => {
			window.removeEventListener("scroll", handleScroll);
		};
	});
</script>

<Navbar invert={false} />

<div class="grid h-full w-full place-items-center overflow-x-hidden">
	<main class="flex w-full flex-col gap-8 overflow-x-hidden">
		{@render children?.()}
	</main>
</div>

<Footer />

<!-- Scroll to top FAB -->
{#if showScrollTop}
	<button
		onclick={scrollToTop}
		class="fixed bottom-4 left-4 z-50 flex h-12 w-12 items-center justify-center rounded-full border-2 border-white/60 bg-primary text-white shadow-lg transition-opacity hover:bg-primary/90 lg:bottom-8 lg:right-8"
		aria-label="Scroll to top"
	>
		<Icon icon={UpIcon} cls="w-auto h-6 text-white" />
	</button>
{/if}
