<template>
  <!-- 未登录 → 登录页 -->
  <LoginPage v-if="!auth.loggedIn" @login-success="onLoginSuccess" />
  <!-- 已登录 → 管理后台 -->
  <MainLayout v-else />
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import LoginPage from '@/views/LoginPage.vue'
import MainLayout from '@/layouts/MainLayout.vue'
import { isLoggedIn, clearTokens } from '@/utils/token'
import { toast } from '@/utils/toast'

const auth = useAuthStore()

function onLoginSuccess(user: any) {
  auth.onLoginSuccess(user)
}

onMounted(async () => {
  // 启动时验证登录态
  if (isLoggedIn()) {
    const ok = await auth.fetchUser()
    if (!ok) {
      // 尝试刷新 Token
      const refreshed = await auth.tryRefreshToken()
      if (refreshed) {
        await auth.fetchUser().catch(() => {})
      } else {
        auth.logout()
      }
    }
  }

  // 监听 401 事件
  window.addEventListener('auth:unauthorized', async () => {
    const refreshed = await auth.tryRefreshToken()
    if (refreshed) {
      await auth.fetchUser().catch(() => {})
    } else {
      auth.logout()
      toast('登录已过期，请重新登录', 'error')
    }
  })
})
</script>
