<script setup lang="ts">
/**
 * @file discovery.vue
 * @description Course Discovery / Catalog Page.
 * Allows users to browse, filter, and view details of available courses.
 * Includes a toggleable detailed view for course previews.
 */

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

useHead({
  title: "รายการคอร์ส - e-Learning",
});

// ==========================================
// 1. State Management
const showDetail = ref(false);
const searchQuery = ref("");
const selectedCategoryIds = ref<number[]>([]);
const categories = ref<any[]>([]);
const courses = ref<any[]>([]);
const selectedCourse = ref<any>(null);

const isLoading = ref(false);
const isLoadingDetail = ref(false);
const isEnrolling = ref(false);
const showAllCategories = ref(false);

const { t } = useI18n();
const { fetchCategories } = useCategory();
const { fetchCourses, fetchCourseById, enrollCourse } = useCourse();
// const { currentUser } = useAuth() // Unused

// 2. Computed Properties
const sortOption = ref(computed(() => t('discovery.sortRecent')));
const sortOptions = computed(() => [t('discovery.sortRecent')]);

const filteredCourses = computed(() => {
  let result = courses.value;
  if (selectedCategoryIds.value.length > 0) {
    result = result.filter(c => selectedCategoryIds.value.includes(c.category_id));
  }
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(c => {
      const title = getLocalizedText(c.title).toLowerCase();
      const desc = getLocalizedText(c.description).toLowerCase();
      return title.includes(query) || (desc && desc.includes(query));
    });
  }
  return result;
});

// 3. Helper Functions
const getLocalizedText = (text: string | { th: string; en: string } | undefined) => {
  if (!text) return '';
  if (typeof text === 'string') return text;
  return text.th || text.en || '';
};

// 4. API Actions
const loadCategories = async () => {
  const res = await fetchCategories();
  if (res.success) categories.value = res.data || [];
};

const loadCourses = async () => {
  isLoading.value = true;
  const res = await fetchCourses();
  if (res.success) {
    courses.value = res.data || [];
  }
  isLoading.value = false;
};

const selectCourse = async (id: number) => {
  isLoadingDetail.value = true;
  selectedCourse.value = null;
  showDetail.value = true;
  const res = await fetchCourseById(id);
  if (res.success) selectedCourse.value = res.data;
  isLoadingDetail.value = false;
};

const handleEnroll = async (id: number) => {
  if (isEnrolling.value) return;
  isEnrolling.value = true;
  const res = await enrollCourse(id);
  if (res.success) {
    return navigateTo('/dashboard/my-courses?enrolled=true');
  } else {
    alert(res.error || 'Failed to enroll');
  }
  isEnrolling.value = false;
};

onMounted(() => {
  loadCategories();
  loadCourses();
});
</script>

<template>
  <div class="p-6 max-w-[1400px] mx-auto">


    <!-- CATALOG VIEW: Browse courses -->
    <div v-if="!showDetail">
      
      <!-- Top Header Area -->
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <!-- Title -->
        <h2 class="text-2xl font-bold text-slate-900 dark:text-white">
          {{ $t('discovery.title') }}
        </h2>

        <!-- Right Side: Search & Sort -->
        <div class="flex items-center gap-3">
          <!-- Search Input -->
          <q-input
            v-model="searchQuery"
            dense
            outlined
            rounded
            :placeholder="$t('discovery.searchPlaceholder')"
            class="disc-search w-full md:w-64"
          >
            <template v-slot:append>
              <q-icon name="search" class="text-slate-400" />
            </template>
          </q-input>

          <!-- Sort Dropdown -->
          <q-select
            v-model="sortOption"
            :options="sortOptions"
            dense
            outlined
            rounded
            :dark="false"
            class="disc-sort w-40"
            :options-dark="false"
            options-dense
            popup-content-class="text-slate-900"
            behavior="menu"
          />
        </div>
      </div>

      <!-- Main Layout: Sidebar + Grid -->
      <div class="flex flex-col lg:flex-row gap-8 items-start">
          
          <!-- LEFT SIDEBAR: Category Filter -->
          <div class="w-full lg:w-64 flex-shrink-0 sticky top-24">
             <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
                <q-expansion-item
                    expand-separator
                    :label="`หมวดหมู่ (${selectedCategoryIds.length})`"
                    class="font-bold text-slate-900"
                    header-class="bg-white"
                    text-color="slate-900"
                    :header-style="{ color: '#0f172a' }"
                    default-opened
                >
                  <q-list class="bg-white border-t border-slate-200">
                      <q-item
                        v-for="cat in (showAllCategories ? categories : categories.slice(0, 4))"
                        :key="cat.id"
                        tag="label"
                        clickable
                        v-ripple
                        dense
                      >
                        <q-item-section avatar>
                          <q-checkbox 
                            v-model="selectedCategoryIds" 
                            :val="cat.id" 
                            color="primary" 
                            dense
                            class="checkbox-visible"
                          />
                        </q-item-section>
                        <q-item-section>
                          <q-item-label class="text-sm font-medium text-slate-900">{{ getLocalizedText(cat.name) }}</q-item-label>
                        </q-item-section>
                      </q-item>

                      <!-- Show More/Less Button -->
                      <q-item
                        v-if="categories.length > 4"
                        clickable
                        v-ripple
                        @click="showAllCategories = !showAllCategories"
                        class="text-blue-600 font-bold text-sm"
                      >
                        <q-item-section>
                            <div class="flex items-center gap-1">
                              {{ showAllCategories ? 'แสดงน้อยลง' : 'แสดงเพิ่มเติม' }}
                              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" :class="showAllCategories ? 'rotate-180' : ''">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                              </svg>
                            </div>
                        </q-item-section>
                      </q-item>
                  </q-list>
                </q-expansion-item>
             </div>
          </div>

          <!-- RIGHT CONTENT: Course Grid -->
          <div class="flex-1 w-full">
              <div v-if="filteredCourses.length > 0" class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6">
                  <CourseCard
                    v-for="course in filteredCourses"
                    :key="course.id"
                    :title="course.title"
                    :price="course.price"
                    :description="course.description"
                    :rating="course.rating"
                    :lessons="course.lessons"
                    :image="course.thumbnail_url"
                    show-view-details
                    @view-details="selectCourse(course.id)"
                  />
              </div>

              <!-- Empty State -->
              <div
                v-else
                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"
              >
                
                <h3 class="text-xl font-bold text-slate-900 dark:text-white mb-2">{{ $t('discovery.emptyTitle') }}</h3>
                <p class="text-slate-500 dark:text-slate-400 text-center max-w-md">
                  {{ $t('discovery.emptyDesc') }}
                </p>
                <button class="mt-6 font-bold text-blue-600 hover:underline" @click="searchQuery = ''; selectedCategoryIds = []">
                  {{ $t('discovery.showAll') }}
                </button>
              </div>
          </div>

      </div>

    </div>

    <!-- COURSE DETAIL VIEW: Detailed information about a specific course -->
    <div v-else>
      <button 
        @click="showDetail = false" 
        class="inline-flex items-center gap-2 text-slate-600 dark:text-white hover:text-blue-600 dark:hover:text-blue-300 mb-6 transition-all font-black text-lg md:text-xl group"
      >
        <q-icon name="arrow_back" size="28px" class="transition-transform group-hover:-translate-x-2" />
        {{ $t('discovery.backToCatalog') }}
      </button>

      <div v-if="isLoadingDetail" class="flex justify-center py-20">
         <q-spinner size="3rem" color="primary" />
      </div>

      <div v-else-if="selectedCourse" class="grid grid-cols-1 lg:grid-cols-12 gap-8">
        <!-- Main Content (Left Column) -->
        <div class="lg:col-span-8">
          <!-- Hero Video Placeholder -->
          <div
            class="w-full aspect-video bg-slate-900 rounded-3xl overflow-hidden relative shadow-lg mb-8 group"
          >
             <img 
               v-if="selectedCourse.thumbnail_url" 
               :src="selectedCourse.thumbnail_url" 
               class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:opacity-40 transition-opacity"
             />
          </div>

          <h1 class="text-3xl md:text-4xl font-bold mb-4 text-slate-900 dark:text-white tracking-tight">
            {{ getLocalizedText(selectedCourse.title) }}
          </h1>
          <p class="text-slate-600 dark:text-slate-400 text-lg leading-relaxed mb-8">
            {{ getLocalizedText(selectedCourse.description) }}
          </p>

          <!-- Course Syllabus -->
          <div class="bg-white dark:bg-slate-800 rounded-3xl p-8 shadow-sm border border-slate-100 dark:border-slate-700">
            <h3 class="text-xl font-bold mb-6 text-slate-900 flex items-center gap-2">
               <span class="w-1 h-6 bg-blue-500 rounded-full"></span>
               {{ $t('course.courseContent') }}
            </h3>
            <div class="space-y-4">
                <div v-for="(chapter, index) in selectedCourse.chapters" :key="chapter.id" class="border border-slate-200 dark:border-slate-700 rounded-xl overflow-hidden">
                   <div class="bg-slate-50 dark:bg-slate-700/50 p-4 flex justify-between items-center cursor-pointer">
                      <div class="font-bold text-slate-800 dark:text-slate-100">
                          <span class="opacity-50 mr-2">Chapter {{ Number(index) + 1 }}</span>
                          {{ getLocalizedText(chapter.title) }}
                      </div>
                      <span class="text-xs font-bold px-3 py-1 bg-white rounded-full border border-slate-200">
                          {{ chapter.lessons ? chapter.lessons.length : 0 }} Lessons
                      </span>
                   </div>
                   <!-- Lessons -->
                   <div class="divide-y divide-slate-100 dark:divide-slate-700 bg-white dark:bg-slate-800">
                       <div v-for="(lesson, lIndex) in chapter.lessons" :key="lesson.id" class="p-4 flex justify-between items-center hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors">
                           <div class="flex items-center gap-3">
                               <div class="w-6 h-6 rounded-full bg-slate-100 dark:bg-slate-700 flex items-center justify-center text-[10px] font-bold text-slate-500 dark:text-slate-400">
                                   {{ Number(lIndex) + 1 }}
                               </div>
                               <span class="text-slate-700 dark:text-slate-200 font-medium text-sm">{{ getLocalizedText(lesson.title) }}</span>
                           </div>
                           <span class="text-xs text-slate-400">{{ lesson.duration_minutes || 0 }}:00</span>
                       </div>
                   </div>
                </div>
            </div>
          </div>
        </div>

        <!-- Sidebar (Right Column) -->
        <div class="lg:col-span-4">
          <div class="bg-white rounded-3xl p-6 shadow-lg border border-slate-100 sticky top-24">
            <q-btn
              @click="handleEnroll(selectedCourse.id)"

              unelevated
              rounded
              class="w-full py-3 text-lg font-bold bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-lg"
              :loading="isEnrolling"
              :label="$t('course.enrollNow')"
            >
              <template v-slot:loading>
                <q-spinner-facebook />
              </template>
            </q-btn>

            <div class="text-sm space-y-3 pt-4 border-t border-slate-100">
               <div class="flex justify-between text-slate-600 dark:text-black">
                   <span>{{ $t('course.certificate') }}</span>
                   <span class="font-bold text-slate-900 dark:text-black">{{ selectedCourse.have_certificate ? 'มีใบประกาศฯ' : 'ไม่มี' }}</span>
               </div>
               <div v-if="selectedCourse.instructor_name" class="flex justify-between text-slate-600 dark:text-black">
                   <span>ผู้สอน</span>
                   <span class="font-bold text-slate-900 dark:text-black">{{ selectedCourse.instructor_name }}</span>
               </div>
               <div v-if="selectedCourse.level" class="flex justify-between text-slate-600 dark:text-black">
                   <span>ระดับ</span>
                   <span class="font-bold text-slate-900 dark:text-black">{{ selectedCourse.level }}</span>
               </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* =========================
   Discovery: Quasar Field Fix
   - จำกัดผลกระทบเฉพาะช่องค้นหา/เรียงตาม
   - ตัด focus ring (กรอบขาว 4 เหลี่ยม)
   ========================= */

/* ให้หน้าตา input เป็น pill ขาวเหมือนรูป (ทั้ง Light/Dark) */
.disc-search :deep(.q-field__control),
.disc-sort :deep(.q-field__control) {
  background: #ffffff !important;
  border-radius: 9999px !important;
}

/* สีตัวอักษร/placeholder/icon ให้คมชัด */
.disc-search :deep(.q-field__native),
.disc-search :deep(.q-field__input),
.disc-sort :deep(.q-field__native),
.disc-sort :deep(.q-field__input) {
  color: #0f172a !important;
  -webkit-text-fill-color: #0f172a !important;
}

.disc-search :deep(.q-placeholder),
.disc-sort :deep(.q-placeholder) {
  color: #64748b !important; /* slate-500 */
}

.disc-search :deep(.q-icon),
.disc-sort :deep(.q-icon),
.disc-sort :deep(.q-select__dropdown-icon) {
  color: #64748b !important;
}

/* ✅ ตัด “Focus outline / Focus ring” ที่เป็นกรอบสว่าง */
.disc-search :deep(.q-field__control:after),
.disc-sort :deep(.q-field__control:after) {
  opacity: 0 !important; /* ตัวนี้มักเป็นเส้น/แสงตอน focus */
}

/* คุมเส้นขอบปกติให้บาง ๆ ไม่เด้งเป็นกรอบขาว */
.disc-search :deep(.q-field__control:before),
.disc-sort :deep(.q-field__control:before) {
  border-color: rgba(203, 213, 225, 0.9) !important; /* slate-300 */
}

/* กัน browser outline ซ้อน */
.disc-search :deep(input:focus),
.disc-sort :deep(input:focus) {
  outline: none !important;
  box-shadow: none !important;
}
</style>

