<script setup lang="ts">
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";

const auth = useAuthStore();
const route = useRoute();
const router = useRouter();

const email = ref("");
const username = ref("");
const displayName = ref("");
const password = ref("");
const confirmPassword = ref("");
const pending = ref(false);
const localError = ref<string | null>(null);

const canSubmit = computed(() => email.value.trim() && username.value.trim() && password.value.length >= 10 && password.value === confirmPassword.value);

async function submit(): Promise<void> {
  localError.value = null;
  if (password.value.length < 10) {
    localError.value = "密码至少需要 10 个字符。";
    return;
  }
  if (password.value !== confirmPassword.value) {
    localError.value = "两次输入的密码不一致。";
    return;
  }
  pending.value = true;
  await auth.register({ email: email.value, username: username.value, displayName: displayName.value, password: password.value });
  pending.value = false;
  if (auth.isAuthenticated) await router.replace(nextPath());
}

function nextPath(): string {
  const redirect = route.query.redirect;
  return typeof redirect === "string" && redirect.startsWith("/") && !redirect.startsWith("//") ? redirect : "/workbench";
}
</script>

<template>
  <section class="login-shell">
    <form class="login-card register-card" @submit.prevent="submit">
      <div class="brand-lockup centered"><span class="brand-mark">HW</span><strong>注册 HWLAB Cloud Web</strong></div>
      <label>邮箱<input v-model="email" class="input" type="email" autocomplete="email" /></label>
      <label>用户名<input v-model="username" class="input" autocomplete="username" /></label>
      <label>显示名<input v-model="displayName" class="input" autocomplete="name" /></label>
      <label>密码<input v-model="password" class="input" type="password" autocomplete="new-password" /></label>
      <label>确认密码<input v-model="confirmPassword" class="input" type="password" autocomplete="new-password" /></label>
      <p v-if="localError || auth.error" class="form-error">{{ localError || auth.error }}</p>
      <button class="btn btn-primary" type="submit" :disabled="pending || !canSubmit">{{ pending ? "注册中" : "注册并登录" }}</button>
      <p class="login-note">注册账号由 hwlab-user-billing 写入 PK01 PostgreSQL；浏览器仅持有 HttpOnly Web session cookie。</p>
      <RouterLink class="auth-link" to="/login">已有账号，返回登录</RouterLink>
    </form>
  </section>
</template>
