<script lang="ts">
	import '../app.css';
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { getSupabase } from '$lib/supabase';
	import { currentUser, authLoading } from '$lib/stores/auth';
	import { userCollectives, currentCollective } from '$lib/stores/collective';
	import { ParaglideJS } from '@inlang/paraglide-sveltekit';
	import { i18n } from '$lib/i18n';

	onMount(() => {
		const supabase = getSupabase();

		const {
			data: { subscription }
		} = supabase.auth.onAuthStateChange((event, session) => {
			currentUser.set(session?.user ?? null);
			authLoading.set(false);

			if (session) {
				// Defer out of the onAuthStateChange callback so the internal auth
				// lock is fully released before we make any PostgREST query.
				// Without this, queries hang on `getAccessToken() -> initializePromise`
				// in some browser environments (e.g. Playwright headless Chromium).
				setTimeout(async () => {
					await loadUserCollectives(session.user.id);

					if (event === 'SIGNED_IN') {
						// Post-login: send the user where they belong.
						// Only redirect when coming from the callback or the root — not on
						// token refreshes or when the user is already on a real route.
						const path = $page.url.pathname;
						if (path === '/auth/callback' || path === '/') {
							if ($userCollectives.length === 0) {
								goto('/onboarding');
							} else {
								goto('/lists');
							}
						}
					}
				}, 0);
			}
		});

		return () => subscription.unsubscribe();
	});

	async function loadUserCollectives(userId: string): Promise<void> {
		const supabase = getSupabase();

		const { data } = await supabase
			.from('collective_members')
			.select('collective_id, role, collectives(id, name, emoji, created_at)')
			.eq('user_id', userId);

		if (!data) return;

		type CollectiveRow = { id: string; name: string; emoji: string; created_at: string };
		const collectives = data
			.map((row) => {
				const c = row.collectives as CollectiveRow | null;
				return c ? { id: c.id, name: c.name, emoji: c.emoji, created_at: c.created_at } : null;
			})
			.filter((c): c is CollectiveRow => c !== null);

		userCollectives.set(collectives);

		// Restore last active collective from localStorage, or default to first
		const savedId = localStorage.getItem('activeCollectiveId');
		const active = collectives.find((c) => c.id === savedId) ?? collectives[0] ?? null;
		currentCollective.set(active);
		if (active) localStorage.setItem('activeCollectiveId', active.id);
	}
</script>

<ParaglideJS {i18n}>
	<slot />
</ParaglideJS>
