<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");
	// the welcome flow runs its own steps chrome, so the bar and footer step aside
	const isWelcomeShell = $derived(page.url.pathname === "/welcome");
	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-background-default text-foreground-default dark:bg-background-canvas"
		: isMarketingShell
			? "flex min-h-screen flex-col bg-linear-to-b from-background-default to-background-canvas text-foreground-default"
			: "flex min-h-screen flex-col bg-background-canvas text-foreground-default"}
>
	{#if !isAuthShell && !isWelcomeShell}
		<header
			class={isMarketingShell
				? "z-20 w-full bg-transparent pt-[env(safe-area-inset-top)]"
				: "top-0 z-20 w-full bg-background-default pt-[env(safe-area-inset-top)]"}
		>
			<Topbar
				user={auth.currentUser}
				variant={topbarVariant}
				loading={auth.state.kind === "authenticating" || auth.state.kind === "profile-loading"}
				onSignOut={auth.signOut}
			/>
		</header>
	{/if}

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

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