<script lang="ts">
	import { page } from '$app/stores';
	import { env } from '$env/dynamic/public';
	import { IconOutline } from 'svelte-heros-v2';
	import { buttonTriggeredRequest } from '$lib/components/utils';
	import { goto } from '$app/navigation';
	import type { LayoutData } from './$types';
	import { adminCount } from '$lib/stores';

	async function logout() {
		const response = await fetch(`${env.PUBLIC_BASE_PATH}/admin/logout`, {
			method: 'POST'
		});
		if (response.ok) {
			await goto(`${env.PUBLIC_BASE_PATH}/`);
		} else {
			throw new Error();
		}
	}

	export let data: LayoutData;
	if (data.adminCount) $adminCount = data.adminCount;
</script>

{#if $page.url.pathname !== `${env.PUBLIC_BASE_PATH}/admin/login`}
	<div class="flex h-screen">
		<div class="h-full">
			<ul class="menu p-4 w-max h-full bg-base-200 text-base-content">
				{#if data.userCount != null}
					<li>
						<a href="{env.PUBLIC_BASE_PATH}/admin/users">
							<IconOutline name="user-group-outline" />
							<span class="ml-1">Registrierte Nutzer</span>
							<div class="badge">{data.userCount}</div>
						</a>
					</li>
				{/if}
				{#if data.adminCount != null}
					<li>
						<a href="{env.PUBLIC_BASE_PATH}/admin/admin">
							<IconOutline name="users-outline" />
							<span class="ml-1">Website Admins</span>
							<div class="badge">{$adminCount}</div>
						</a>
					</li>
				{/if}
				<li class="mt-auto">
					<button on:click={(e) => buttonTriggeredRequest(e, logout())}>
						<IconOutline name="arrow-left-on-rectangle-outline" />
						<span class="ml-1">Ausloggen</span>
					</button>
				</li>
			</ul>
		</div>
		<div class="h-full w-full overflow-scroll">
			<slot />
		</div>
	</div>
{:else}
	<div class="h-full w-full">
		<slot />
	</div>
{/if}
