<script setup lang="ts">
/**
 * @file login.vue
 * @description หน้าเข้าสู่ระบบ (Login Page)
 * รองรับการเข้าสู่ระบบด้วย Email/Password
 * NOTE: ไม่เปลี่ยนสี และไม่เปลี่ยนการเรียก API login
 */

definePageMeta({
  layout: 'auth',
  middleware: 'auth'
})

useHead({
  title: 'เข้าสู่ระบบ - e-Learning'
})

const router = useRouter()
const { login, user } = useAuth()
const { errors, validate, clearFieldError } = useFormValidation()

const isLoading = ref(false)
const rememberMe = ref(false)
const showPassword = ref(false)

// Form data model
const loginForm = reactive({
  email: '',
  password: ''
})

type LoginField = keyof typeof loginForm

// Validation rules definition
// กำหนดกฎการตรวจสอบข้อมูล (Validation Rules)
const loginRules = {
  email: {
    rules: {
      required: true,
      email: true,
      custom: (val: string) => (/[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null)
    },
    label: 'อีเมล',
    messages: {
      required: 'กรุณากรอกอีเมลของคุณ',
      email: 'กรุณากรอกอีเมลให้ถูกต้อง (you@example.com)'
    }
  },
  password: {
    rules: {
      required: true,
      minLength: 8,
      custom: (val: string) => (/[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null)
    },
    label: 'รหัสผ่าน',
    messages: {
      required: 'กรุณากรอกรหัสผ่าน',
      minLength: 'กรุณากรอกรหัสผ่าน (อย่างน้อย 8 ตัวอักษร)'
    }
  }
} as const

/**
 * จัดการเมื่อมีการพิมพ์ข้อมูล (Input Handler)
 * - ลบ error เมื่อเริ่มพิมพ์ใหม่
 * - ตรวจสอบภาษาไทยแบบ real-time
 */
const handleInput = (field: LoginField, value: string) => {
  loginForm[field] = value

  if (/[\u0E00-\u0E7F]/.test(value)) {
    errors.value[field] = 'ห้ามใส่ภาษาไทย'
    return
  }

  if (errors.value[field] === 'ห้ามใส่ภาษาไทย') {
    clearFieldError(field)
  }
}

/**
 * ฟังก์ชันตรวจสอบความถูกต้องของฟอร์มและเรียก API login
 */
const handleLogin = async () => {
  if (!validate(loginForm, loginRules)) return

  isLoading.value = true

  // ✅ ไม่เปลี่ยน API: ยังคงเรียก login({ email, password }) ตามเดิม
  const result = await login({
    email: loginForm.email,
    password: loginForm.password
  })

  isLoading.value = false

  if (result.success) {
    // จดจำฉัน: บันทึกอีเมลลงเครื่องเฉพาะตอนติ๊กถูกเท่านั้น
    if (rememberMe.value) {
      localStorage.setItem('remembered_email', loginForm.email)
    } else {
      // ถ้าไม่ได้ติ๊ก ให้ลบทิ้งเพื่อความปลอดภัย
      localStorage.removeItem('remembered_email')
    }

    router.push('/dashboard')
    return
  }


  // Show error on specific fields
  // Show generic error for security (or specific if role mismatch)
  if (result.error === 'Email ไม่ถูกต้อง') {
     errors.value.email = result.error // Role mismatch case
  } else {
     // Generic login failure (401, 404, etc.)
     const msg = 'กรุณาเช็ค Email หรือ รหัสผ่านใหม่อีกครั้ง'
     errors.value.email = msg
     errors.value.password = msg
  }
}



onMounted(() => {
  const savedEmail = localStorage.getItem('remembered_email')
  if (savedEmail) {
    loginForm.email = savedEmail
    rememberMe.value = true
  }
})
</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>

    <!-- ==========================================
          LOGIN CARD
     ========================================== -->
    <div class="w-full max-w-[460px] relative z-10 slide-up">
      
       <!-- Header / Logo -->
       <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">
        
        <!-- Form -->
        <form @submit.prevent="handleLogin" class="flex flex-col gap-5">
          
          <!-- Email Input -->
          <div>
            <label class="block text-sm font-semibold text-slate-700 mb-2 ml-1">อีเมล</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
                v-model="loginForm.email"
                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=""
                :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.email}"
                @input="(e) => handleInput('email', (e.target as HTMLInputElement).value)"
              />
            </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>

          <!-- Password Input -->
          <div>
            <label class="block text-sm font-semibold text-slate-700 mb-2 ml-1">รหัสผ่าน</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">lock</span>
              </div>
              <input
                v-model="loginForm.password"
                :type="showPassword ? 'text' : 'password'"
                class="w-full h-12 pl-12 pr-12 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=""
                :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.password}"
                @input="(e) => handleInput('password', (e.target as HTMLInputElement).value)"
              />
              <button 
                type="button" 
                @click="showPassword = !showPassword"
                class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition-colors focus:outline-none flex items-center"
              >
                 <span class="material-icons text-lg">{{ showPassword ? 'visibility_off' : 'visibility' }}</span>
              </button>
            </div>
            <span v-if="errors.password" class="text-xs text-red-500 font-medium ml-1 mt-1 block slide-up-sm">{{ errors.password }}</span>
          </div>

          <!-- Options -->
          <div class="flex items-center justify-between mt-1">
             <label class="flex items-center gap-2 cursor-pointer group select-none">
               <div class="relative flex items-center">
                 <input type="checkbox" v-model="rememberMe" class="peer sr-only">
                 <div class="w-5 h-5 border-2 border-slate-300 rounded-md peer-checked:bg-blue-600 peer-checked:border-blue-600 transition-all bg-white flex items-center justify-center">
                    <svg class="w-3.5 h-3.5 text-white opacity-0 peer-checked:opacity-100 transition-opacity" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                    </svg>
                 </div>
               </div>
               <span class="text-sm text-slate-600 font-medium group-hover:text-slate-800 transition-colors">จดจำฉัน</span>
             </label>
             <NuxtLink to="/auth/forgot-password" class="text-sm font-semibold text-blue-600 hover:text-blue-700 transition-colors">
                ลืมรหัสผ่าน?
             </NuxtLink>
          </div>

          <!-- Submit Button -->
          <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 mt-4"
          >
            <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>

        <!-- Divider -->
        <div class="my-8 flex items-center gap-4">
           <div class="h-px bg-slate-200 flex-1"></div>
           <span class="text-slate-400 text-xs font-medium uppercase tracking-wider">หรือ</span>
           <div class="h-px bg-slate-200 flex-1"></div>
        </div>

        <!-- Register Link -->
        <div class="text-center">
            <p class="text-slate-600 text-sm">
               ยังไม่มีบัญชีสมาชิก? 
               <NuxtLink to="/auth/register" class="font-bold text-blue-600 hover:text-blue-700 transition-colors ml-1">
                 สมัครสมาชิกฟรี
               </NuxtLink>
            </p>
        </div>

      </div>

      <!-- Back Link -->
       <div class="mt-8 text-center text-slate-500">
           <NuxtLink to="/" 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>
