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

const toast = useToast()
const route = useRoute()
const router = useRouter(); const auth = useAuthStore()
const formRef = ref<FormInst | null>(null)
const form = ref({ email: '', password: '', display_name: '', 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' }, { min: 8, message: '密码至少8位，需包含大小写字母和数字', trigger: 'blur' }],
  display_name: [{ 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 handleRegister() {
  error.value = ''
  try { await formRef.value?.validate() } catch { error.value = '请填写所有必填项'; return }
  loading.value = true
  try {
    const { data: verifyData } = await api.post('/captcha/verify', { captcha_id: captchaId.value, captcha_answer: Number(form.value.captchaAnswer) })
    form.value.captchaAnswer = ''; refreshCaptcha()
    await auth.register({ email: form.value.email, password: form.value.password, display_name: form.value.display_name, verify_token: verifyData.verify_token })
    router.push((route.query.redirect as string) || '/app/settings/interests')
  } catch (e: any) { error.value = e.response?.data?.detail || '注册失败'; refreshCaptcha() }
  finally { loading.value = false }
}
</script>

<template>
  <div class="auth-form">
    <h3 class="auth-title">免费注册（30秒）</h3>
    <NForm ref="formRef" :model="form" :rules="rules">
      <NFormItem path="email" class="tight-item"><NInput v-model:value="form.email" placeholder="邮箱地址" @keyup.enter="handleRegister" /></NFormItem>
      <NFormItem path="password" class="tight-item"><NInput v-model:value="form.password" type="password" placeholder="密码（至少8位，含大小写字母+数字）" @keyup.enter="handleRegister" /></NFormItem>
      <NFormItem path="display_name" class="tight-item"><NInput v-model:value="form.display_name" placeholder="怎么称呼你" @keyup.enter="handleRegister" /></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="handleRegister" />
            <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 type="primary" block :loading="loading" @click="handleRegister" class="submit-btn sky-btn"><template #icon><NIcon size="14"><PersonAddOutline /></NIcon></template>创 建 账 号</NButton>
    </NForm>
    <div style="text-align:center;margin-top:10px">
      <router-link to="/auth/login" style="font-size:13px;color:#1a5276">已有账号？去登录</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; }
.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-char:nth-child(odd) { transform-origin:bottom left; }
.c-char:nth-child(even) { transform-origin:top right; }
.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; }</style>
