<script setup lang="ts">
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router'
import { useAuthStore } from './stores/auth'
import AlertDialog from './components/AlertDialog.vue'
import AnnouncementsBanner from './components/AnnouncementsBanner.vue'
import { computed } from 'vue'

const authStore = useAuthStore()
const router = useRouter()
const route = useRoute()

const onLoginPage = computed(() => route.path === '/login')

async function logOut() {
  authStore.logOut()
  await router.replace('/')
}

async function exitAdminViewAsUser() {
  if (!authStore.state) return
  authStore.state.adminAsUser = null
  await router.replace('/admin-dashboard')
}
</script>

<template>
  <header>
    <div>
      <nav class="global-navbar" v-if="!onLoginPage">
        <div>
          <span style="font-weight: bold; font-size: large;">Teacher Tools</span>
          <RouterLink class="link" to="/">Apps</RouterLink>
          <RouterLink class="link" to="/my-account" v-if="authStore.state">My Account</RouterLink>
          <RouterLink class="link" to="/admin-dashboard" v-if="authStore.isAdmin()">Admin</RouterLink>
        </div>

        <div>
          <RouterLink class="link" to="/login" v-if="!authStore.state">Login</RouterLink>
          <span v-if="authStore.state" style="margin-right: 0.25em; font-style: italic; font-size: smaller;">
            Logged in as <span v-text="authStore.state.username"
              style="font-weight: bold; font-style: normal; font-size: medium;"></span>
          </span>
          <span v-if="authStore.state && authStore.state.adminAsUser !== null"
            style="margin-right: 0.25em; font-style: italic; font-size: smaller">
            Viewing as <span v-text="authStore.state.adminAsUser.username"
              style="font-weight: bold; font-style: normal; font-size: medium;"></span>
            <button type="button" @click="exitAdminViewAsUser" style="margin-left: 0.25em;">Exit Admin View-As</button>
          </span>
          <button type="button" @click="logOut" v-if="authStore.state">Log out</button>
        </div>
      </nav>
    </div>
  </header>

  <AnnouncementsBanner />

  <RouterView />

  <!-- Global dialog elements are included here below, hidden by default. -->
  <AlertDialog />
</template>

<style scoped>
.global-navbar {
  display: flex;
  justify-content: space-between;
}

.global-navbar>div {
  display: inline-block;
}

.global-navbar>div>*+* {
  margin-left: 1em;
}
</style>
