<script setup async lang="ts">
import type { MenuOption } from 'naive-ui';
import { provide, ref, h } from 'vue';
import { useRouter, RouterLink } from 'vue-router';
import type { TokenInjectType } from '@/api';
import { useMessage, NMenu, NPageHeader, NIcon } from 'naive-ui';
import { BareMetalServer02 } from '@vicons/carbon';

const router = useRouter();
const message = useMessage();

const jwt = ref<string | null>(localStorage.getItem('token'));

function setToken(token: string) {
	jwt.value = token;
	localStorage.setItem('token', token);
}

function logout() {
	jwt.value = null;
	localStorage.removeItem('token');
	router.push({ name: 'login' });
}

provide<TokenInjectType>('jwt', {
	jwt,
	setToken,
	logout
});

router.afterEach(() => message.destroyAll());

function handleUpdateValue(key: string) {
	if (key === 'login') logout();
}

const menuOptions: MenuOption[] = [
	{
		label: () =>
			h(
				RouterLink,
				{
					to: '/'
				},
				{ default: () => 'Files' }
			),
		key: 'fs'
	},
	{
		label: () =>
			h(
				RouterLink,
				{
					to: '/profile'
				},
				{ default: () => 'Profile' }
			),
		key: 'profile'
	},
	{
		label: () =>
			h(
				RouterLink,
				{
					to: '/login'
				},
				{ default: () => 'Logout' }
			),
		key: 'login'
	}
];
</script>

<template>
	<n-page-header style="margin-bottom: 3em">
		<template #title>
			<n-icon class="nav-icon" size="1.5em">
				<BareMetalServer02 />
			</n-icon>
			MFileserver
		</template>
		<template #extra>
			<n-menu
				v-if="jwt != null"
				mode="horizontal"
				:options="menuOptions"
				@update:value="handleUpdateValue"
			/>
		</template>
	</n-page-header>
	<router-view />
</template>

<style lang="scss">
body {
	height: 100%;
	padding: 2em;
	display: flex;
	justify-content: center;
	align-content: center;
}

#app {
	font-family: Avenir, Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	color: #2c3e50;
}

.nav-icon {
	top: 0.25em;
}
</style>
