<script setup lang="ts">
import { ref } from "vue";
import { apiPost, apiErrorMessage } from "@/api/client";
import AppLogo from "@/components/AppLogo.vue";

const email = ref("");
const error = ref("");
const submitted = ref(false);
const submitting = ref(false);

async function handleSubmit() {
  error.value = "";
  submitting.value = true;
  try {
    await apiPost("/api/auth/forgot-password", { email: email.value });
    submitted.value = true;
  } catch (e: unknown) {
    error.value = apiErrorMessage(e, "Something went wrong");
  } finally {
    submitting.value = false;
  }
}
</script>

<template>
  <main class="auth-page">
    <div class="auth-card">
      <div class="auth-brand"><AppLogo :size="32" /><h1>Reset Password</h1></div>

      <template v-if="!submitted">
        <p class="auth-hint">
          Enter the email address associated with your account and we'll send you a link to reset your password.
        </p>
        <form @submit.prevent="handleSubmit">
          <div class="field">
            <label for="email">Email</label>
            <input
              id="email"
              v-model="email"
              type="email"
              autocomplete="email"
              required
              class="input"
            />
          </div>
          <p v-if="error" class="error-msg">{{ error }}</p>
          <button type="submit" class="btn-primary btn-block" :disabled="submitting">
            {{ submitting ? "Sending..." : "Send Reset Link" }}
          </button>
        </form>
      </template>

      <div v-else class="auth-note">
        <p>If an account exists with that email address, you will receive a password reset link shortly.</p>
        <p>Check your email and follow the instructions to reset your password.</p>
      </div>

      <p class="auth-footer">
        <router-link to="/login">Back to Sign In</router-link>
      </p>
    </div>
  </main>
</template>

<style src="@/assets/auth-shared.css" />
