<script lang="ts">
	import '../app.css';
	import { onDestroy, onMount } from 'svelte';
	import type { Auth, User } from 'firebase/auth';
	import { addToast, toastStore } from '$lib/toast';
	import type { Toast } from '$lib/toast';

	var auth: Auth | null = null;
	var user: User | null = null;
	var unsubAuth: (() => void) | null = null;

	let toasts: Toast[] = [];
	let unsubToast = toastStore.subscribe((value) => {
		toasts = value;
	});

	onMount(async () => {
		const { auth: _auth } = await import('../lib/firebase');
		auth = _auth;
		user = auth.currentUser;
		unsubAuth = auth.onAuthStateChanged((newUser) => {
			user = newUser;
		});
	});

	onDestroy(() => {
		unsubToast();
		if (unsubAuth) {
			unsubAuth();
		}
	});

	const signOut = async () => {
		try {
			await (auth as Auth).signOut();
			addToast('Signed out successfully', 'success');
		} catch (error) {
			console.error(error);
		}
	};
</script>

<svelte:head>
	<title>ME-FIT</title>
</svelte:head>

<div class="h-screen flex flex-col">
	<div class="flex justify-end items-center gap-2 py-1 px-2 md:gap-10 md:px-10 md:py-2 shadow">
		<a href="/" class="flex-1 flex gap-2">
			<img src="/favicon.svg" alt="ME-FIT logo" />
			<span>ME-FIT</span>
		</a>
		{#if user}
			<p class="hidden md:block">{user?.email}</p>
			<button class="btn btn-sm" on:click={async () => signOut()}>Sign Out</button>
		{:else}
			<a href="/signup" class="btn btn-sm">Sign Up</a>
			<a href="/signin" class="btn btn-sm">Sign In</a>
		{/if}
	</div>

	<div class="flex-1">
		<slot></slot>
	</div>

	<!-- This is needed so all class names are inside the bundle The class names are used dynamically, so -->
	<!-- tailwind can't know -->
	<div class="hidden">
		<div class="alert-info text-info-content"></div>
		<div class="alert-success text-success-content"></div>
		<div class="alert-warning text-warning-content"></div>
		<div class="alert-error text-error-content"></div>
	</div>

	<div class="toast toast-end">
		{#each toasts as toast}
			<div class="alert alert-{toast.type}">
				<span class="text-{toast.type}-content">{toast.message}</span>
			</div>
		{/each}
	</div>
</div>
