<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { clearSession, session } from './stores/session'
import * as api from './services/api'
import { t, toggleLocale } from './i18n'
import ToastContainer from './components/ToastContainer.vue'

const router = useRouter()

const isAuthed = computed(() => Boolean(session.token))

async function onLogout() {
  try {
    await api.logout()
  } catch {
    // Ignore remote logout failure and clear local session anyway.
  }
  clearSession()
  router.push('/auth/login')
}
</script>

<template>
  <div class="app-bg"></div>
  <div class="layout">
    <aside class="sidebar">
      <h1>{{ t('brand_name') }}</h1>
      <p class="caption">{{ t('brand_caption') }}</p>
      <nav>
        <template v-if="isAuthed">
          <RouterLink to="/todos">{{ t('nav_todo') }}</RouterLink>
          <RouterLink to="/team">{{ t('nav_team') }}</RouterLink>
          <RouterLink to="/settings/user">{{ t('nav_user_settings') }}</RouterLink>
          <RouterLink to="/settings/team">{{ t('nav_team_settings') }}</RouterLink>
        </template>
        <template v-else>
          <RouterLink to="/auth/login">{{ t('nav_login') }}</RouterLink>
        </template>
      </nav>
      <div class="sidebar-foot">
        <span>{{ session.email || t('guest_mode') }}</span>
        <button class="btn" @click="toggleLocale">{{ t('language') }}: {{ t('lang_switch') }}</button>
        <button v-if="isAuthed" class="btn danger" @click="onLogout">{{ t('logout') }}</button>
      </div>
    </aside>
    <main class="content"><RouterView /></main>
    <ToastContainer />
  </div>
</template>
