<script setup lang="ts">
/**
 * @file forgot-password.vue
 * @description Forgot Password Page.
 * Allows users to request a password reset link via email.
 */

definePageMeta({
  layout: 'auth'
})

useHead({
  title: 'ลืมรหัสผ่าน - e-Learning'
})

const { errors, validate, clearFieldError } = useFormValidation()

const isLoading = ref(false)
// State to track if the request email has been sent
const forgotStep = ref<'initial' | 'success'>('initial')

const forgotForm = reactive({
  email: ''
})

const forgotRules = {
  email: { 
    rules: { 
      required: true, 
      email: true,
      custom: (val: string) => /[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null 
    }, 
    label: 'อีเมล' 
  }
}

const handleInput = (val: string | number | null) => {
  const value = String(val || '')
  forgotForm.email = value
  if (/[\u0E00-\u0E7F]/.test(value)) {
    errors.value.email = 'ห้ามใส่ภาษาไทย'
  } else {
    if (errors.value.email === 'ห้ามใส่ภาษาไทย') {
      clearFieldError('email')
    }
  }
}

const { requestPasswordReset } = useAuth()

const sendResetLink = async () => {
  if (!validate(forgotForm, forgotRules)) return
  
  isLoading.value = true
  
  const result = await requestPasswordReset(forgotForm.email)
  
  isLoading.value = false
  
  if (result.success) {
    forgotStep.value = 'success'
  } else {
    // Basic alert for now, could be improved with q-notify later
    alert(result.error || 'ไม่สามารถส่งลิงก์รีเซ็ตได้ กรุณาลองใหม่')
  }
}
</script>

<template>
  <div class="relative min-h-screen w-full flex items-center justify-center p-4 overflow-hidden bg-slate-50 transition-colors">
    <!-- ==========================================
          BACKGROUND EFFECTS (Light Mode Only)
     ========================================== -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none -z-10">
       <div class="absolute inset-0 bg-gradient-to-br from-white via-slate-50 to-blue-50/50"></div>
       <div class="absolute top-[-10%] right-[-5%] w-[500px] h-[500px] rounded-full bg-blue-100/50 blur-[100px] animate-pulse-slow"/>
       <div class="absolute bottom-[-10%] left-[-5%] w-[500px] h-[500px] rounded-full bg-indigo-100/50 blur-[100px] animate-pulse-slow" style="animation-delay: 3s;"/>
    </div>

    <!-- ==========================================
          Forgot Password Card
     ========================================== -->
    <div class="w-full max-w-[460px] relative z-10 slide-up">
      
       <!-- Logo area -->
       <div class="text-center mb-8">
          <div class="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-gradient-to-tr from-blue-600 to-indigo-600 text-white shadow-lg shadow-blue-600/20 mb-6">
             <span class="font-black text-2xl">E</span>
          </div>
          <h1 class="text-3xl font-black text-slate-900 mb-2">ลืมรหัสผ่าน?</h1>
          <p class="text-slate-600 text-base">ไม่ต้องห่วง! เราจะช่วยคุณตั้งค่ารหัสผ่านใหม่</p>
       </div>

      <div class="bg-white rounded-[2rem] p-8 md:p-10 shadow-xl shadow-slate-200/50 border border-slate-100 relative overflow-hidden">
        
       <!-- Step 1: Request Email Form -->
       <form v-if="forgotStep === 'initial'" @submit.prevent="sendResetLink" class="flex flex-col gap-6">
           
           <p class="text-slate-500 text-sm text-center px-4 leading-relaxed">
             กรุณากรอกอีเมลที่ลงทะเบียนไว้ เราจะส่งลิงก์สำหรับรีเซ็ตรหัสผ่านไปให้คุณ
           </p>

           <!-- Email Input -->
           <div>
             <label class="block text-sm font-semibold text-slate-700 mb-2 ml-1">อีเมล <span class="text-red-500">*</span></label>
             <div class="relative group">
                <div class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 transition-colors group-focus-within:text-blue-500 pointer-events-none">
                 <span class="material-icons text-xl">email</span>
               </div>
               <input
                 :value="forgotForm.email"
                  @input="(e) => handleInput((e.target as HTMLInputElement).value)"
                 type="email"
                 class="w-full h-12 pl-12 pr-4 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 placeholder-slate-400 text-base focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all font-medium"
                 placeholder="student@example.com"
                 :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.email}"
               />
             </div>
             <span v-if="errors.email" class="text-xs text-red-500 font-medium ml-1 mt-1 block slide-up-sm">{{ errors.email }}</span>
           </div>

           <button 
              type="submit" 
              :disabled="isLoading"
              class="w-full py-3.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl text-lg font-bold shadow-lg shadow-blue-600/30 transform active:scale-[0.98] transition-all duration-200 flex items-center justify-center gap-2 disabled:opacity-70 disabled:cursor-not-allowed"
            >
              <span v-if="!isLoading">ส่งลิงก์รีเซ็ต</span>
              <div v-else class="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
            </button>
        </form>

        <!-- Step 2: Success Message -->
        <div v-else class="text-center slide-up-sm py-4">
          <div class="mb-6 flex justify-center">
            <div class="w-20 h-20 bg-green-50 rounded-full flex items-center justify-center text-green-500 mb-2 border border-green-100 shadow-sm">
               <span class="material-icons text-4xl">check_circle</span>
            </div>
          </div>
          <h3 class="text-xl font-bold text-slate-900 mb-2">ส่งลิงก์เรียบร้อยแล้ว!</h3>
          <p class="text-slate-500 text-sm leading-relaxed px-2 mb-8">
            กรุณาตรวจสอบกล่องจดหมายของคุณ<br>เพื่อดำเนินการตั้งค่ารหัสผ่านใหม่
          </p>
          
          <button 
             @click="forgotStep = 'initial'"
             class="text-sm font-bold text-blue-600 hover:text-blue-700 transition-colors"
          >
             ส่งอีกครั้ง?
          </button>
        </div>

      </div>

      <!-- Back Link -->
       <div class="mt-8 text-center text-slate-500">
           <NuxtLink to="/auth/login" class="inline-flex items-center gap-2 text-sm font-medium hover:text-slate-800 transition-colors group px-4 py-2 rounded-lg hover:bg-white/50">
             <span class="group-hover:-translate-x-1 transition-transform">←</span> กลับไปหน้าเข้าสู่ระบบ
           </NuxtLink>
        </div>
    </div>
  </div>
</template>

<style scoped>
/* Animations */
@keyframes pulse-slow {
  0%, 100% { opacity: 0.3; transform: scale(1); }
  50% { opacity: 0.5; transform: scale(1.15); }
}

.animate-pulse-slow {
  animation: pulse-slow 8s ease-in-out infinite;
}

@keyframes slide-up {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.slide-up {
  animation: slide-up 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}

.slide-up-sm {
  animation: slide-up 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
</style>
