<script lang="ts">
	import '../app.css';
	import { page } from '$app/stores';
	import { stdb, pgWsConnect, pgWsDisconnect } from '$lib/spacetime';
	import { browser } from '$app/environment';
	import SystemAnnouncements from '$lib/components/SystemAnnouncements.svelte';

	let { children } = $props();

	// Connect to SpacetimeDB when authenticated and in browser
	$effect(() => {
		if (browser && $page.data.session?.user) {
			stdb.connect();
		}
		return () => {
			if (browser) stdb.disconnect();
		};
	});

	// Connect PG WebSocket in parallel for verification (Fase M1, oppgave 22.1)
	$effect(() => {
		const session = $page.data.session as Record<string, unknown> | undefined;
		const accessToken = session?.accessToken as string | undefined;
		if (browser && accessToken) {
			pgWsConnect(accessToken);
		}
		return () => {
			if (browser) pgWsDisconnect();
		};
	});
</script>

<SystemAnnouncements />
{@render children()}
