<script setup lang="ts">
/**
 * @file recommended.vue
 * @description Page displaying recommended courses.
 * Matches the layout of the browse page.
 */

// Define page metadata using the landing layout (dark theme default)
definePageMeta({
  layout: 'landing'
})

// Set the HTML head title for SEO
useHead({
  title: 'คอร์สเรียนแนะนำ - E-Learning System'
})

// Reactive state for the search input
const searchQuery = ref('')
const { fetchCourses } = useCourse()
const { fetchCategories, categories } = useCategory()

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

// State for selected category
const selectedCategory = ref('all')

// Fetch categories on mount
await useAsyncData('categories-list', () => fetchCategories())

// Fetch courses from API (reactive to selectedCategory)
const { data: coursesResponse, error, refresh } = await useAsyncData(
  'recommended-courses-list', 
  () => {
    const params: any = {
      is_recommended: true // Only fetch recommended courses
    }
    console.log('Fetching recommended courses. Selected Category:', selectedCategory.value)
    
    if (selectedCategory.value !== 'all') {
      const category = categories.value.find(c => c.slug === selectedCategory.value)
      console.log('Found Category:', category)
      
      if (category) {
        params.category_id = category.id
      }
    }
    
    console.log('Params being sent to fetchCourses:', params)
    return fetchCourses(params)
  }
)

// Watch for category changes and refresh data
watch(selectedCategory, (newVal) => {
    console.log('Selected Category Changed to:', newVal)
    refresh()
})

// Ref for the scroll container
const categoryScroll = ref<HTMLElement | null>(null)

// Computed property for courses list from API response
const courses = computed(() => {
  if (coursesResponse.value?.success) {
    return coursesResponse.value.data
  }
  return []
})

/**
 * @computed filteredCourses
 * @description Filters the courses list based on the search query.
 * Checks both the course title and description (case-insensitive).
 */
const filteredCourses = computed(() => {
  const list = courses.value || []
  if (!searchQuery.value) return list
  
  const query = searchQuery.value.toLowerCase()
  return list.filter(c => {
    const title = getLocalizedText(c.title).toLowerCase()
    const desc = getLocalizedText(c.description).toLowerCase()
    return title.includes(query) || desc.includes(query)
  })
})
</script>

<template>
  <!-- Main Container: Dark Theme Base -->
  <div class="relative min-h-screen text-slate-600  bg-slate-50  transition-colors">
     
     <!-- ==========================================
          BACKGROUND EFFECTS
          Ambient glows matching the index.vue theme
     ========================================== -->
     <div class="fixed inset-0 overflow-hidden pointer-events-none -z-10">
      <div class="absolute top-[-20%] right-[-10%] w-[60%] h-[60%] rounded-full bg-blue-600/10 blur-[140px] animate-pulse-slow"/>
      <div class="absolute bottom-[-20%] left-[-10%] w-[60%] h-[60%] rounded-full bg-indigo-600/10 blur-[140px] animate-pulse-slow" style="animation-delay: 3s;"/>
    </div>

    <!-- ==========================================
          HERO SECTION
          Title and subtitle area
     ========================================== -->
    <section class="relative pt-32 pb-20 px-6 overflow-hidden">
      <div class="container mx-auto max-w-6xl text-center relative z-10">
        <!-- Tagline Badge -->
        <!-- Main Title -->
        <h1 class="text-4xl md:text-6xl font-black text-slate-900 mb-6 tracking-tight py-2 slide-up leading-[1.2] overflow-visible" style="animation-delay: 0.1s;">
          คอร์สเรียนออนไลน์<span class="text-gradient-cyan">แนะนำ</span>
        </h1>
        <!-- Subtitle -->
        <p class="text-slate-400 text-xl max-w-2xl mx-auto leading-relaxed slide-up" style="animation-delay: 0.2s;">
          คัดสรรคอร์สเรียนที่ดีที่สุดเพื่อคุณโดยเฉพาะ ยกระดับทักษะของคุณด้วยเนื้อหาคุณภาพสูงที่เราแนะนำ
        </p>
      </div>
    </section>

    <!-- ==========================================
          SEARCH & GRID SECTION
     ========================================== -->
    <section class="container mx-auto max-w-[1440px] px-6 pb-20">
       
       <!-- Content Frame Container -->
       <div class="glass-premium rounded-[3rem] p-8 md:p-12 shadow-xl shadow-blue-900/5">
        
          <div class="flex flex-col md:flex-row md:items-center justify-between gap-8 mb-8">
            <h2 class="text-2xl font-black text-slate-900  flex items-center gap-3">
              <span class="w-2 h-8 bg-blue-600 rounded-full"/>
              คอร์สที่คุณห้ามพลาด
            </h2>

            <!-- Search Bar (Compact) -->
            <div class="relative max-w-md w-full">
              <div class="relative group">
                <input 
                  v-model="searchQuery" 
                  type="text" 
                  class="w-full pl-12 pr-6 py-3 bg-slate-100  border border-slate-200  rounded-xl text-slate-900  placeholder-slate-400  focus:outline-none focus:bg-white focus: focus:ring-2 focus:ring-blue-500/50 transition-all font-medium" 
                  placeholder="ค้นหาคอร์สแนะนำ..." 
                >
                <div class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                </div>
              </div>
            </div>
          </div>

          <!-- Category Filter Tabs with Scroll Buttons -->
          <div class="relative mb-8">
            <!-- Left Scroll Button -->
            <button 
              class="absolute left-0 top-1/2 -translate-y-1/2 z-10 w-10 h-10 rounded-full bg-white shadow-md border border-slate-100 flex items-center justify-center text-slate-500 hover:text-blue-600 transition-all md:hidden"
              @click="categoryScroll?.scrollBy({ left: -200, behavior: 'smooth' })"
            >
              <q-icon name="chevron_left" size="24px" />
            </button>

            <!-- Scrollable Container -->
            <div 
              ref="categoryScroll"
              class="flex items-center gap-3 overflow-x-auto pb-2 no-scrollbar px-1 scroll-smooth"
            >
              <button 
                class="px-6 py-2.5 rounded-full font-bold text-sm transition-all whitespace-nowrap border-2 flex-shrink-0"
                :class="selectedCategory === 'all' ? 'bg-blue-600 text-white border-blue-600 shadow-lg shadow-blue-600/30' : 'bg-white border-slate-100 text-slate-500 hover:border-slate-300'"
                @click="selectedCategory = 'all'"
              >
                All
              </button>
              <button 
                v-for="category in categories" 
                :key="category.id"
                class="px-6 py-2.5 rounded-full font-bold text-sm transition-all whitespace-nowrap border-2 flex-shrink-0"
                :class="selectedCategory === category.slug ? 'bg-blue-600 text-white border-blue-600 shadow-lg shadow-blue-600/30' : 'bg-white border-slate-100 text-slate-500 hover:border-slate-300'"
                @click="selectedCategory = category.slug"
              >
                {{ getLocalizedText(category.name) }}
              </button>
            </div>

            <!-- Right Scroll Button -->
             <button 
              class="absolute right-0 top-1/2 -translate-y-1/2 z-10 w-10 h-10 rounded-full bg-white shadow-md border border-slate-100 flex items-center justify-center text-slate-500 hover:text-blue-600 transition-all md:hidden"
              @click="categoryScroll?.scrollBy({ left: 200, behavior: 'smooth' })"
            >
              <q-icon name="chevron_right" size="24px" />
            </button>
          </div>


          <!-- Course Grid (4 cols) -->
          <div v-if="filteredCourses.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            <div 
              v-for="(course, index) in filteredCourses" 
              :key="course.id" 
              class="glass-card group flex flex-col h-full hover:-translate-y-2 transition-transform duration-500 slide-up"
              :style="{ animationDelay: `${0.1 * (index + 1)}s` }"
            >
              <!-- Card Image -->
              <div class="h-48 bg-gradient-to-br from-slate-800 to-slate-900 relative overflow-hidden group-hover:opacity-90 transition-opacity">
                <!-- Recommended Badge -->
                
                
                <img 
                  v-if="course.thumbnail_url" 
                  :src="course.thumbnail_url" 
                  :alt="getLocalizedText(course.title)"
                  class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                  @error="(e) => (e.target as HTMLImageElement).style.display = 'none'" 
                />
                <div 
                  v-else 
                  class="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-slate-800 to-slate-900"
                >
                </div>
              </div>

              <!-- Card Content Body -->
              <div class="p-6 flex-1 flex flex-col border-t border-slate-100 ">
                <h3 class="text-xl font-bold text-slate-900  mb-2 leading-snug group-hover:text-blue-600  transition-colors line-clamp-2">
                  {{ getLocalizedText(course.title) }}
                </h3>
                <p class="text-slate-500  text-xs mb-6 line-clamp-2 leading-relaxed flex-1">
                  {{ getLocalizedText(course.description) }}
                </p>

                <!-- Card Footer -->
                <div class="pt-4 border-t border-slate-100  flex items-center justify-between mt-auto">
                  <span class="text-lg font-black text-blue-600  tracking-tight">
                    {{ course.is_free ? 'ฟรี' : course.price }}
                  </span>
                  <NuxtLink 
                    :to="`/course/${course.id}`" 
                    class="px-4 py-2 bg-slate-50  hover:bg-blue-600 text-slate-600  hover:text-white rounded-lg text-xs font-bold transition-all border border-slate-200  hover:border-blue-500/50"
                  >
                    ดูรายละเอียด
                  </NuxtLink>
                </div>
              </div>
            </div>
          </div>

          <!-- Empty State (No Results) -->
          <div v-else class="text-center py-20">
            <div class="text-6xl mb-6 opacity-50 animate-bounce">💎</div>
            <h2 class="text-2xl font-black text-slate-900  mb-3">ไม่พบคอร์สแนะนำในขณะนี้</h2>
            <p class="text-slate-400 mb-8 max-w-md mx-auto">
              ลองเลือกหมวดหมู่อื่น หรือกลับมาดูใหม่ภายหลัง
            </p>
            <button 
              class="px-6 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-xl font-bold transition-all shadow-lg shadow-blue-600/20" 
              @click="searchQuery = ''; selectedCategory = 'all'"
            >
              ล้างค่าการค้นหา
            </button>
          </div>

       </div>
    </section>

    <!-- ==========================================
          CTA SECTION
     ========================================== -->
    <section class="py-24 relative overflow-hidden">
       <!-- Background Decoration -->
       <div class="absolute inset-0 bg-gradient-to-b from-transparent to-blue-50/80 pointer-events-none -z-10"/>
       <div class="absolute bottom-0 left-1/2 -translate-x-1/2 w-[800px] h-[400px] bg-blue-400/10 blur-[120px] rounded-full -z-10 pointer-events-none"/>
      
      <div class="container mx-auto max-w-4xl text-center relative z-10 px-6">
        <h2 class="text-4xl md:text-5xl font-black text-slate-900  mb-6 tracking-tight">
          ปลดล็อกศักยภาพของคุณวันนี้
        </h2>
        <p class="text-slate-500 text-lg md:text-xl mb-10 max-w-2xl mx-auto leading-relaxed">
          เริ่มเรียนรู้กับคอร์สที่เราแนะนำ และเติบโตไปพร้อมกับผู้เรียนนับหมื่นคน
        </p>
        <NuxtLink 
          to="/auth/register" 
          class="inline-flex items-center gap-3 px-10 py-5 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white rounded-2xl text-lg font-black shadow-2xl shadow-blue-900/40 hover:scale-105 transition-all duration-300"
        >
          <span></span>
          <span>สมัครสมาชิกฟรี</span>
        </NuxtLink>
      </div>
    </section>
  </div>
</template>

<style scoped>
/* 
  MATCHING INDEX.VUE STYLES
  Adjusted to Pink/Rose theme for "Recommended" feel
*/

/* Gradient Text Effect (Cyan to Blue) */
.text-gradient-cyan {
  background: linear-gradient(135deg, #22d3ee 0%, #3b82f6 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  display: inline-block;
  padding: 0.5em 0.2em;
  margin: -0.5em -0.2em;
  vertical-align: baseline;
}

/* Premium Glass Effect */
.glass-premium {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(40px);
  border: 1px solid rgba(255, 255, 255, 0.5);
}

/* Glass Card Style */
.glass-card {
  background: white;
  border: 1px solid rgba(0, 0, 0, 0.05);
  border-radius: 2rem;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0,0,0,0.05);
}

/* Animations */
@keyframes pulse-slow {
  0%, 100% { opacity: 0.1; transform: scale(1); }
  50% { opacity: 0.15; transform: scale(1.15); }
}

.animate-pulse-slow {
  animation: pulse-slow 10s linear infinite;
}

@keyframes slide-up {
  from { opacity: 0; transform: translateY(30px); }
  to { opacity: 1; transform: translateY(0); }
}

.slide-up {
  animation: slide-up 0.8s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
  opacity: 0;
}
</style>
