<template>
  <div class="login-page">
    <van-nav-bar title="登录" left-text="返回" left-arrow @click-left="$router.back()" />

    <div class="login-content">
      <div class="login-hero">
        <h2>欢迎来到许愿树 ✨</h2>
        <p>登录后记录你的每一个心愿</p>
      </div>

      <van-form @submit="handleLogin">
        <van-cell-group inset>
          <van-field
            v-model="phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            type="tel"
            maxlength="11"
            :rules="[{ required: true, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]"
          />
          <van-field
            v-model="code"
            name="code"
            label="验证码"
            placeholder="请输入验证码"
            maxlength="6"
            :rules="[{ required: true, message: '请输入验证码' }]"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                plain
                :disabled="countdown > 0"
                @click="sendCode"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </van-button>
            </template>
          </van-field>
        </van-cell-group>

        <div class="submit-wrap">
          <van-button type="primary" block round native-type="submit" :loading="logging">
            登录
          </van-button>
        </div>
      </van-form>

      <p class="login-tip">Mock 模式：输入任意手机号和验证码即可登录</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showSuccessToast, showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { sendSms, login } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

const phone = ref('')
const code = ref('')
const countdown = ref(0)
const logging = ref(false)

function sendCode() {
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    showToast('请输入正确的手机号')
    return
  }
  sendSms(phone.value)
  showToast('验证码已发送（Mock模式任意6位数字）')
  countdown.value = 60
  const t = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) clearInterval(t)
  }, 1000)
}

async function handleLogin() {
  logging.value = true
  try {
    const res = await login(phone.value, code.value)
    userStore.login(res.data)
    showSuccessToast('登录成功')
    router.replace('/')
  } finally {
    logging.value = false
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: #f7f8fa;
}
.login-content {
  padding: 16px;
}
.login-hero {
  text-align: center;
  padding: 30px 0;
}
.login-hero h2 {
  font-size: 22px;
  margin-bottom: 6px;
}
.login-hero p {
  font-size: 14px;
  color: #999;
}
.submit-wrap {
  padding: 24px 16px;
}
.login-tip {
  text-align: center;
  font-size: 12px;
  color: #bbb;
  margin-top: 20px;
}
</style>
