<script lang="ts">
	import { page } from '$app/state';
	import { createAuth, AUTH_KEY } from '$lib/auth.svelte';
	import Footer from '$lib/components/shell/Footer.svelte';
	import Topbar from '$lib/components/shell/Topbar.svelte';
	import { onMount, setContext, untrack } from 'svelte';
	import '../app.css';

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

	const auth = createAuth(
		data.publicConfig.bobbinUrl,
		untrack(() => data.auth)
	);
	setContext(AUTH_KEY, auth);

	onMount(() => {
		if (page.url.pathname !== '/oauth/callback') void auth.refresh();
	});

	const signedIn = $derived(Boolean(auth.currentUser));
	const isAuthShell = $derived(page.url.pathname === '/login');
	const isMarketingShell = $derived(
		!signedIn && (page.url.pathname === '/about' || page.url.pathname === '/')
	);
	const topbarVariant = $derived(isMarketingShell ? 'marketing' : 'app');
</script>

<svelte:head>
	<title>Tangled</title>
</svelte:head>

<div
	class={isAuthShell
		? 'flex min-h-screen flex-col bg-bg-auth text-fg'
		: isMarketingShell
			? 'flex min-h-screen flex-col bg-gradient-to-b from-bg-auth to-bg text-fg'
			: 'flex min-h-screen flex-col bg-bg text-fg'}
>
	{#if !isAuthShell}
		<header
			class={isMarketingShell
				? 'z-20 w-full bg-transparent pt-[env(safe-area-inset-top)]'
				: 'sticky top-0 z-20 w-full bg-surface pt-[env(safe-area-inset-top)] shadow-sm'}
		>
			<Topbar
				user={auth.currentUser}
				variant={topbarVariant}
				loading={auth.authenticating || auth.profileLoading}
				onSignOut={auth.signOut}
			/>
		</header>
	{/if}

	<main class={isAuthShell ? 'flex flex-grow items-center justify-center px-7' : 'flex-grow'}>
		{@render children()}
	</main>

	{#if !isAuthShell}
		<Footer variant={isMarketingShell ? 'full' : 'minimal'} />
	{/if}
</div>
