<script setup lang="ts">
import { useAuth } from "~/composables/useAuth";
import type { CaptchaData } from "~/composables/useAuth";

const props = defineProps<{
  mode: "login" | "register";
}>();

const emit = defineEmits<{
  submit: [data: { username: string; password: string; captchaToken: string; captchaCode: string }];
}>();

const auth = useAuth();

const username = ref("");
const password = ref("");
const captchaCode = ref("");
const captcha = ref<CaptchaData | null>(null);
const captchaLoading = ref(false);
const errorMsg = ref("");

async function refreshCaptcha() {
  captchaLoading.value = true;
  try {
    captcha.value = await auth.fetchCaptcha();
  } finally {
    captchaLoading.value = false;
  }
}

function handleSubmit() {
  errorMsg.value = "";

  if (!username.value.trim()) {
    errorMsg.value = "请输入用户名";
    return;
  }
  if (!password.value) {
    errorMsg.value = "请输入密码";
    return;
  }
  if (props.mode === "register" && password.value.length < 8) {
    errorMsg.value = "密码长度不能少于8位";
    return;
  }
  if (!captchaCode.value.trim()) {
    errorMsg.value = "请输入验证码";
    return;
  }
  if (!captcha.value) {
    errorMsg.value = "请先获取验证码";
    return;
  }

  emit("submit", {
    username: username.value.trim(),
    password: password.value,
    captchaToken: captcha.value.token,
    captchaCode: captchaCode.value.trim(),
  });
}

function setError(msg: string) {
  errorMsg.value = msg;
}

defineExpose({ setError, refreshCaptcha });

onMounted(() => {
  refreshCaptcha();
});
</script>

<template>
  <div class="w-full max-w-[380px] mx-auto">
    <!-- Header -->
    <div class="text-center mb-10">
      <h1 v-if="mode === 'login'" class="text-[34px] font-semibold tracking-[-0.374px] leading-[1.47]" style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #1d1d1f;">
        登录
      </h1>
      <h1 v-else class="text-[34px] font-semibold tracking-[-0.374px] leading-[1.47]" style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #1d1d1f;">
        创建账户
      </h1>
      <p class="mt-2 text-[17px] leading-[1.47] tracking-[-0.374px]" style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #7a7a7a;">
        {{ mode === 'login' ? '欢迎回来' : '加入我们' }}
      </p>
    </div>

    <!-- Error -->
    <div v-if="errorMsg" class="mb-5 px-4 py-3 rounded-[11px] text-[14px] leading-[1.43] tracking-[-0.224px]"
      style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; background: #fff2f0; color: #cc3333; border: 1px solid #ffccc7;">
      {{ errorMsg }}
    </div>

    <!-- Form -->
    <form @submit.prevent="handleSubmit" class="space-y-4">
      <!-- Username -->
      <div>
        <label class="block text-[14px] font-semibold leading-[1.29] tracking-[-0.224px] mb-1.5"
          style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #1d1d1f;">
          用户名
        </label>
        <input
          v-model="username"
          type="text"
          autocomplete="username"
          class="w-full h-[44px] px-4 text-[17px] leading-[1.47] tracking-[-0.374px] rounded-[11px] outline-none transition-colors duration-150"
          style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; background: #f5f5f7; color: #1d1d1f; border: 1px solid #e0e0e0;"
          placeholder="请输入用户名"
        />
      </div>

      <!-- Password -->
      <div>
        <label class="block text-[14px] font-semibold leading-[1.29] tracking-[-0.224px] mb-1.5"
          style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #1d1d1f;">
          密码
        </label>
        <input
          v-model="password"
          type="password"
          autocomplete="current-password"
          class="w-full h-[44px] px-4 text-[17px] leading-[1.47] tracking-[-0.374px] rounded-[11px] outline-none transition-colors duration-150"
          style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; background: #f5f5f7; color: #1d1d1f; border: 1px solid #e0e0e0;"
          placeholder="请输入密码"
        />
        <p v-if="mode === 'register'" class="mt-1 text-[12px] leading-[1.0] tracking-[-0.12px]" style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #7a7a7a;">
          密码长度至少8位
        </p>
      </div>

      <!-- Captcha -->
      <div>
        <label class="block text-[14px] font-semibold leading-[1.29] tracking-[-0.224px] mb-1.5"
          style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #1d1d1f;">
          验证码
        </label>
        <div class="flex gap-3">
          <input
            v-model="captchaCode"
            type="text"
            maxlength="4"
            autocomplete="off"
            class="flex-1 h-[44px] px-4 text-[17px] leading-[1.47] tracking-[-0.374px] rounded-[11px] outline-none uppercase transition-colors duration-150"
            style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; background: #f5f5f7; color: #1d1d1f; border: 1px solid #e0e0e0;"
            placeholder="验证码"
          />
          <button
            type="button"
            @click="refreshCaptcha"
            :disabled="captchaLoading"
            class="h-[44px] min-w-[120px] rounded-[11px] flex items-center justify-center overflow-hidden transition-opacity duration-150"
            style="background: #fafafc; border: 1px solid #e0e0e0;"
            :style="{ opacity: captchaLoading ? 0.5 : 1 }"
          >
            <img
              v-if="captcha?.image"
              :src="captcha.image"
              alt="验证码"
              class="h-full w-full object-contain"
            />
            <span v-else class="text-[12px]" style="color: #7a7a7a;">加载中...</span>
          </button>
        </div>
      </div>

      <!-- Submit -->
      <button
        type="submit"
        class="w-full h-[44px] rounded-full text-[18px] font-light leading-[1.0] tracking-[0] text-white transition-colors duration-150 mt-2"
        style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; background: #0066cc;"
        @mouseenter="(e) => { const t = e.currentTarget as HTMLElement; t.style.background = '#0071e3'; }"
        @mouseleave="(e) => { const t = e.currentTarget as HTMLElement; t.style.background = '#0066cc'; }"
      >
        {{ mode === 'login' ? '登录' : '注册' }}
      </button>
    </form>

    <!-- Footer link -->
    <div class="mt-8 text-center">
      <NuxtLink
        v-if="mode === 'login'"
        to="/register"
        class="text-[17px] leading-[2.41] tracking-[0] transition-colors duration-150"
        style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #0066cc;"
      >
        还没有账户？立即注册
      </NuxtLink>
      <NuxtLink
        v-else
        to="/login"
        class="text-[17px] leading-[2.41] tracking-[0] transition-colors duration-150"
        style="font-family: 'SF Pro Text', system-ui, -apple-system, sans-serif; color: #0066cc;"
      >
        已有账户？前去登录
      </NuxtLink>
    </div>
  </div>
</template>
