<script setup>
import { ref, computed } from "vue";
import { login } from "../api";
import { t } from "../i18n";

const emit = defineEmits(["authenticated"]);

const email = ref("");
const password = ref("");
const error = ref("");
const busy = ref(false);

const canSubmit = computed(() => email.value.trim() !== "" && password.value !== "" && !busy.value);

async function submit() {
  if (!canSubmit.value) return;
  error.value = "";
  busy.value = true;
  try {
    const who = await login(email.value.trim(), password.value);
    // Any DriverVault account can authenticate; the console itself is only
    // useful to a manager, and the server enforces that on every call anyway.
    emit("authenticated", who);
  } catch (e) {
    // 400/404 from PocketBase both mean "bad credentials" — don't leak which.
    error.value =
      e.status === 400 || e.status === 404
        ? t("login.invalid")
        : e.message || t("login.failed");
    password.value = "";
  } finally {
    busy.value = false;
  }
}
</script>

<template>
  <div class="mx-auto flex w-full max-w-sm flex-col gap-5 pt-24">
    <div class="dh-card p-6">
      <h1 class="text-lg font-bold tracking-[-0.02em] text-strong">{{ t("login.title") }}</h1>
      <p class="mt-1 mb-5 text-sm text-body">
        {{ t("login.subtitle") }}
      </p>

      <form class="flex flex-col gap-4" @submit.prevent="submit">
        <div>
          <label class="dh-label" for="login-email">{{ t("login.email") }}</label>
          <input
            id="login-email"
            v-model="email"
            class="dh-input"
            type="email"
            autocomplete="username"
            autofocus
            placeholder="you@example.com"
          />
        </div>
        <div>
          <label class="dh-label" for="login-password">{{ t("login.password") }}</label>
          <input
            id="login-password"
            v-model="password"
            class="dh-input"
            type="password"
            autocomplete="current-password"
            placeholder="••••••••"
          />
        </div>

        <p v-if="error" class="rounded-control bg-danger-soft px-3 py-2 text-xs text-danger">
          {{ error }}
        </p>

        <button class="dh-btn w-full" type="submit" :disabled="!canSubmit">
          {{ busy ? t("login.submitting") : t("login.submit") }}
        </button>
      </form>
    </div>

    <p class="eyebrow text-center">
      {{ t("login.authNote") }}
    </p>
  </div>
</template>
