<!-- This is common file and will render through all pages -->

<script lang="ts">
	import '../app.css';
	import favicon from '$lib/assets/favicon.svg';

	import { AdbInstance } from './state.svelte';

	import * as NavigationMenu from '$lib/components/ui/navigation-menu/index.js';
	import { onMount } from 'svelte';
	import { onAuthStateChanged } from 'firebase/auth';
	import { auth as authStore } from '$lib/core/stores/auth';
	import { auth } from '$lib/core/client/firebase';
	import { goto } from '$app/navigation';
	import { getUserPermission } from '$lib/core/auth/userPermissions';
	import { permission as currentPermissions } from '$lib/core/stores/permissions';
	import { get } from 'svelte/store';

	import { ModeWatcher } from 'mode-watcher';
	import { Toaster } from '$lib/components/ui/sonner';
	import { departmentStore } from '$lib/core/stores/departments';
	import { browser } from '$app/environment';
	import {
		deleteCookiesOnNonBrowser,
		extractCookieOnNonBrowser,
		setCookieOnNonBrowser
	} from '$lib/helpers/cookie';

	let { children } = $props();

	onMount(() => {
		console.log('base url', window.location.origin, document.cookie);

		onAuthStateChanged(auth, async function (s) {
			authStore.set(s);
			if (s) {
				if (browser && 'cookieStore' in window) await cookieStore.set('logged_in', 'true');
				else {
					setCookieOnNonBrowser('logged_in', 'true');
				}
			} else {
				if (browser && 'cookieStore' in window) await cookieStore.delete('logged_in');
				else {
					deleteCookiesOnNonBrowser('logged_in');
				}
				await goto('/login');
			}
		});
		return authStore.subscribe(async function (user) {
			// console.log(`store get ${JSON.stringify(user)}`);
			// reloading permissions
			if (get(currentPermissions).length == 0 && user != null) {
				// need update
				let currentUser = user;
				currentPermissions.set(await getUserPermission(currentUser));
				console.log('reloading permissions ... ');
			}

			if (!get(departmentStore)) {
				let saved =
					browser && 'cookieStore' in window
						? await cookieStore.get('department')
						: extractCookieOnNonBrowser()['department'];
				if (saved) {
					departmentStore.set(saved.value);
					console.log('get dep', get(departmentStore));
				}
			}
		});
	});
</script>

<svelte:head>
	<link rel="icon" href={favicon} />
	<link href="https://fonts.googleapis.com/css2?family=Roboto+Flex" rel="stylesheet" />
	<title>Taobin Management Tools</title>
</svelte:head>

<ModeWatcher />
<Toaster />
{@render children()}
