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

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

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

	onDestroy(() => {
		if (unsub) {
			unsub();
		}
	});

	const signOut = async () => {
		try {
			await (auth as Auth).signOut();
		} catch (error) {
			console.error(error);
		}
	};
</script>

<div class="h-lvh flex flex-col">
	<div class="flex justify-end items-center min-h-10 gap-10 py-1 px-10 border-b border-accent">
		<a href="/" class="flex-1">ME-FIT</a>
		{#if user}
			<p>{user?.email}</p>
			<button class="btn" on:click={async () => signOut()}>Logout</button>
		{:else}
			<a href="/login" class="btn">Login</a>
		{/if}
	</div>

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