<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";

import { useSessionStore } from "../../shared/stores/session";

const router = useRouter();
const session = useSessionStore();
const mode = ref<"login" | "register">("login");
const username = ref("");
const password = ref("");
const errorMessage = ref("");

async function submit(): Promise<void> {
  errorMessage.value = "";
  try {
    await session.authenticate(mode.value, username.value, password.value);
    await router.replace("/workspace/emotion");
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "登录失败，请稍后重试。";
  }
}
</script>

<template>
  <main class="auth-view">
    <section class="auth-panel card">
      <header class="auth-brand">
        <span class="brand-mark">复</span>
        <div><h1>小白复盘</h1><p>进入你的复盘工作台</p></div>
      </header>
      <div class="auth-tabs" role="tablist">
        <button type="button" :class="{ active: mode === 'login' }" role="tab" @click="mode = 'login'">登录</button>
        <button type="button" :class="{ active: mode === 'register' }" role="tab" @click="mode = 'register'">注册</button>
      </div>
      <form class="auth-form" @submit.prevent="submit">
        <div class="field">
          <label for="username">账号名</label>
          <input id="username" v-model="username" class="input" autocomplete="username" placeholder="请输入账号名" required />
        </div>
        <div class="field">
          <label for="password">密码</label>
          <input id="password" v-model="password" class="input" type="password" :autocomplete="mode === 'login' ? 'current-password' : 'new-password'" placeholder="请输入密码" required />
        </div>
        <p v-if="errorMessage" class="field-error" role="alert">{{ errorMessage }}</p>
        <button class="btn btn-primary auth-submit" type="submit" :disabled="session.busy">
          {{ session.busy ? "请稍候" : mode === "login" ? "登录" : "注册并登录" }}
        </button>
      </form>
      <p class="auth-risk">数据仅供复盘研究，不构成投资建议<br />股市有风险，投资需谨慎</p>
    </section>
  </main>
</template>
