<script setup async lang="ts">
import { provide, ref } from 'vue';
import { useRouter } from 'vue-router';
import { TokenInjectType } from '@/api';

const router = useRouter();

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
});
</script>

<template>
	<nav>
		<template v-if="jwt != null">
			<router-link to="/">Files</router-link>
			<span style="margin-left: 2em" />
			<router-link to="/profile">Profile</router-link>
			<span style="margin-left: 2em" />
			<router-link to="/login" @click="logout()">Logout</router-link>
		</template>
	</nav>
	<router-view />
</template>

<style lang="scss">
#app {
	font-family: Avenir, Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
}

nav {
	padding: 30px;

	a {
		font-weight: bold;
		color: #2c3e50;

		&.router-link-exact-active {
			color: #42b983;
		}
	}
}
</style>
