<template>
  <div class="reset">
    <h2 class="reset__title">Сброс пароля</h2>
    <p class="small-text reset__subtitle">Введите email для сброса пароля</p>

    <form @submit.prevent="handleReset" class="reset__form">
      <div class="form-group">
        <label class="form-label">Email</label>
        <input
          v-model="email"
          type="email"
          class="form-input"
          :class="{ 'form-input--error': errors.email }"
          placeholder="example@mail.com"
          required
        />
        <span v-if="errors.email" class="form-error">{{ errors.email }}</span>
      </div>

      <button
        type="submit"
        class="btn btn--primary btn--lg btn--full"
        :disabled="loading"
      >
        {{ loading ? 'Отправка...' : 'Отправить' }}
      </button>

      <p v-if="success" class="reset__success">
        Инструкция по сбросу пароля отправлена на ваш email
      </p>
      <p v-if="apiError" class="reset__error">{{ apiError }}</p>
    </form>

    <p class="reset__back">
      <NuxtLink to="/auth/login">Вернуться ко входу</NuxtLink>
    </p>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'auth',
  title: 'Сброс пароля',
  middleware: 'guest',
})

const email = ref('')
const errors = reactive({ email: '' })
const apiError = ref('')
const success = ref(false)
const loading = ref(false)

async function handleReset() {
  errors.email = ''
  apiError.value = ''
  success.value = false

  if (!email.value) {
    errors.email = 'Введите email'
    return
  }

  loading.value = true
  try {
    const api = useApi()
    await api.post('/auth/reset-password', { email: email.value })
    success.value = true
  } catch (e: any) {
    apiError.value = e.message || 'Ошибка отправки'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.reset__title {
  text-align: center;
  margin-bottom: 8px;
}

.reset__subtitle {
  text-align: center;
  margin-bottom: 24px;
}

.reset__form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.reset__error {
  font-family: var(--font-body);
  font-size: var(--font-size-small);
  color: var(--color-red);
  text-align: center;
  padding: 8px;
  background: var(--color-bg-error);
  border-radius: var(--radius-sm);
}

.reset__success {
  font-family: var(--font-body);
  font-size: var(--font-size-small);
  color: var(--color-green-accent);
  text-align: center;
  padding: 8px;
  background: var(--color-bg-success);
  border-radius: var(--radius-sm);
}

.reset__back {
  text-align: center;
  margin-top: 24px;
}

.reset__back a {
  font-family: var(--font-body);
  font-size: var(--font-size-small);
  color: var(--color-primary);
}

.reset__back a:hover {
  text-decoration: underline;
}
</style>
