<script setup lang="ts">
const email = ref("");
const error = ref("");
const success = ref("");
const pending = ref(false);

const handleSubmit = async () => {
  error.value = "";
  success.value = "";
  pending.value = true;

  try {
    const result = await useApi<{ message: string }>("/auth/forgot-password", {
      method: "POST",
      body: { email: email.value }
    });

    success.value = result.message;
  } catch (submitError) {
    error.value = submitError instanceof Error ? submitError.message : "Не удалось отправить письмо";
  } finally {
    pending.value = false;
  }
};
</script>

<template>
  <section class="mx-auto grid min-h-[calc(100vh-12rem)] w-full items-center gap-8 md:max-w-6xl md:grid-cols-[minmax(0,1.1fr)_minmax(22rem,28rem)] md:[min-height:calc(100vh-10rem)]">
    <div class="grid max-w-lg gap-3">
      <p class="m-0 text-xs font-semibold uppercase tracking-[0.18em] text-(--muted)">Alpinbet</p>
      <h1 class="m-0 text-4xl font-semibold leading-tight">Восстановление пароля</h1>
      <p class="m-0 text-base leading-7 text-(--muted)">
        Укажите email аккаунта. Мы отправим ссылку, по которой можно задать новый пароль.
      </p>
    </div>

    <form
      class="grid w-full max-w-md gap-4 rounded-[28px] border p-4"
      :style="{ borderColor: 'var(--border)', backgroundColor: 'var(--surface-strong)' }"
      @submit.prevent="handleSubmit"
    >
      <p class="m-0 text-xs font-semibold uppercase tracking-[0.18em] text-(--muted)">Запрос письма</p>

      <label class="grid gap-1">
        <span>Email</span>
        <input v-model="email" type="email" autocomplete="email" />
      </label>

      <p
        v-if="error"
        class="rounded-2xl p-4 text-sm whitespace-pre-line"
        :style="{ backgroundColor: 'var(--danger-bg)', color: 'var(--danger-text)' }"
      >
        {{ error }}
      </p>

      <p
        v-if="success"
        class="rounded-2xl p-4 text-sm"
        :style="{ backgroundColor: 'var(--success-bg)', color: 'var(--success-text)' }"
      >
        {{ success }}
      </p>

      <button type="submit" :disabled="pending">
        {{ pending ? "Отправляем..." : "Отправить ссылку" }}
      </button>

      <p class="m-0 text-(--muted)">
        Вспомнили пароль?
        <NuxtLink class="text-(--accent-strong)" to="/login">Вернуться ко входу</NuxtLink>
      </p>
    </form>
  </section>
</template>
