<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NResult, NSpin, NIcon } from 'naive-ui'
import { LogInOutline, CheckmarkCircleOutline, ArrowBackOutline } from '@vicons/ionicons5'
import { useAuthStore } from '../../stores/auth'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()

const loading = ref(true)
const error = ref('')
const success = ref(false)
// 将 token 存入 sessionStorage（不在 URL 中传递）
const token = (route.query.token as string) || sessionStorage.getItem('pending_invite') || ''

onMounted(async () => {
  if (!token) { error.value = '缺少邀请令牌'; loading.value = false; return }

  if (!auth.isAuthenticated) {
    // 把 token 暂存到 sessionStorage，登录/注册后取回
    sessionStorage.setItem('pending_invite', token)
    loading.value = false  // 停止 loading，显示登录/注册按钮
    return
  }
  await accept()
})

async function accept() {
  loading.value = true
  try {
    const { api } = await import('../../api/client')
    const res = await api.post('/teams/invitations/accept', { token })
    if (res.data.status === 'joined' || res.data.status === 'already_member') {
      success.value = true
      sessionStorage.removeItem('pending_invite')
    }
  } catch (e: any) {
    error.value = e.response?.data?.detail || '邀请已失效或过期'
  } finally { loading.value = false }
}

function goToApp() { router.push('/app/feed') }
function goToLogin() { router.push(`/auth/login?redirect=/auth/accept`) }
function goToRegister() { router.push(`/auth/register?redirect=/auth/accept`) }
</script>

<template>
  <div class="auth-layout">
    <div class="auth-card">
      <div style="text-align:center;padding:24px 0">
        <NSpin :show="loading" size="large">
          <div v-if="!auth.isAuthenticated">
            <h3>🔬 邀请加入科室</h3>
            <p style="color:var(--text-secondary);margin:16px 0">请先登录或注册以接受邀请</p>
            <NButton type="primary" block @click="goToLogin" class="sky-btn" style="margin-bottom:8px"><template #icon><NIcon size="14"><LogInOutline /></NIcon></template>去登录</NButton>
            <NButton block @click="goToRegister" class="sky-btn"><template #icon><NIcon size="14"><CheckmarkCircleOutline /></NIcon></template>去注册</NButton>
          </div>
          <div v-else-if="success">
            <NResult status="success" title="已成功加入科室团队！" description="现在你可以查看科室共享文献、参与团队讨论了">
              <template #footer>
<NButton type="primary" class="sky-btn" @click="goToApp"><template #icon><NIcon size="14"><CheckmarkCircleOutline /></NIcon></template>进入应用</NButton>
              </template>
            </NResult>
          </div>
          <div v-else-if="error">
            <NResult status="error" :title="error">
              <template #footer>
                <NButton class="sky-btn" @click="goToApp"><template #icon><NIcon size="14"><ArrowBackOutline /></NIcon></template>返回首页</NButton>
              </template>
            </NResult>
          </div>
        </NSpin>
      </div>
    </div>
  </div>
</template>

<style scoped>
.auth-layout { min-height: 100vh; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, #1a5276 0%, #2e86c1 100%); }
.auth-card { background: var(--bg-card); border-radius: 12px; padding: 40px; width: 100%; max-width: 450px; box-shadow: 0 8px 32px rgba(0,0,0,0.12); }
</style>
