<template>
  <div class="layout">
    <div class="view">
      <form class="forgot-form" @submit.prevent="submitForm" novalidate>
        <h2>Reset your password</h2>

        <div class="form-group">
          <label for="email">Email address</label>
          <input
            id="email"
            type="email"
            autocomplete="username"
            autofocus
            v-model="email"
            :class="{ 'input-error': submitAttempted && !isFormValid }"
            required
          />
          <small v-if="submitAttempted && !email" class="error-message" aria-live="polite">
            Email is required.
          </small>
          <small
            v-else-if="submitAttempted && !isFormValid"
            class="error-message"
            aria-live="polite"
          >
            Please enter a valid email address.
          </small>
        </div>

        <div v-if="errorMsg" class="error-message" style="margin-bottom: 1rem" aria-live="polite">
          {{ errorMsg }}
        </div>
        <div
          v-if="successMsg"
          class="success-message"
          style="margin-bottom: 1rem"
          aria-live="polite"
        >
          {{ successMsg }}
        </div>

        <div class="form-group actions" style="margin-top: 0.4rem">
          <button type="submit" class="btn btn-primary" :disabled="loading || !isFormValid">
            {{ loading ? 'Sending…' : 'Send Reset Link' }}
          </button>
        </div>

        <p
          style="
            text-align: center;
            margin-top: 0.8rem;
            color: var(--sub-message-color, #6b7280);
            font-size: 0.95rem;
          "
        >
          Remembered your password?
          <button
            type="button"
            class="btn-link"
            @click="goToLogin"
            style="
              background: none;
              border: none;
              color: var(--btn-primary);
              font-weight: 600;
              cursor: pointer;
              padding: 0;
              margin-left: 6px;
            "
          >
            Sign in
          </button>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { isEmailValid } from '@/common/api'
import '@/assets/styles.css'

const router = useRouter()

const email = ref('')
const submitAttempted = ref(false)
const loading = ref(false)
const errorMsg = ref('')
const successMsg = ref('')

const isEmailValidRef = computed(() => isEmailValid(email.value))

// Add computed for form validity: email must be non-empty and valid
const isFormValid = computed(() => email.value.trim() !== '' && isEmailValidRef.value)

async function submitForm() {
  submitAttempted.value = true
  errorMsg.value = ''
  successMsg.value = ''

  if (!isFormValid.value) return
  loading.value = true
  try {
    const res = await fetch('/api/auth/request-password-reset', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: email.value.trim() }),
    })
    if (!res.ok) {
      let msg = 'Could not send reset email.'
      try {
        const data = await res.json()
        if (data && (data.error || data.message)) {
          msg = data.error || data.message
        }
      } catch {
        try {
          const text = await res.text()
          if (text) msg = text
        } catch {}
      }
      errorMsg.value = msg
      return
    }
    successMsg.value =
      'If this email is registered, you will receive a password reset link shortly.'
    email.value = ''
    submitAttempted.value = false
  } catch {
    errorMsg.value = 'Network error. Please try again.'
  } finally {
    loading.value = false
  }
}

async function goToLogin() {
  await router.push({ name: 'Login' }).catch(() => (window.location.href = '/auth/login'))
}
</script>

<style scoped>
.view {
  max-width: 420px;
  margin: 0 auto;
  background: var(--edit-view-bg, #fff);
  border-radius: 14px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
  padding: 2.2rem 2.2rem 1.5rem 2.2rem;
}
.view h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: var(--form-heading);
}

.forgot-form {
  background: transparent;
  box-shadow: none;
  padding: 0;
  border: none;
}

/* reuse edit-forms form-group styles */
.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  color: var(--form-label, #444);
  font-weight: 600;
}
.form-group input,
.form-group input[type='email'],
.form-group input[type='password'] {
  display: block;
  width: 100%;
  margin-top: 0.4rem;
  padding: 0.6rem;
  border-radius: 7px;
  border: 1px solid var(--form-input-border, #e6e6e6);
  font-size: 1rem;
  background: var(--form-input-bg, #fff);
  box-sizing: border-box;
}

@media (max-width: 520px) {
  .forgot-form {
    padding: 1rem;
    border-radius: 10px;
  }
}

.actions {
  display: flex;
  gap: 3rem;
  justify-content: center;
  margin-top: 0.5rem;
  margin-bottom: 0.4rem;
}
.actions .btn {
  padding: 1rem 2.2rem;
  font-weight: 700;
  font-size: 1.25rem;
  min-width: 120px;
}
</style>
