<template>
  <section class="page-card">
    <div class="flex justify-center py-12">
      <div v-if="status === 'loading'" class="text-center flex flex-col items-center gap-3">
        <h2>正在验证登录...</h2>
        <p class="tag">请稍候，正在与萌芽认证中心确认身份</p>
      </div>
      <div v-else-if="status === 'success'" class="text-center flex flex-col items-center gap-3">
        <h2>登录成功</h2>
        <p class="tag">欢迎回来，{{ displayName }}！正在跳转...</p>
      </div>
      <div v-else class="text-center flex flex-col items-center gap-3">
        <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 {
    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 {
    setAuth({ token, account, username, avatarUrl: fragmentAvatar })
    displayName.value = username || account
    status.value = 'success'
    setTimeout(() => router.push('/'), 1000)
  }
})
</script>
