<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-5xl mx-auto py-8 space-y-6">
    <UCard v-if="loggedIn">
      <template #header>
        <div class="flex items-start justify-between gap-4">
          <div>
            <h1 class="text-2xl font-semibold">欢迎回来，{{ user?.username }}</h1>
            <p class="text-sm text-muted mt-1">你已登录，可访问站内受保护内容。</p>
          </div>
          <UBadge color="success" variant="subtle">已登录</UBadge>
        </div>
      </template>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
        <UCard>
          <p class="text-xs text-muted">状态</p>
          <p class="mt-1 font-medium">会话有效</p>
        </UCard>
        <UCard>
          <p class="text-xs text-muted">入口</p>
          <p class="mt-1 font-medium">首页 / 配置 / API</p>
        </UCard>
        <UCard>
          <p class="text-xs text-muted">建议</p>
          <p class="mt-1 font-medium">可继续扩展个人中心</p>
        </UCard>
      </div>

      <div class="mt-5 flex items-center gap-3">
        <UButton color="neutral" :loading="logoutLoading" @click="logout">
          退出登录
        </UButton>
        <UButton to="/api/config/me" target="_blank" variant="outline">
          打开受保护接口
        </UButton>
      </div>
    </UCard>

    <UCard v-else>
      <template #header>
        <div class="flex items-start justify-between gap-4">
          <div>
            <h1 class="text-2xl font-semibold">欢迎来到本站</h1>
            <p class="text-sm text-muted mt-1">当前为访客模式，仅开放首页与认证页面。</p>
          </div>
          <UBadge color="neutral" variant="subtle">未登录</UBadge>
        </div>
      </template>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
        <UCard>
          <p class="text-xs text-muted">访问策略</p>
          <p class="mt-1 font-medium">登录优先，白名单放行</p>
        </UCard>
        <UCard>
          <p class="text-xs text-muted">安全能力</p>
          <p class="mt-1 font-medium">API 默认鉴权 + 401 统一处理</p>
        </UCard>
      </div>

      <div class="mt-5 flex gap-3">
        <UButton to="/login">去登录</UButton>
        <UButton to="/register" color="neutral" variant="outline">去注册</UButton>
      </div>
    </UCard>
  </div>
</template>