<script setup lang="ts">
import { ref } from "vue";
import { api, saveToken } from "../services/api";
import type { UserProfile } from "../types/api";

const emit = defineEmits<{
  loggedIn: [user: UserProfile];
}>();

const phone = ref("");
const code = ref("123456");
const loading = ref(false);
const message = ref("开发阶段验证码默认 123456");

async function sendCode() {
  loading.value = true;
  message.value = "";
  try {
    await api.sendSms(phone.value);
    message.value = "验证码已发送，开发阶段默认 123456";
  } catch (error) {
    message.value = error instanceof Error ? error.message : "发送失败";
  } finally {
    loading.value = false;
  }
}

async function login() {
  loading.value = true;
  message.value = "";
  try {
    const result = await api.login(phone.value, code.value);
    saveToken(result.token);
    emit("loggedIn", result.user);
  } catch (error) {
    message.value = error instanceof Error ? error.message : "登录失败";
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <section class="login-panel">
    <div class="brand-mark">AI</div>
    <h1>AI知识库助手</h1>
    <p>企业知识统一问答入口</p>

    <label>
      手机号
      <input v-model="phone" inputmode="numeric" maxlength="11" placeholder="请输入手机号" />
    </label>

    <label>
      验证码
      <div class="code-row">
        <input v-model="code" inputmode="numeric" maxlength="8" placeholder="验证码" />
        <button type="button" class="secondary" :disabled="loading || phone.length < 11" @click="sendCode">
          发送
        </button>
      </div>
    </label>

    <button type="button" class="primary" :disabled="loading || phone.length < 11 || code.length < 4" @click="login">
      {{ loading ? "处理中..." : "立即进入" }}
    </button>
    <div class="form-tip">{{ message }}</div>
  </section>
</template>
