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

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

onMounted(() => {
  username.value = getSavedUsername()
  rememberMe.value = getRememberPreference()
})

async function handleLogin() {
  error.value = ''
  if (!username.value || !password.value) {
    error.value = '请填写用户名和密码'
    return
  }
  loading.value = true
  try {
    const { data } = await api.login(username.value, password.value, rememberMe.value)
    setAuth(data.access_token, rememberMe.value, 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">WordLoop</div>
    <p class="auth-sub">单词循环记忆系统</p>
    <div v-if="error" class="message error">{{ error }}</div>
    <form class="card" @submit.prevent="handleLogin">
      <label class="label">用户名</label>
      <input v-model="username" class="input" placeholder="请输入用户名" autocomplete="username" />
      <label class="label">密码</label>
      <input
        v-model="password"
        type="password"
        class="input"
        placeholder="请输入密码"
        autocomplete="current-password"
      />
      <label class="remember-row">
        <input v-model="rememberMe" type="checkbox" class="remember-check" />
        <span>记住登录状态（关闭浏览器后仍保持登录，有效期约 30 天）</span>
      </label>
      <button type="submit" class="btn btn-primary" style="margin-top: 16px" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </form>
    <p class="auth-link">还没有账号？<router-link to="/register">立即注册</router-link></p>
  </div>
</template>

<style scoped>
.auth-page {
  padding-top: 60px;
}
.auth-logo {
  font-size: 32px;
  font-weight: 800;
  color: var(--primary);
  text-align: center;
}
.auth-sub {
  text-align: center;
  color: var(--muted);
  margin: 8px 0 24px;
}
.label {
  display: block;
  font-size: 13px;
  color: var(--muted);
  margin: 12px 0 6px;
}
.remember-row {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-top: 14px;
  font-size: 13px;
  color: var(--muted);
  cursor: pointer;
  line-height: 1.4;
}
.remember-check {
  margin-top: 2px;
  flex-shrink: 0;
}
.auth-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}
</style>
