<script setup lang="ts">
/**
 * @file my-courses.vue
 * @description หน้าคอร์สของฉัน (My Enrolled Courses)
 */

// 1. นำเข้าระบบและกำหนด MetaData
definePageMeta({
  layout: 'default',
  middleware: 'auth'
})

const { t, locale } = useI18n()
const route = useRoute()
const quasar = useQuasar()
useHead({ title: `${t('sidebar.myCourses') || 'My Courses'} - e-Learning Platform` })

// 2. เรียกใช้งาน Composables
const { fetchEnrolledCourses, getCertificate, generateCertificate, fetchCourses } = useCourse()
const { fetchCategories } = useCategory()

// 3. กำหนดสถานะ (State)
const enrolledCourses = ref<any[]>([])
const allCategories = ref<any[]>([])
const isLoading = ref(false)
const searchQuery = ref('')
const activeCategory = ref<number | 'all'>('all')
const viewMode = ref<'grid' | 'list'>('grid')
const showEnrollModal = ref(false)

// 4. ฟังก์ชันเสริม (Helper Functions)
const getLocalizedText = (text: any) => {
  if (!text) return ''
  if (typeof text === 'string') return text
  const currentLocale = locale.value as 'th' | 'en'
  return text[currentLocale] || text.th || text.en || ''
}

const getCategoryIcon = (name: any) => {
   const text = getLocalizedText(name) || ''
   if (text.includes('เว็บ') || text.includes('Web') || text.includes('โปรแกรม') || text.includes('Program') || text.includes('โค้ด')) return 'code'
   if (text.includes('ออกแบบ') || text.includes('Design') || text.includes('UI')) return 'palette'
   if (text.includes('ธุรกิจ') || text.includes('Business') || text.includes('การตลาด') || text.includes('Market')) return 'trending_up'
   if (text.includes('ข้อมูล') || text.includes('Data') || text.includes('วิเคราะ') || text.includes('Sci')) return 'storage'
   return 'category'
}

// 5. การจัดการโหลดข้อมูล (Data Loading)
const loadData = async () => {
    isLoading.value = true
    try {
        const [catRes, courseRes, allCoursesRes] = await Promise.all([
            fetchCategories(),
            fetchEnrolledCourses({}),
            fetchCourses({ limit: 1000 })
        ])

        if (catRes.success) allCategories.value = catRes.data || []
        const catMap = new Map()
        allCategories.value.forEach(c => catMap.set(c.id, c))
        
        const catIdMap = new Map()
        if (allCoursesRes && allCoursesRes.success && allCoursesRes.data) {
            allCoursesRes.data.forEach((c: any) => catIdMap.set(c.id, c.category_id))
        }

        if (courseRes.success && courseRes.data) {
            enrolledCourses.value = courseRes.data.map(item => {
               const mappedCategoryId = catIdMap.get(item.course.id) || item.course.category_id
               const cat = catMap.get(mappedCategoryId)
               
               // ตรรกะการหาชื่อผู้สอน (Instructor Name Logic)
               let instName = t('course.instructor')
               let user = null;
               if (item.course.instructors && item.course.instructors.length > 0) {
                   const primary = item.course.instructors.find((i: any) => i.is_primary);
                   user = primary ? primary.user : item.course.instructors[0].user;
               } else {
                   user = item.course.creator || (item.course as any).instructor;
               }
               
               if (user?.profile?.first_name) {
                   instName = `${user.profile.first_name} ${user.profile.last_name || ''}`.trim();
               } else if (user?.first_name) {
                   instName = `${user.first_name} ${user.last_name || ''}`.trim();
               } else if (user?.username) {
                   instName = user.username;
               }

               return {
                 id: item.course_id,
                 enrollment_id: item.id,
                 title: item.course.title,
                 progress: item.progress_percentage || 0,
                 lessons: item.course.total_lessons || 10,
                 completed: item.status === 'COMPLETED',
                 thumbnail_url: item.course.thumbnail_url,
                 category_id: mappedCategoryId,
                 category_name: cat ? getLocalizedText(cat.name) : '',
                 instructor_name: instName
               }
            })
        }
    } catch (err) {
        console.error("Failed to load enrolled courses", err)
    } finally {
        isLoading.value = false
    }
}

// 6. ตัวแปร Computed (Computed Properties)
const uniqueCategories = computed(() => {
    const ids = Array.from(new Set(enrolledCourses.value.map(c => c.category_id)))
    return allCategories.value.filter(c => ids.includes(c.id))
})

const inProgressCourses = computed(() => {
    return enrolledCourses.value.filter(c => !c.completed && c.progress >= 0 && c.progress < 100).reverse()
})

const filteredEnrolledCourses = computed(() => {
    let result = enrolledCourses.value
    if (activeCategory.value !== 'all') {
        result = result.filter(c => c.category_id === activeCategory.value)
    }
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(c => getLocalizedText(c.title).toLowerCase().includes(query))
    }
    return result
})

const validCourseId = computed(() => {
    const cid = route.query.course_id
    if (!cid || cid === 'undefined' || cid === 'null' || cid === 'NaN') return null
    return cid
})

// 7. ฟังก์ชันการทำงาน (Actions)
const handleDownloadCertificate = async (courseId: number) => {
    try {
        quasar.notify({ message: t('common.loading') + '...', color: 'info' })
        const genRes = await generateCertificate(courseId)
        if (genRes.success && genRes.data?.download_url) {
            window.open(genRes.data.download_url, '_blank')
        } else {
            throw new Error(genRes.error || t('common.error'))
        }
    } catch (err: any) {
        quasar.notify({ message: err.message || t('common.error'), color: 'negative' })
    }
}

// 8. Lifecycle Hooks
onMounted(() => {
  if (route.query.enrolled) showEnrollModal.value = true
  loadData()
})
</script>

<template>
  <div class="bg-[#F8F9FA] dark:bg-[#020617] min-h-screen p-4 md:p-8 transition-colors duration-300">
    <div class="max-w-[1240px] mx-auto">
      
      <!-- Section 1: เรียนต่อจากครั้งก่อน (Continue Learning) -->
      <div v-if="inProgressCourses.length > 0 && !searchQuery" class="bg-white dark:!bg-slate-900 rounded-[2rem] p-6 md:p-8 shadow-[0_2px_15px_rgb(0,0,0,0.02)] border border-slate-100 dark:border-slate-800 mb-8 transition-all">
        <div class="flex items-center gap-2.5 mb-6">
          <q-icon name="play_circle_outline" size="26px" class="text-[#3B6BE8]" />
          <h2 class="text-[1.35rem] font-bold text-slate-900 dark:text-white tracking-tight">{{ $t('dashboard.continueLearningTitle') }}</h2>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div v-for="course in inProgressCourses.slice(0, 2)" :key="course.id" class="border border-slate-100 dark:border-slate-800 rounded-3xl p-4 flex flex-col sm:flex-row gap-5 items-center bg-[#F8FAFC] dark:bg-slate-800/50 hover:border-blue-100 dark:hover:border-blue-900/50 transition-colors">
            <!-- ส่วนรูปภาพหน้าปก (Image) -->
            <div class="w-full sm:w-[160px] h-[120px] rounded-[1.25rem] overflow-hidden bg-slate-200 shrink-0 relative group">
               <img :src="course.thumbnail_url" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"/>
               <!-- เลเยอร์เล่นวิดีโอด่วน (Quick play overlay) -->
               <div @click="navigateTo(`/classroom/learning?course_id=${course.id}`)" class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer">
                  <div class="bg-white/30 backdrop-blur-md rounded-full w-10 h-10 flex flex-col items-center justify-center">
                      <q-icon name="play_arrow" color="white" size="20px" class="ml-0.5" />
                  </div>
               </div>
            </div>
            <!-- ส่วนข้อมูลเนื้อหา (Info) -->
            <div class="flex-1 flex flex-col justify-center min-w-0 py-1 w-full">
               <div class="mb-2" v-if="course.category_name">
                  <span class="bg-[#E9EFFD] dark:bg-blue-900/40 text-[#3B6BE8] dark:text-blue-400 px-3.5 py-1.5 rounded-full text-[10px] font-bold tracking-wide">{{ course.category_name }}</span>
               </div>
               <h3 class="font-bold text-slate-900 dark:text-white text-[14px] leading-snug line-clamp-2 mb-4 pr-2">{{ getLocalizedText(course.title) }}</h3>
               
               <div class="flex items-center justify-between gap-4 mt-auto">
                  <div class="flex-1">
                     <div class="flex items-center gap-2 text-[11px] font-bold text-slate-700 dark:text-slate-300 mb-1.5 tracking-wide">
                        {{ $t('course.progress') }}: {{ course.progress }}%
                     </div>
                     <div class="h-[6px] w-full bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
                        <div class="h-full bg-[#3B6BE8] rounded-full transition-all duration-500" :style="{ width: `${course.progress}%` }"></div>
                     </div>
                  </div>
                  <button @click="navigateTo(`/classroom/learning?course_id=${course.id}`)" class="bg-[#3B6BE8] hover:bg-blue-700 text-white rounded-full px-5 py-2 text-[12px] font-bold shrink-0 shadow-md shadow-blue-500/20 transition-transform hover:scale-105 outline-none">{{ $t('dashboard.continue') }}</button>
               </div>
            </div>
          </div>
        </div>
      </div>

      <!-- ส่วนที่ 2: คอร์สของฉัน (My Courses) -->
      <div class="bg-white dark:!bg-slate-900 rounded-[2rem] p-6 md:p-8 shadow-[0_2px_15px_rgb(0,0,0,0.02)] border border-slate-100 dark:border-slate-800 min-h-[500px] mb-12">
        <!-- ส่วนหัวและการค้นหา -->
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
          <h2 class="text-[1.35rem] font-bold text-slate-900 dark:text-white tracking-tight">{{ $t('myCourses.title') }}</h2>
          <div class="flex flex-wrap sm:flex-nowrap items-center gap-3 w-full md:w-auto">
            <div class="relative w-full sm:w-[260px] flex-1">
              <q-icon name="search" size="18px" class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[#3B6BE8]" />
              <input v-model="searchQuery" class="w-full bg-slate-100 dark:bg-slate-800 border-none rounded-xl py-2.5 pl-11 pr-4 text-sm font-medium text-slate-700 dark:text-slate-200 placeholder:text-slate-400 focus:ring-2 focus:ring-blue-500/20 outline-none transition-all shadow-sm" :placeholder="$t('myCourses.searchPlaceholder')" />
            </div>
            <div class="flex items-center gap-2 shrink-0">
              <button @click="viewMode = 'grid'" :class="viewMode === 'grid' ? 'bg-[#E9EFFD] dark:bg-blue-900/40 text-[#3B6BE8] border-[#3B6BE8]' : 'bg-white border-slate-200 dark:bg-slate-800 dark:border-slate-700 text-slate-400 hover:bg-slate-50'" class="w-[42px] h-[42px] flex items-center justify-center rounded-xl border transition-colors outline-none"><q-icon name="grid_view" size="20px" /></button>
              <button @click="viewMode = 'list'" :class="viewMode === 'list' ? 'bg-[#E9EFFD] dark:bg-blue-900/40 text-[#3B6BE8] border-[#3B6BE8]' : 'bg-white border-slate-200 dark:bg-slate-800 dark:border-slate-700 text-slate-400 hover:bg-slate-50'" class="w-[42px] h-[42px] flex items-center justify-center rounded-xl border transition-colors outline-none"><q-icon name="view_list" size="20px" /></button>
            </div>
          </div>
        </div>

        <!-- ตัวกรองหมวดหมู่ (แบบเลื่อนแนวนอนบนมือถือ) -->
        <div class="mb-8 w-full overflow-hidden">
          <div class="flex flex-nowrap items-center gap-3 overflow-x-auto scrollbar-hide pb-2 -mx-1 px-1">
                <button 
                  @click="activeCategory = 'all'"
                  :class="activeCategory === 'all' ? 'bg-[#3B6BE8] text-white border-transparent' : 'bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 hover:border-slate-300'"
                  class="px-5 py-2.5 rounded-xl border text-[13px] sm:text-[14px] flex items-center justify-center gap-2 transition-all outline-none whitespace-nowrap font-bold shadow-sm">
                  <q-icon name="apps" size="18px" /> {{ $t('myCourses.filterAll') }}
                </button>
                
                <button 
                  v-for="cat in uniqueCategories" :key="cat.id"
                  @click="activeCategory = cat.id"
                  :class="activeCategory === cat.id ? 'bg-[#3B6BE8] text-white border-transparent' : 'bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 hover:border-slate-300'"
                  class="px-5 py-2.5 rounded-xl border text-[13px] sm:text-[14px] flex items-center justify-center gap-2 transition-all outline-none whitespace-nowrap font-bold shadow-sm">
                  <q-icon :name="getCategoryIcon(cat.name)" size="18px" />
                  {{ getLocalizedText(cat.name) }}
                </button>
             </div>
         </div>

        <!-- Active View -->
        <div v-if="isLoading" class="flex justify-center py-24">
           <q-spinner size="3rem" color="primary" />
        </div>
        
        <div v-else-if="filteredEnrolledCourses.length > 0">
           
           <!-- หมวดแสดงสไตล์กริดตาราง (GRID VIEW) -->
           <div v-if="viewMode === 'grid'" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              <div v-for="course in filteredEnrolledCourses" :key="course.id" class="flex flex-col rounded-[1.5rem] bg-white dark:!bg-slate-900 border border-slate-100 dark:border-slate-800 overflow-hidden shadow-sm hover:shadow-[0_8px_30px_rgb(0,0,0,0.06)] transition-all duration-300 group cursor-pointer" @click="navigateTo(`/classroom/learning?course_id=${course.id}`)">
                 <!-- ส่วนรูปภาพหน้าปก (Thumbnail) -->
                 <div class="relative w-full aspect-[4/3] bg-slate-100 dark:bg-slate-800 overflow-hidden">
                    <img :src="course.thumbnail_url" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                    <!-- ป้ายหมวดหมู่บนมุมซ้ายของรูป (Badge inside Image Map Top Left) -->
                    <div v-if="course.category_name" class="absolute top-3 left-3 bg-white/95 dark:bg-slate-900/95 backdrop-blur-md text-[#3B6BE8] dark:text-blue-400 font-bold text-[10px] px-3.5 py-1 rounded-full shadow-sm">
                       {{ course.category_name }}
                    </div>
                 </div>
                 
                 <!-- ตัวการ์ด (Card Body) -->
                 <div class="p-5 flex flex-col flex-1">
                    <h3 class="font-bold text-slate-900 dark:text-white text-[14px] leading-snug line-clamp-2 mb-3">{{ getLocalizedText(course.title) }}</h3>
                    

                    
                    <div class="mt-auto flex items-center justify-between gap-4">
                       <div class="flex-1">
                          <div class="text-[10px] font-bold text-slate-700 dark:text-slate-300 mb-1.5 tracking-wide">{{ $t('course.progress') }}: {{ course.progress }}%</div>
                           <div class="h-[6px] w-full bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
                              <div class="h-full rounded-full transition-all duration-500" :class="course.completed ? 'bg-green-500' : 'bg-[#3B6BE8] dark:bg-blue-400'" :style="{ width: `${course.progress}%` }"></div>
                           </div>
                       </div>
                        <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 mt-3 sm:mt-0">
                            <!-- ปุ่มดาวน์โหลดใบเซอร์ (Certificate Button) -->
                            <button v-if="course.completed" @click.stop="handleDownloadCertificate(course.id)" class="border border-green-100 bg-green-50 text-green-600 dark:border-green-900/50 dark:bg-green-900/30 dark:text-green-400 rounded-full px-3 py-1.5 text-[11px] font-bold hover:bg-green-100 dark:hover:bg-green-900/50 transition-colors shrink-0 flex items-center justify-center gap-1">
                              <q-icon name="workspace_premium" size="14px" /> {{ $t('course.certificate') }}
                            </button>
                            <!-- ปุ่มเรียนต่อหรือเรียนซ้ำ (Continue/Replay Button) -->
                            <button class="bg-[#3B6BE8] text-white border-transparent hover:bg-blue-700 shadow-sm rounded-full px-5 py-1.5 text-[11px] font-bold transition-colors shrink-0 text-center cursor-pointer">
                               {{ course.completed ? $t('course.studyAgain') : $t('dashboard.continue') }}
                            </button>
                        </div>
                    </div>
                 </div>
              </div>
           </div>

           <!-- หมวดแสดงสไตล์บรรทัดรายการ (LIST VIEW) -->
           <div v-else class="flex flex-col gap-4">
              <div v-for="course in filteredEnrolledCourses" :key="course.id" class="flex flex-col sm:flex-row items-center rounded-[1.5rem] bg-white dark:!bg-slate-900 border border-slate-100 dark:border-slate-800 p-4 gap-6 shadow-sm hover:shadow-[0_8px_30px_rgb(0,0,0,0.06)] transition-all duration-300 cursor-pointer group" @click="navigateTo(`/classroom/learning?course_id=${course.id}`)">
                 
                 <!-- ส่วนภาพหน้าปกด้านซ้าย (Thumbnail Left) -->
                 <div class="relative w-full sm:w-[240px] aspect-[16/10] sm:aspect-auto sm:h-[130px] rounded-2xl bg-slate-100 dark:bg-slate-800 overflow-hidden shrink-0">
                    <img :src="course.thumbnail_url" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                    <!-- ป้ายหมวดหมู่ในรูปภาพ (Badge inside Image) -->
                    <div v-if="course.category_name" class="absolute top-2.5 left-2.5 bg-white/95 dark:bg-slate-900/95 backdrop-blur-md text-[#3B6BE8] dark:text-blue-400 font-bold text-[10px] px-3.5 py-1 rounded-full shadow-sm">
                       {{ course.category_name }}
                    </div>
                 </div>

                 <!-- เนื้อหาอยู่ทางขวา (Content Right) -->
                 <div class="flex-1 w-full flex flex-col md:flex-row gap-6 md:items-center">
                    
                    <div class="flex-1 min-w-0">
                        <h3 class="font-bold text-slate-900 dark:text-white text-[15px] leading-snug line-clamp-2 mb-3 pr-4">{{ getLocalizedText(course.title) }}</h3>

                    </div>

                    <!-- โซนความคืบหน้าและปุ่มกด (Progress and Button Zone) -->
                    <div class="flex md:flex-col items-center md:items-end justify-between md:justify-center gap-4 shrink-0 md:w-[200px]">
                        <div class="w-full max-w-[140px] md:max-w-full">
                           <div class="flex justify-between items-center text-[11px] font-bold text-slate-700 dark:text-slate-300 mb-2 tracking-wide">
                              <span>{{ $t('course.progress') }}:</span>
                              <span>{{ course.progress }}%</span>
                           </div>
                           <div class="h-[6px] w-full bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
                              <div class="h-full rounded-full transition-all duration-500" :class="course.completed ? 'bg-green-500' : 'bg-[#3B6BE8] dark:bg-blue-400'" :style="{ width: `${course.progress}%` }"></div>
                           </div>
                        </div>

                        <div class="flex flex-col items-stretch md:items-end gap-2 mt-3 sm:mt-0 w-full sm:w-auto">
                            <!-- ปุ่มดาวน์โหลดใบเซอร์ (Certificate Button) -->
                            <button v-if="course.completed" @click.stop="handleDownloadCertificate(course.id)" class="border border-green-100 bg-green-50 text-green-600 dark:border-green-900/50 dark:bg-green-900/30 dark:text-green-400 rounded-full px-4 py-2 text-[12px] font-bold hover:bg-green-100 dark:hover:bg-green-900/50 transition-colors shrink-0 flex items-center justify-center gap-1 w-full sm:w-auto">
                              <q-icon name="workspace_premium" size="16px" /> {{ $t('course.downloadCertificate') }}
                            </button>
                            <!-- ปุ่มเรียนต่อหรือเรียนซ้ำ (Continue/Replay Button) -->
                            <button class="bg-[#3B6BE8] text-white border-transparent hover:bg-blue-700 shadow-sm rounded-full px-6 py-2 text-[12px] font-bold transition-colors shrink-0 text-center w-full sm:w-auto cursor-pointer">
                              {{ course.completed ? $t('course.studyAgain') : $t('dashboard.continue') }}
                            </button>
                        </div>
                    </div>
                 </div>
                 
              </div>
           </div>

        </div>
        
        <!-- กรณีที่ค้นหา/กรองแล้วไม่พบข้อมูล (Empty filter state) -->
        <div v-else class="flex flex-col items-center justify-center py-20">
          <q-icon name="search_off" size="48px" class="text-slate-300 dark:text-slate-600 mb-4" />
          <h3 class="text-lg font-bold text-slate-900 dark:text-white mb-2">{{ $t('myCourses.searchNoResult') }}</h3>
          <p class="text-slate-500 dark:text-slate-400 text-sm">{{ $t('myCourses.searchNoResultDesc') }}</p>
        </div>
      </div>
    
    </div>

    <!-- หน้าต่างแจ้งเตือน: ลงทะเบียนสำเร็จ (MODAL: Enrollment Success) -->
    <q-dialog v-model="showEnrollModal" backdrop-filter="blur(4px)">
      <q-card class="rounded-[1.5rem] shadow-2xl p-8 max-w-sm w-full text-center relative overflow-hidden bg-white dark:bg-slate-800">
        <div class="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-green-400 to-emerald-600"></div>
        <div class="w-16 h-16 bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 rounded-full flex items-center justify-center text-3xl mx-auto mb-6">✓</div>
        <h2 class="text-2xl font-bold mb-2 text-slate-900 dark:text-white">{{ $t('enrollment.successTitle') }}</h2>
        <p class="text-slate-500 dark:text-slate-400 mb-8">{{ $t('enrollment.successDesc') }}</p>
        <div class="flex flex-col gap-3">
          <q-btn v-if="validCourseId" :to="`/classroom/learning?course_id=${validCourseId}`" unelevated rounded color="primary" class="w-full py-3 text-lg font-bold shadow-lg" :label="$t('enrollment.startNow')" />
          <q-btn v-else unelevated rounded color="primary" class="w-full py-3 text-lg font-bold shadow-lg" :label="$t('common.close')" @click="showEnrollModal = false" />
          <q-btn v-if="validCourseId" flat rounded color="grey-7" class="w-full py-3 font-bold" :label="$t('enrollment.later')" @click="showEnrollModal = false" />
        </div>
      </q-card>
    </q-dialog>

  </div>
</template>
