<script setup lang="ts">
/**
 * @file register.vue
 * @description User Registration Page.
 * Features a multi-step style form (though currently single view) for creating a new account.
 * Updated to match the Dark Theme design.
 */

definePageMeta({
  layout: "auth",
  middleware: "auth",
});

useHead({
  title: "สมัครสมาชิก - e-Learning",
});

const router = useRouter();
const { register } = useAuth();
const $q = useQuasar();
const { errors, validate, clearFieldError } = useFormValidation();

const isLoading = ref(false);
const showPassword = ref(false);
const showConfirmPassword = ref(false);

const registerForm = reactive({
  prefix: "นาย",
  username: "",
  firstName: "",
  lastName: "",
  phone: "",
  email: "",
  password: "",
  confirmPassword: "",
});

const registerRules = {
  username: { 
    rules: { 
      required: true, 
      minLength: 4,
      custom: (val: string) => /[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null
    }, 
    label: "ชื่อผู้ใช้" 
  },
  firstName: { 
    rules: { 
      required: true, 
      minLength: 2,
      custom: (val: string) => /\d/.test(val) ? 'ห้ามใส่ตัวเลข' : null
    }, 
    label: "ชื่อ" 
  },
  lastName: { 
    rules: { 
      required: true, 
      minLength: 2,
      custom: (val: string) => /\d/.test(val) ? 'ห้ามใส่ตัวเลข' : null
    }, 
    label: "นามสกุล" 
  },
  phone: {
    rules: { 
      required: true, 
      pattern: /^0[0-9]{8,9}$/,
      custom: (val: string) => /\D/.test(val) ? 'กรุณากรอกเฉพาะตัวเลข' : null
    },
    label: "เบอร์โทรศัพท์",
  },
  email: { 
    rules: { 
      required: true, 
      email: true,
      custom: (val: string) => /[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null 
    }, 
    label: "อีเมล" 
  },
  password: { 
    rules: { 
      required: true, 
      minLength: 8,
      custom: (val: string) => /[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null 
    }, 
    label: "รหัสผ่าน" 
  },
  confirmPassword: {
    rules: { required: true, match: "password" },
    label: "ยืนยันรหัสผ่าน",
  },
};

const prefixOptions = ['นาย', 'นาง', 'นางสาว']

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

const onPhoneInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.phone = value;
  if (/\D/.test(value)) {
    errors.value.phone = 'กรุณากรอกเฉพาะตัวเลข';
  } else {
    if (errors.value.phone === 'กรุณากรอกเฉพาะตัวเลข') clearFieldError('phone');
  }
};

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

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

const onFirstNameInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.firstName = value;
  if (/\d/.test(value)) {
    errors.value.firstName = 'ห้ามใส่ตัวเลข';
  } else {
    if (errors.value.firstName === 'ห้ามใส่ตัวเลข') clearFieldError('firstName');
  }
};

const onLastNameInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.lastName = value;
  if (/\d/.test(value)) {
    errors.value.lastName = 'ห้ามใส่ตัวเลข';
  } else {
    if (errors.value.lastName === 'ห้ามใส่ตัวเลข') clearFieldError('lastName');
  }
};

const handleRegister = async () => {
  if (!validate(registerForm, registerRules)) return;

  isLoading.value = true;

  const prefixMap: Record<string, string> = {
    'นาย': 'Mr.',
    'นาง': 'Mrs.',
    'นางสาว': 'Ms.'
  };

  const payload = {
    username: registerForm.username,
    email: registerForm.email,
    password: registerForm.password,
    first_name: registerForm.firstName,
    last_name: registerForm.lastName,
    prefix: {
        th: registerForm.prefix,
        en: prefixMap[registerForm.prefix] || 'Mr.'
    },
    phone: registerForm.phone
  };

  const result = await register(payload);

  isLoading.value = false;

  if (result.success) {
      $q.notify({
          type: 'positive',
          message: 'สมัครสมาชิกสำเร็จ! กรุณาเข้าสู่ระบบ',
          position: 'top',
          timeout: 4000
      });
      router.push("/auth/login");
  } else {
      $q.notify({
          type: 'negative',
          message: result.error || 'การลงทะเบียนล้มเหลว',
          position: 'top',
          timeout: 3000,
          actions: [{ icon: 'close', color: 'white' }]
      });
  }
};
</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>

    <!-- ==========================================
          REGISTER CARD
     ========================================== -->
    <div class="w-full max-w-[700px] 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 @submit.prevent="handleRegister" class="flex flex-col gap-5">
          
          <!-- Username & Email Row -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
            <!-- Username -->
            <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">person</span>
                </div>
                <input
                  :value="registerForm.username"
                  @input="(e) => onUsernameInput((e.target as HTMLInputElement).value)"
                  type="text"
                  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="username"
                  :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.username}"
                />
              </div>
              <span v-if="errors.username" class="text-xs text-red-500 font-medium ml-1 mt-1 block slide-up-sm">{{ errors.username }}</span>
            </div>

            <!-- Email -->
            <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="registerForm.email"
                  @input="(e) => onEmailInput((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>
          </div>

          <!-- Name Section -->
          <div class="grid grid-cols-12 gap-4">
             <!-- Prefix -->
             <div class="col-span-12 md:col-span-3">
               <label class="block text-sm font-semibold text-slate-700 mb-2 ml-1">คำนำหน้า</label>
               <div class="relative">
                 <select 
                   v-model="registerForm.prefix"
                   class="w-full h-12 pl-4 pr-8 rounded-xl bg-slate-50 border border-slate-200 text-slate-900 text-base focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all font-medium appearance-none cursor-pointer"
                 >
                   <option v-for="opt in prefixOptions" :key="opt" :value="opt">{{ opt }}</option>
                 </select>
                 <div class="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400">
                    <span class="material-icons">expand_more</span>
                 </div>
               </div>
             </div>

             <!-- First Name -->
             <div class="col-span-12 md:col-span-4">
               <label class="block text-sm font-semibold text-slate-700 mb-2 ml-1">ชื่อ <span class="text-red-500">*</span></label>
               <input
                  :value="registerForm.firstName"
                  @input="(e) => onFirstNameInput((e.target as HTMLInputElement).value)"
                  type="text"
                  class="w-full h-12 px-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"
                  :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.firstName}"
                />
                <span v-if="errors.firstName" class="text-xs text-red-500 font-medium ml-1 mt-1 block slide-up-sm">{{ errors.firstName }}</span>
             </div>

             <!-- Last Name -->
             <div class="col-span-12 md:col-span-5">
               <label class="block text-sm font-semibold text-slate-700 mb-2 ml-1">นามสกุล <span class="text-red-500">*</span></label>
               <input
                  :value="registerForm.lastName"
                  @input="(e) => onLastNameInput((e.target as HTMLInputElement).value)"
                  type="text"
                  class="w-full h-12 px-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"
                  :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.lastName}"
                />
                <span v-if="errors.lastName" class="text-xs text-red-500 font-medium ml-1 mt-1 block slide-up-sm">{{ errors.lastName }}</span>
             </div>
          </div>

          <!-- Phone -->
          <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">phone</span>
              </div>
              <input
                :value="registerForm.phone"
                @input="(e) => onPhoneInput((e.target as HTMLInputElement).value)"
                type="tel"
                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"
                :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.phone}"
              />
            </div>
            <span v-if="errors.phone" class="text-xs text-red-500 font-medium ml-1 mt-1 block slide-up-sm">{{ errors.phone }}</span>
          </div>

          <!-- Password Row -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
            <!-- Password -->
            <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">lock</span>
                </div>
                <input
                  :value="registerForm.password"
                  @input="(e) => onPasswordInput((e.target as HTMLInputElement).value)"
                  :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"
                  :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.password}"
                />
                <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>

            <!-- Confirm Password -->
            <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">lock_clock</span>
                </div>
                <input
                  v-model="registerForm.confirmPassword"
                  @input="clearFieldError('confirmPassword')"
                  :type="showConfirmPassword ? '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"
                 
                  :class="{'border-red-500 focus:ring-red-500/20 focus:border-red-500': errors.confirmPassword}"
                />
                <button 
                  type="button" 
                  @click="showConfirmPassword = !showConfirmPassword"
                  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">{{ showConfirmPassword ? 'visibility_off' : 'visibility' }}</span>
                </button>
              </div>
              <span v-if="errors.confirmPassword" class="text-xs text-red-500 font-medium ml-1 mt-1 block slide-up-sm">{{ errors.confirmPassword }}</span>
            </div>
          </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>

          <!-- Divider -->
          <div class="my-4 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>

          <!-- Login Link -->
          <div class="text-center">
              <p class="text-slate-600 text-sm">
                 มีบัญชีอยู่แล้ว? 
                 <NuxtLink to="/auth/login" class="font-bold text-blue-600 hover:text-blue-700 transition-colors ml-1">
                   เข้าสู่ระบบ
                 </NuxtLink>
              </p>
          </div>

        </form>

      </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>
