<template>
  <section class="page-card">
    <div class="auth-callback">
      <div v-if="status === 'loading'" class="auth-status">
        <h2>正在验证登录...</h2>
        <p class="tag">请稍候，正在与萌芽认证中心确认身份</p>
      </div>
      <div v-else-if="status === 'success'" class="auth-status">
        <h2>登录成功</h2>
        <p class="tag">欢迎回来，{{ displayName }}！正在跳转...</p>
      </div>
      <div v-else class="auth-status">
        <h2>登录失败</h2>
        <p class="tag">{{ errorMessage }}</p>
        <button class="primary" @click="goHome">返回商店</button>
      </div>
    </div>
  </section>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { setAuth } from '../shared/auth'
import { verifySproutGateToken } from '../shared/api'

const router = useRouter()
const status = ref('loading')
const displayName = ref('')
const errorMessage = ref('')

const goHome = () => router.push('/')

const parseFragment = () => {
  const hash = window.location.hash.slice(1)
  const params = new URLSearchParams(hash)
  return {
    token:     params.get('token')     || '',
    account:   params.get('account')   || '',
    username:  params.get('username')  || '',
    avatarUrl: params.get('avatarUrl') || ''
  }
}

onMounted(async () => {
  const { token, account, username, avatarUrl: fragmentAvatar } = parseFragment()

  if (!token) {
    status.value = 'error'
    errorMessage.value = '未获取到登录令牌，请重试'
    return
  }

  try {
    // 验证 token 并从 SproutGate 获取最新用户信息
    const verifyData = await verifySproutGateToken(token)
    if (!verifyData.valid) {
      status.value = 'error'
      errorMessage.value = '令牌验证失败，请重新登录'
      return
    }

    const user = verifyData.user || {}
    const finalAccount   = user.account   || account
    const finalUsername  = user.username  || username
    const finalAvatarUrl = user.avatarUrl || fragmentAvatar
    const finalEmail     = user.email     || ''

    setAuth({ token, account: finalAccount, username: finalUsername, avatarUrl: finalAvatarUrl, email: finalEmail })
    displayName.value = finalUsername || finalAccount
    status.value = 'success'
    setTimeout(() => router.push('/'), 1000)
  } catch {
    // 验证失败（如网络异常）时，回退使用 URL fragment 中的数据
    setAuth({ token, account, username, avatarUrl: fragmentAvatar })
    displayName.value = username || account
    status.value = 'success'
    setTimeout(() => router.push('/'), 1000)
  }
})
</script>

<style scoped>
.auth-callback {
  display: flex;
  justify-content: center;
  padding: 48px 0;
}

.auth-status {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}
</style>
