<script lang="ts">
	import '../app.css';
	import { auth } from '$lib/stores/auth.svelte';
	import { refresh } from '$lib/stores/refresh.svelte';
	import { data } from '$lib/stores/data.svelte';
	import { AdminLayout, LoginScreen } from '$lib/layout';
	import { onMount, untrack } from 'svelte';

	let { children } = $props();
	let mounted = $state(false);

	onMount(() => {
		auth.init();
		mounted = true;
	});

	// Once authenticated, do initial fetch
	let dataInitialized = false;
	$effect(() => {
		if (!auth.authenticated) {
			dataInitialized = false;
			return;
		}

		if (mounted && auth.authenticated && !dataInitialized) {
			dataInitialized = true;
			data.fetchAll();
		}
	});

	// Auto-refresh driven by the global tick
	$effect(() => {
		void refresh.tick;
		untrack(() => {
			if (dataInitialized && data.initialLoaded) data.fetchAll();
		});
	});
</script>

<svelte:head>
	<title>Treehouse MC</title>
</svelte:head>

{#if !mounted || !auth.ready}
	<div class="loading-screen">
		<div class="loading-spinner"></div>
	</div>
{:else if !auth.authenticated}
	<LoginScreen />
{:else}
	<AdminLayout>
		{@render children()}
	</AdminLayout>
{/if}

<style>
	.loading-screen {
		min-height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		background: var(--bg);
	}
	.loading-spinner {
		width: 24px;
		height: 24px;
		border: 2px solid var(--border);
		border-top-color: var(--accent);
		border-radius: 50%;
		animation: spin 0.6s linear infinite;
	}
	@keyframes spin { to { transform: rotate(360deg); } }
</style>
