<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { CSSProperties } from 'vue'
import { NForm, NFormItem, NInput, NButton, type FormInst, type FormRules } from 'naive-ui'
import { useAuthStore } from '../../stores/auth'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'

const toast = useToast()
const router = useRouter(); const route = useRoute(); const auth = useAuthStore()
const formRef = ref<FormInst | null>(null)
const form = ref({ email: '', password: '', captchaAnswer: '' })
const loading = ref(false); const error = ref('')
const captchaId = ref(''); const captchaQuestion = ref(''); const captchaRefreshing = ref(false)
const captchaChars = ref<Array<{char:string;style:CSSProperties}>>([])
const COLORS = ['#1a5276','#c0392b','#27ae60','#8e44ad','#d35400','#2980b9','#b7950b']

const rules: FormRules = {
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captchaAnswer: [{ required: true, message: '请填写验证码', trigger: 'blur' }],
}

onMounted(refreshCaptcha)
async function refreshCaptcha() {
  captchaRefreshing.value = true
  try {
    const { data } = await api.get('/captcha/generate')
    captchaId.value = data.id
    captchaQuestion.value = data.question
    captchaChars.value = (data.question as string).split('').map(c => ({
      char: c === ' ' ? '\xa0' : c,
      style: {
        transform: `rotate(${(Math.random()-0.5)*16}deg) translateY(${(Math.random()-0.5)*3}px)`,
        color: COLORS[Math.floor(Math.random()*COLORS.length)],
      }
    }))
  } catch (e) { toast.apiError(e, "刷新验证码失败") }
  finally { captchaRefreshing.value = false }
}
async function handleLogin() {
  error.value = ''
  try { await formRef.value?.validate() } catch { error.value = '请填写所有必填项'; return }
  loading.value = true
  try {
    await api.post('/captcha/verify', { captcha_id: captchaId.value, captcha_answer: Number(form.value.captchaAnswer) })
    form.value.captchaAnswer = ''; refreshCaptcha()
    await auth.login(form.value.email, form.value.password)
    // 只允许相对路径跳转，防止开放重定向
    const redirect = route.query.redirect as string
    const safePath = redirect && redirect.startsWith('/') ? redirect : '/app/feed'
    router.push(safePath)
  } catch (e: any) {
    const d = e.response?.data?.detail
    error.value = Array.isArray(d) ? (d[0]?.msg || '登录失败') : d || e.response?.data?.error?.message || '登录失败'
    refreshCaptcha()
  }
  finally { loading.value = false }
}
</script>

<template>
  <div class="auth-form">
    <h3 class="auth-title">用户登录</h3>
    <p class="auth-sub">OncoLit 体验版</p>
    <NForm ref="formRef" :model="form" :rules="rules">
      <NFormItem path="email" class="tight-item"><NInput v-model:value="form.email" placeholder="邮箱地址" @keyup.enter="handleLogin" /></NFormItem>
      <NFormItem path="password" class="tight-item"><NInput v-model:value="form.password" type="password" placeholder="密码" @keyup.enter="handleLogin" /></NFormItem>
      <NFormItem path="captchaAnswer" class="tight-item">
        <div class="captcha-block">
          <div class="captcha-input-group">
            <NInput v-model:value="form.captchaAnswer" placeholder="答案" @keyup.enter="handleLogin" />
            <NButton :loading="captchaRefreshing" @click="refreshCaptcha" class="captcha-btn sky-btn" title="换一个">
              <template #icon>
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M17.65 6.35A7.96 7.96 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>
              </template>
            </NButton>
          </div>
          <div class="captcha-chip" v-if="captchaQuestion">
            <span v-for="(ch, i) in captchaChars" :key="i" class="c-char" :style="ch.style">{{ ch.char }}</span>
            <span class="c-answer-label">= ?</span>
          </div>
        </div>
      </NFormItem>
      <div v-if="error" class="form-error">{{ error }}</div>
      <NButton block :loading="loading" @click="handleLogin" class="submit-btn sky-btn">登 录</NButton>
    </NForm>

    <div class="auth-links">
      <router-link to="/auth/register">没有账号？马上注册</router-link>
      <router-link to="/auth/forgot-password">忘记密码？</router-link>
    </div>
  </div>
</template>

<style scoped>
.auth-form { padding: 0; }
.auth-title { text-align:center; font-size:20px; margin:0 0 4px; font-weight:700; }
html.dark .auth-title { color: #e0e0e0; }
.auth-sub { text-align:center; color:var(--text-muted); font-size:13px; margin:0 0 12px; }
.tight-item { margin-bottom: 0 !important; }
.tight-item :deep(.n-form-item-blank) { padding-top: 0 !important; padding-bottom: 0 !important; }
.tight-item :deep(.n-form-item-feedback-wrapper) { min-height: 0 !important; height: 0 !important; overflow: hidden !important; }
.captcha-btn { width:40px; min-width:40px; height:40px; padding:0; font-size:18px; display:flex; align-items:center; justify-content:center; }
.captcha-btn :deep(.n-button__content) { color: var(--text-secondary); }
html.dark .captcha-btn :deep(.n-button__content) { color: #6ab0e0; }
.captcha-block { display:flex; flex-direction:row; align-items:center; gap:6px; width:100%; }
.captcha-chip { display:flex; align-items:center; gap:1px; padding:4px 8px; background:var(--bg-page); border-radius:4px; user-select:none; white-space:nowrap; flex-shrink:0; }
.captcha-input-group { display:flex; gap:6px; flex:1; min-width:0; }
.c-char { display:inline-block; font-size:16px; font-weight:700; font-family:'Georgia','Times New Roman',serif; }
.c-answer-label { font-size:13px; color:var(--text-muted); white-space:nowrap; }
.form-error { color:#d03050; font-size:13px; margin:0 0 4px; text-align:center; }
.submit-btn { height:40px; margin-top:14px; }
.auth-links { display:flex; justify-content:space-between; margin-top:6px; font-size:13px; }
.auth-links a { color:var(--text-muted); text-decoration:none; }
.auth-links a:hover { color: var(--kw-pill-color); }
html.dark .auth-links a:hover { color: #6ab0e0; }
</style>
