<script setup lang="ts">
/**
 * @file my-courses.vue
 * @description My Courses Page.
 * Displays enrolled courses with filters for progress/completed.
 * Handles enrollment success modals and certificate downloads.
 */

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

useHead({
  title: 'คอร์สของฉัน - e-Learning'
})

const route = useRoute()
const showEnrollModal = ref(false)
const activeFilter = ref<'all' | 'progress' | 'completed'>('all')
const searchQuery = ref('')


// Check URL query parameters to show 'Enrollment Success' modal
onMounted(() => {
  if (route.query.enrolled) {
    showEnrollModal.value = true
  }
})

const { locale } = useI18n()

// Helper to get localized text
const getLocalizedText = (text: string | { th: string; en: string } | undefined) => {
  if (!text) return ''
  if (typeof text === 'string') return text
  
  const currentLocale = locale.value as 'th' | 'en'
  return text[currentLocale] || text.th || text.en || ''
}

// Data Handling
const { fetchEnrolledCourses, getCertificate, generateCertificate } = useCourse()
const enrolledCourses = ref<any[]>([])
const isLoading = ref(false)
const isDownloadingCert = ref(false)

const loadEnrolledCourses = async () => {
  isLoading.value = true
  // FIX: For 'progress' tab, we want both ENROLLED and IN_PROGRESS.
  // Since API takes single status, we fetch ALL and filter locally for 'progress'.
  const apiStatus = activeFilter.value === 'completed' 
      ? 'COMPLETED' 
      : undefined // 'all' or 'progress' -> fetch all

  const res = await fetchEnrolledCourses({ 
    status: apiStatus
  })

  if (res.success) {
    let courses = (res.data || [])

    // Local filter to ensure UI consistency regardless of backend filtering
    if (activeFilter.value === 'progress') {
        courses = courses.filter(c => c.status !== 'COMPLETED')
    } else if (activeFilter.value === 'completed') {
        courses = courses.filter(c => c.status === 'COMPLETED')
    }

    enrolledCourses.value = courses.map(item => ({
      id: item.course_id, 
      enrollment_id: item.id,
      title: item.course.title,
      progress: item.progress_percentage || 0, 
      lessons: item.course.total_lessons || 0,
      completed: item.status === 'COMPLETED',
      thumbnail_url: item.course.thumbnail_url 
    }))
  }
  isLoading.value = false
}

// Watch filter changes to reload
watch(activeFilter, () => {
  loadEnrolledCourses()
})

// Client-side Search Filtering
const filteredEnrolledCourses = computed(() => {
  if (!searchQuery.value) return enrolledCourses.value
  const query = searchQuery.value.toLowerCase()
  return enrolledCourses.value.filter(c => {
    const title = getLocalizedText(c.title).toLowerCase()
    return title.includes(query)
  })
})

onMounted(() => {
  if (route.query.enrolled) {
    showEnrollModal.value = true
  }
  loadEnrolledCourses()
})

// Certificate Handling
const downloadingCourseId = ref<number | null>(null)
// Certificate Handling

const downloadCertificate = async (course: any) => {
  if (!course) return
  downloadingCourseId.value = course.id
  
  try {
      // 1. Try to GET existing certificate
      let res = await getCertificate(course.id)

      // 2. If not found (or error), try to GENERATE new one
      if (!res.success) {
         res = await generateCertificate(course.id)
      }

      // 3. Handle Result
      if (res.success && res.data) {
          const cert = res.data
          if (cert.download_url) {
              window.open(cert.download_url, '_blank')
          } else {
              // Fallback if no URL but success (maybe show message)
              console.warn('Certificate ready but no URL')
          }
      } else {
           // Silent fail or minimal log, or maybe use a toast if available, but avoid $q if undefined
           console.error(res.error || 'Failed to get certificate')
      }
  } catch (e) {
      console.error(e)
  } finally {
      downloadingCourseId.value = null
  }
}

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

<template>
  <div class="page-container">


    <!-- Page Header & Filters (Unified Layout) -->
    <div class="mb-8">
       <div class="flex items-start gap-4 mb-2">
          <span class="w-1.5 h-10 md:h-12 bg-blue-600 rounded-full shadow-lg shadow-blue-500/50 mt-1 flex-shrink-0"></span>
          <div>
            <h1 class="text-3xl md:text-4xl font-black text-slate-900 dark:text-white leading-tight">
              {{ $t('sidebar.myCourses') }}
            </h1>
          </div>
       </div>

       <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mt-4">
          <!-- Filter Tabs (Horizontal Bar) -->
          <div class="bg-white dark:bg-slate-900/50 p-1.5 rounded-2xl border border-slate-100 dark:border-white/5 inline-flex items-center gap-1 shadow-sm">
            <q-btn
              v-for="filter in ['all', 'progress', 'completed']"
              :key="filter"
              @click="activeFilter = filter as any"
              flat
              rounded
              dense
              class="px-5 py-2 font-bold transition-all text-[11px] uppercase tracking-wider"
              :class="activeFilter === filter ? 'bg-blue-600 text-white shadow-md shadow-blue-600/20' : 'text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-800'"
              :label="$t(`myCourses.filter${filter.charAt(0).toUpperCase() + filter.slice(1)}`)"
            />
          </div>

          <!-- Search Input -->
          <div class="w-full md:w-72">
            <q-input
              v-model="searchQuery"
              dense
              outlined
              rounded
              :placeholder="$t('discovery.searchPlaceholder')"
              class="search-input shadow-sm"
              bg-color="transparent"
            >
              <template v-slot:prepend>
                <q-icon name="search" class="text-slate-400" />
              </template>
            </q-input>
          </div>
       </div>
    </div>

    <!-- Courses Grid -->
    <div v-if="isLoading" class="flex justify-center py-20">
       <q-spinner size="3rem" color="primary" />
    </div>
    <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
      <template v-for="course in filteredEnrolledCourses" :key="course.id">
        <!-- In Progress Course Card -->
        <CourseCard 
          v-if="!course.completed"
          :id="course.id"
          :title="course.title"
          :progress="course.progress"
          :image="course.thumbnail_url"
          show-continue
          :show-view-details="false"
        />
        <!-- Completed Course Card -->
        <CourseCard 
          v-else
          :id="course.id"
          :title="course.title"
          :progress="100"
          :image="course.thumbnail_url"
          :completed="true"
          show-certificate
          show-study-again
          :show-view-details="false"
          :loading="downloadingCourseId === course.id"
          @view-certificate="downloadCertificate(course)"
        />
      </template>
    </div>

    <!-- Empty State -->
    <div v-if="!isLoading && filteredEnrolledCourses.length === 0" class="flex flex-col items-center justify-center py-20 bg-slate-50 dark:bg-slate-800/50 rounded-3xl border-2 border-dashed border-slate-200 dark:border-slate-700 mt-4">
      <q-icon v-if="searchQuery" name="search_off" size="64px" class="text-slate-300 dark:text-slate-600 mb-4" />
      <h3 class="text-xl font-bold text-slate-900 dark:text-white mb-2">
        {{ searchQuery ? $t('discovery.emptyTitle') : $t('myCourses.emptyTitle') }}
      </h3>
      <p class="text-slate-500 dark:text-slate-400 text-center max-w-md">
        {{ searchQuery ? $t('discovery.emptyDesc') : $t('myCourses.emptyDesc') }}
      </p>
      <NuxtLink v-if="!searchQuery" to="/browse/discovery" class="mt-6 px-6 py-2 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 transition-colors">{{ $t('myCourses.goToDiscovery') }}</NuxtLink>
      <button v-else class="mt-4 font-bold text-blue-600 hover:text-blue-700 transition-colors" @click="searchQuery = ''">
        {{ $t('discovery.showAll') }}
      </button>
    </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>

<style scoped>
/* Custom Font for Signature/Name if desired */
.font-handwriting {
  font-family: 'Dancing Script', cursive, serif; /* Fallback */
}
</style>
