<script setup>
import { RouterLink, RouterView, useRouter } from "vue-router";
import { request } from "./assets/helpers.js";
import { ref, watch, computed } from "vue";
import { useEventBus } from "@vueuse/core";
import { useStore } from "vuex";

const router = useRouter();
const bus = useEventBus("login");
const userStore = useStore("userStore")

let loggedIn = ref(!!document.cookie.match(/session=/));
if (loggedIn.value) getUserInfo();

bus.on(() => {
	loggedIn.value = true
	getUserInfo();
});

async function getUserInfo() {
	userStore.dispatch("updateUserInfo");
}

async function logout() {
	await request("POST", "/logout");
	loggedIn.value = false;
	router.push("/");
}
</script>

<template>
	<header>
		<nav>
			<RouterLink to="/">Home</RouterLink>
			<RouterLink to="/about">About</RouterLink>

			<template v-if="!loggedIn">
				<RouterLink to="/login">Login</RouterLink>
				<RouterLink to="/register">Register</RouterLink>
			</template>

			<template v-else>
				<span style="color: #BDBDBD;">{{ userStore.state.userInfo?.username ?? "Loading.." }}</span>
				<a href="#" @click.prevent="logout">Log out</a>
			</template>
		</nav>

		<RouterView />
	</header>
</template>

<style scoped>

</style>
