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

const auth = useAuthStore();
const route = useRoute();
const router = useRouter();
const username = ref("");
const password = ref("");
const pending = ref(false);

async function submit(): Promise<void> {
  pending.value = true;
  await auth.login(username.value, 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" @submit.prevent="submit">
      <div class="brand-lockup centered"><span class="brand-mark">HW</span><strong>HWLAB Cloud Web</strong></div>
      <label>账号或邮箱<input v-model="username" class="input" autocomplete="username" /></label>
      <label>密码<input v-model="password" class="input" type="password" autocomplete="current-password" /></label>
      <p v-if="auth.error" class="form-error">{{ auth.error }}</p>
      <button class="btn btn-primary" type="submit" :disabled="pending">{{ pending ? "登录中" : "登录" }}</button>
      <p class="login-note">Web session 使用服务器签发的 hwlab_session cookie；浏览器不保存 user-billing token、provider Secret 或 AgentRun token。</p>
      <RouterLink class="auth-link" to="/register">创建 HWLAB 账号</RouterLink>
    </form>
  </section>
</template>
