<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const success = ref(false)
const title = ref('')
const message = ref('')

const primaryLabel = ref('')
const primaryUrl = ref('')
const secondaryLabel = ref('')
const secondaryUrl = ref('')

const redirectUrl = ref('')
const secondsLeft = ref(0)
let countdownTimer = null

function loadInitialState() {
  if (typeof window === 'undefined') return null
  const state = window.__APP_INITIAL_STATE__
  if (!state || typeof state !== 'object') return null
  window.__APP_INITIAL_STATE__ = null
  return state
}

function normalize(state) {
  const ok = Boolean(state?.success)
  success.value = ok

  title.value = state?.title || (ok ? '验证成功' : '验证失败')
  message.value =
    state?.message || state?.error_message || (ok ? '操作已完成，现在可以继续使用系统。' : '操作失败，请稍后重试。')

  primaryLabel.value = state?.primary_label || (ok ? '立即登录' : '重新注册')
  primaryUrl.value = state?.primary_url || (ok ? '/login' : '/register')
  secondaryLabel.value = state?.secondary_label || (ok ? '' : '返回登录')
  secondaryUrl.value = state?.secondary_url || (ok ? '' : '/login')

  redirectUrl.value = state?.redirect_url || (ok ? '/login' : '')
  secondsLeft.value = Number(state?.redirect_seconds || (ok ? 5 : 0)) || 0
}

const hasSecondary = computed(() => Boolean(secondaryLabel.value && secondaryUrl.value))
const hasCountdown = computed(() => Boolean(redirectUrl.value && secondsLeft.value > 0))

async function go(url) {
  if (!url) return
  if (url.startsWith('http://') || url.startsWith('https://')) {
    window.location.href = url
    return
  }
  await router.push(url)
}

function startCountdown() {
  if (!hasCountdown.value) return
  countdownTimer = window.setInterval(() => {
    secondsLeft.value -= 1
    if (secondsLeft.value <= 0) {
      window.clearInterval(countdownTimer)
      countdownTimer = null
      window.location.href = redirectUrl.value
    }
  }, 1000)
}

onMounted(() => {
  const state = loadInitialState()
  normalize(state)
  startCountdown()
})

onBeforeUnmount(() => {
  if (countdownTimer) window.clearInterval(countdownTimer)
})
</script>

<template>
  <div class="auth-wrap">
    <el-card shadow="never" class="auth-card" :body-style="{ padding: '22px' }">
      <div class="brand">
        <div class="brand-title">知识管理平台</div>
        <div class="brand-sub app-muted">验证结果</div>
      </div>

      <el-result
        :icon="success ? 'success' : 'error'"
        :title="title"
        :sub-title="message"
        class="result"
      >
        <template #extra>
          <div class="actions">
            <el-button type="primary" @click="go(primaryUrl)">{{ primaryLabel }}</el-button>
            <el-button v-if="hasSecondary" @click="go(secondaryUrl)">{{ secondaryLabel }}</el-button>
          </div>
          <div v-if="hasCountdown" class="countdown app-muted">
            {{ secondsLeft }} 秒后自动跳转...
          </div>
        </template>
      </el-result>
    </el-card>
  </div>
</template>

<style scoped>
.auth-wrap {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.auth-card {
  width: 100%;
  max-width: 520px;
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
  box-shadow: var(--app-shadow);
}

.brand {
  margin-bottom: 14px;
}

.brand-title {
  font-size: 18px;
  font-weight: 900;
}

.brand-sub {
  margin-top: 4px;
  font-size: 12px;
}

.result {
  padding: 8px 0 2px;
}

.actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}

.countdown {
  margin-top: 10px;
  text-align: center;
  font-size: 13px;
}
</style>

