<script setup lang="ts">
import { request, unwrapApiBody, type ApiResponse } from '../../utils/http/factory'
import { useAuthSession } from '../../composables/useAuthSession'

const { loggedIn, user, clear } = useAuthSession()

const logoutLoading = ref(false)

async function logout() {
  logoutLoading.value = true
  try {
    unwrapApiBody(await request<ApiResponse<{ success: boolean }>>('/api/auth/logout', { method: 'POST' }))
    clear()
    await navigateTo('/login')
  } finally {
    logoutLoading.value = false
  }
}
</script>

<template>
  <div class="max-w-3xl mx-auto py-10">
    <UCard v-if="loggedIn">
      <template #header>
        <h1 class="text-xl font-semibold">欢迎回来</h1>
      </template>
      <p class="text-sm text-muted">当前用户：{{ user?.username }}</p>
      <UButton class="mt-4" color="neutral" :loading="logoutLoading" @click="logout">
        退出登录
      </UButton>
    </UCard>

    <UCard v-else>
      <template #header>
        <h1 class="text-xl font-semibold">欢迎来到本站</h1>
      </template>
      <p class="text-sm text-muted">登录后可访问更多受保护内容。</p>
      <div class="mt-4 flex gap-3">
        <UButton to="/login">去登录</UButton>
        <UButton to="/register" color="neutral" variant="outline">去注册</UButton>
      </div>
    </UCard>
  </div>
</template>