<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../api/request'
import { setAuth } from '../utils/auth'

const router = useRouter()
const username = ref('')
const password = ref('')
const confirm = ref('')
const error = ref('')
const loading = ref(false)

async function handleRegister() {
  error.value = ''
  if (!username.value || !password.value) {
    error.value = '请填写完整信息'
    return
  }
  if (password.value !== confirm.value) {
    error.value = '两次密码不一致'
    return
  }
  if (password.value.length < 6) {
    error.value = '密码至少 6 位'
    return
  }
  loading.value = true
  try {
    await api.register(username.value, password.value)
    const { data } = await api.login(username.value, password.value, true)
    setAuth(data.access_token, true, username.value)
    router.push('/')
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    error.value = err.response?.data?.detail || '注册失败'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="page auth-page">
    <div class="auth-logo">注册账号</div>
    <div v-if="error" class="message error">{{ error }}</div>
    <form class="card" @submit.prevent="handleRegister">
      <label class="label">用户名</label>
      <input v-model="username" class="input" placeholder="2-50 个字符" autocomplete="username" />
      <label class="label">密码</label>
      <input v-model="password" type="password" class="input" placeholder="至少 6 位" autocomplete="new-password" />
      <label class="label">确认密码</label>
      <input v-model="confirm" type="password" class="input" placeholder="再次输入密码" autocomplete="new-password" />
      <button type="submit" class="btn btn-primary" style="margin-top: 16px" :disabled="loading">
        {{ loading ? '注册中...' : '注册' }}
      </button>
    </form>
    <p class="auth-link">已有账号？<router-link to="/login">去登录</router-link></p>
  </div>
</template>

<style scoped>
.auth-page { padding-top: 40px; }
.auth-logo {
  font-size: 26px;
  font-weight: 700;
  text-align: center;
  margin-bottom: 20px;
}
.label {
  display: block;
  font-size: 13px;
  color: var(--muted);
  margin: 12px 0 6px;
}
.auth-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}
</style>
