﻿<script setup lang="ts">
/**
 * @file learning.vue
 * @description หน้าเรียนออนไลน์ (Classroom Interface)
 * จัดการแสดงผลวิดีโอรายการบทเรียน และติดตามความคืบหน้า
 * ออกแบบให้เหมือนระบบ LMS มาตรฐาน
 */


definePageMeta({
  layout: false, // Custom layout defined within this component
  middleware: 'auth'
})

useHead({
  title: 'ห้องเรียนออนไลน์ - e-Learning'
})

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const { user } = useAuth()
const { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, checkLessonAccess, fetchVideoProgress, fetchCourseAnnouncements } = useCourse()
// Media Prefs (Global Volume)
const { volume, muted: isMuted, setVolume, setMuted, applyTo } = useMediaPrefs()

// State
const sidebarOpen = ref(false)
const courseId = computed(() => Number(route.query.course_id))

// ==========================================
// 1. ตัวแปร State (สถานะของ UI)
// ==========================================
// courseData: เก็บข้อมูลโครงสร้างคอร์ส (บทเรียนต่างๆ)
const courseData = ref<any>(null)
const announcements = ref<any[]>([]) // Announcements state
const showAnnouncementsModal = ref(false) // Modal state
const hasUnreadAnnouncements = ref(false) // Unread state tracking

// Helper for persistent read status
const getAnnouncementStorageKey = () => {
    if (!user.value?.id || !courseId.value) return ''
    return `read_announcements:${user.value.id}:${courseId.value}`
}

const checkUnreadAnnouncements = () => {
    if (!announcements.value || announcements.value.length === 0) {
        hasUnreadAnnouncements.value = false
        return
    }
    
    if (typeof window === 'undefined') return 

    const key = getAnnouncementStorageKey()
    if (!key) return 

    const lastRead = localStorage.getItem(key)
    if (!lastRead) {
        hasUnreadAnnouncements.value = true
        return
    }

    const lastReadDate = new Date(lastRead).getTime()
    const hasNew = announcements.value.some(a => {
        const annDate = new Date(a.created_at || Date.now()).getTime()
        // Check if announcement is strictly newer than last read
        return annDate > lastReadDate
    })
    
    hasUnreadAnnouncements.value = hasNew
}

// Handler for opening announcements
const handleOpenAnnouncements = () => {
    showAnnouncementsModal.value = true
    hasUnreadAnnouncements.value = false // Clear unread badge on click
    
    const key = getAnnouncementStorageKey()
    if (key) {
        localStorage.setItem(key, new Date().toISOString())
    }
}

// currentLesson: บทเรียนที่กำลังเรียนอยู่ปัจจุบัน
const currentLesson = ref<any>(null)
const isLoading = ref(true)        // โหลดข้อมูลคอร์ส
const isLessonLoading = ref(false) // โหลดเนื้อหาบทเรียน

// Video Player State (สถานะวิดีโอ)
const videoRef = ref<HTMLVideoElement | null>(null)
const isPlaying = ref(false)
const videoProgress = ref(0)
const currentTime = ref(0)
const duration = ref(0)


// Helper for localization
const getLocalizedText = (text: any) => {
  if (!text) return ''
  if (typeof text === 'string') return text
  return text.th || text.en || ''
}

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value
}

// Logic loadLesson แยกออกมา
const handleLessonSelect = (lessonId: number) => {
  loadLesson(lessonId)
  // Close sidebar on mobile when selecting a lesson
  if (import.meta.client && window.innerWidth <= 1024) {
    sidebarOpen.value = false
  }
}

// Data Fetching
// ==========================================
// 2. ฟังก์ชันโหลดข้อมูล (Data Fetching)
// ==========================================

// โหลดโครงสร้างคอร์สและบทเรียนทั้งหมด
const loadCourseData = async () => {
  if (!courseId.value) return
  isLoading.value = true
  try {
    const res = await fetchCourseLearningInfo(courseId.value)
    if (res.success) {
      courseData.value = res.data
      
      // Auto-load logic: ถ้ายังไม่ได้เลือกบทเรียน ให้โหลดบทแรกที่ไม่ล็อคมาแสดง
      if (!currentLesson.value) {
        const firstChapter = res.data.chapters[0]
        if (firstChapter && firstChapter.lessons.length > 0) {
            // Find first unlocked or just first
            const availableLesson = firstChapter.lessons.find((l: any) => !l.is_locked) || firstChapter.lessons[0]
            loadLesson(availableLesson.id)
        }
      }

      // Fetch Announcements
      const annRes = await fetchCourseAnnouncements(courseId.value)
      if (annRes.success) {
          announcements.value = annRes.data || []
          checkUnreadAnnouncements()
      }
    }
  } catch (error) {
    console.error('Error loading course:', error)
  } finally {
    isLoading.value = false
  }
}

const loadLesson = async (lessonId: number) => {
  if (currentLesson.value?.id === lessonId) return
  
  // Clear previous video state
  isPlaying.value = false
  videoProgress.value = 0
  currentTime.value = 0
  if (videoRef.value) {
      videoRef.value.pause()
      videoRef.value.currentTime = 0
  }

  isLessonLoading.value = true
  try {
    // Optional: Check access first
    const accessRes = await checkLessonAccess(courseId.value, lessonId)
    if (accessRes.success && !accessRes.data.is_accessible) {
        let msg = t('classroom.notAvailable')
        
        // Handle specific lock reasons
        if (accessRes.data.lock_reason) {
            msg = accessRes.data.lock_reason
        } else if (accessRes.data.required_quiz_pass && !accessRes.data.required_quiz_pass.is_passed) {
             const quizTitle = getLocalizedText(accessRes.data.required_quiz_pass.title)
             msg = `กรุณาทำแบบทดสอบ "${quizTitle}" ให้ผ่านก่อน`
        } else if (accessRes.data.required_lessons && accessRes.data.required_lessons.length > 0) {
             const reqLesson = accessRes.data.required_lessons.find((l: any) => !l.is_completed)
             if (reqLesson) {
                msg = `กรุณาเรียนบทเรียน "${getLocalizedText(reqLesson.title)}" ให้จบก่อน`
             }
        } else if (accessRes.data.is_enrolled === false) {
             msg = 'คุณยังไม่ได้ลงทะเบียนในคอร์สนี้'
        }

        alert(msg)
        isLessonLoading.value = false
        return
    }

    // 1. Fetch content
    const res = await fetchLessonContent(courseId.value, lessonId)
    if (res.success) {
      currentLesson.value = res.data
      
      // Update Lesson Completion UI status safely
      if (currentLesson.value?.progress?.is_completed && courseData.value) {
          for (const chapter of courseData.value.chapters) {
              const lesson = chapter.lessons.find((l: any) => l.id === lessonId)
              if (lesson) {
                  if (!lesson.progress) lesson.progress = {}
                  lesson.progress.is_completed = true
                  break
              }
          }
      }

      // 2. Fetch Initial Progress (Resume Playback)
      if (currentLesson.value.type === 'VIDEO') {
           // A. Server Progress
           const progressRes = await fetchVideoProgress(lessonId)
           let serverProgress = 0
           if (progressRes.success && progressRes.data?.video_progress_seconds) {
               serverProgress = progressRes.data.video_progress_seconds
           }

           // B. Local Progress (Buffer)
           const localProgress = getLocalProgress(lessonId)
           
           // C. Hybrid Resume (Max Wins)
           const resumeTime = Math.max(serverProgress, localProgress)
           
           if (resumeTime > 0) {

               initialSeekTime.value = resumeTime
               maxWatchedTime.value = resumeTime 
               currentTime.value = resumeTime
           } else {
               initialSeekTime.value = 0
               maxWatchedTime.value = 0
           }
      }
    }
  } catch (error) {
    console.error('Error loading lesson:', error)
  } finally {
    isLessonLoading.value = false
  }
}

// Video & Progress State
const initialSeekTime = ref(0)
const maxWatchedTime = ref(0) // Anti-rewind monotonic tracking
const lastSavedTime = ref(-1)
const lastSavedTimestamp = ref(0) // Server throttle timestamp
const lastLocalSaveTimestamp = ref(0) // Local throttle timestamp

// Helper: Get Local Storage Key
const getLocalProgressKey = (lessonId: number) => {
    if (!user.value?.id) return null
    return `progress:${user.value.id}:${lessonId}`
}

// Helper: Get Local Progress
const getLocalProgress = (lessonId: number): number => {
    try {
        const key = getLocalProgressKey(lessonId)
        if (!key) return 0
        const stored = localStorage.getItem(key)
        return stored ? parseFloat(stored) : 0
    } catch (e) {
        return 0
    }
}

// Helper: Save to Local Storage
const saveLocalProgress = (lessonId: number, time: number) => {
    try {
        const key = getLocalProgressKey(lessonId)
        if (key) {
           localStorage.setItem(key, time.toString())
        }
    } catch (e) {
        // Ignore storage errors
    }
}

const onVideoMetadataLoaded = () => {
   if (videoRef.value) {
       // Bind Media Preferences (Volume/Mute)
       applyTo(videoRef.value)

       // Resume playback if we have a saved position
       if (initialSeekTime.value > 0) {
           // Ensure we don't seek past duration
           const seekTo = Math.min(initialSeekTime.value, videoRef.value.duration || Infinity)
           videoRef.value.currentTime = seekTo
       }
   }
}

const togglePlay = () => {
  if (!videoRef.value) return
  if (isPlaying.value) videoRef.value.pause()
  else videoRef.value.play()
  isPlaying.value = !isPlaying.value
}

const isCompleting = ref(false) // Flag to prevent race conditions during completion

// -----------------------------------------------------
// ROBUST PROGRESS SAVING SYSTEM (Hybrid: Local + Server)
// -----------------------------------------------------

// Main Server Save Function
const performSaveProgress = async (force: boolean = false, keepalive: boolean = false) => {
    const lesson = currentLesson.value
    if (!videoRef.value || !lesson || lesson.type !== 'VIDEO') return
    if (!lesson.progress) return

    // 1. Completed Guard: Stop everything if already completed
    if (lesson.progress.is_completed) return

    // 2. Race Condition Guard: Stop if currently completing
    if (isCompleting.value) return

    const now = Date.now()
    const maxSec = Math.floor(maxWatchedTime.value) // Use max watched time
    const durationSec = Math.floor(videoRef.value.duration || 0)

    // 3. Monotonic Check: Don't save if progress hasn't increased (unless forced)
    if (!force && maxSec <= lastSavedTime.value) return
    
    // 4. Throttle Check: Server Throttle (15 seconds)
    if (!force && (now - lastSavedTimestamp.value < 15000)) return

    // Prepare for Save
    lastSavedTime.value = maxSec 
    lastSavedTimestamp.value = now

    // Check if this save might complete the lesson (e.g. > 90% or forced end)
    const isFinishing = force || (durationSec > 0 && maxSec >= durationSec * 0.9)
    
    if (isFinishing) {
        isCompleting.value = true
    }

    try {
        const res = await saveVideoProgress(lesson.id, maxSec, durationSec, keepalive)
        
        // Handle Completion Response
        if (res.success && res.data?.is_completed) {
             markLessonAsCompletedLocally(lesson.id)
             if (lesson.progress) lesson.progress.is_completed = true
        }
    } catch (err) {
        console.error('Save progress failed', err)
    } finally {
        if (isFinishing) {
            isCompleting.value = false
        }
    }
}

// Helper to update Sidebar UI
const markLessonAsCompletedLocally = (lessonId: number) => {
    if (courseData.value) {
        for (const chapter of courseData.value.chapters) {
            const lesson = chapter.lessons.find((l: any) => l.id === lessonId)
            if (lesson) {
                // Compatible with API structure
                lesson.is_completed = true
                if (!lesson.progress) lesson.progress = {}
                lesson.progress.is_completed = true
                break
            }
        }
    }
}

const updateProgress = () => {
  if (!videoRef.value) return
  
  // UI Update
  currentTime.value = videoRef.value.currentTime
  duration.value = videoRef.value.duration
  videoProgress.value = (currentTime.value / duration.value) * 100
  
  // Update Monotonic Progress
  if (currentTime.value > maxWatchedTime.value) {
      maxWatchedTime.value = currentTime.value
  }
  
  // Logic: Periodic Save 
  if (isPlaying.value && currentLesson.value?.id) {
      const now = Date.now()
      
      // 1. Local Save Throttle (5 seconds)
      if (now - lastLocalSaveTimestamp.value > 5000) {
          saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
          lastLocalSaveTimestamp.value = now
      }
      
      // 2. Server Save Throttle (handled inside performSaveProgress)
      performSaveProgress(false, false)
  }
}

// Volume Controls Logic replaced by useMediaPrefs
const volumeIcon = computed(() => {
    if (isMuted.value || volume.value === 0) return 'volume_off'
    if (volume.value < 0.5) return 'volume_down'
    return 'volume_up'
})

const handleToggleMute = () => {
    setMuted(!isMuted.value)
}

const handleVolumeChange = (val: any) => {
    const newVol = typeof val === 'number' ? val : Number(val.target.value)
    setVolume(newVol)
}

const videoSrc = computed(() => {
  if (!currentLesson.value) return ''
  // Use explicit video_url from API first
  if (currentLesson.value.video_url) return currentLesson.value.video_url
  
  // Fallback (deprecated logic, but keeping just in case)
  const content = getLocalizedText(currentLesson.value.content)
  if (content && (content.startsWith('http') || content.startsWith('/')) && !content.includes(' ')) {
    return content
  }
  return ''
})

// ==========================================
// 3. ระบบบันทึกความคืบหน้า (Progress Tracking)
// ==========================================
// บันทึกอัตโนมัติทุกๆ 10 วินาทีเมื่อเล่นวิดีโอ

// Event Listeners for Robustness
onMounted(() => {
    // Page/Tab Visibility Logic
    if (import.meta.client) {
        document.addEventListener('visibilitychange', handleVisibilityChange)
        window.addEventListener('pagehide', handlePageHide)
    }
})

onBeforeUnmount(() => {
    if (import.meta.client) {
        document.removeEventListener('visibilitychange', handleVisibilityChange)
        window.removeEventListener('pagehide', handlePageHide)
    }
    
    // Final save attempt when component destroys
    if (currentLesson.value?.id) {
       saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
    }
    // Only save if not completed
    if (currentLesson.value?.progress && !currentLesson.value.progress.is_completed) {
        performSaveProgress(true, true) 
    }
})

const handleVisibilityChange = () => {
    if (document.hidden) {

        if (currentLesson.value?.id) {
           saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
        }
        performSaveProgress(true, true) // Force save with keepalive
    }
}

const handlePageHide = () => {
    // Triggered on page refresh, close tab, or navigation
    if (currentLesson.value?.id) {
       saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
    }
    performSaveProgress(true, true)
}

// Watch Video Events
watch(isPlaying, (playing) => {
    if (!playing) {
        // Paused: Save immediately
        if (currentLesson.value?.id) {
           saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
        }
        performSaveProgress(true, false)
    }
})

// เมื่อวิดีโอจบ ให้บันทึกว่าเรียนจบ (Complete)

const onVideoEnded = async () => {
    isPlaying.value = false
    
    // Safety check BEFORE trying to save
    const lesson = currentLesson.value
    if (!lesson || !lesson.progress || lesson.progress.is_completed || isCompleting.value) return

    // Force save progress at 100%
    await performSaveProgress(true, false)
    
    // Double check completion state
    if (currentLesson.value && !currentLesson.value.progress?.is_completed) {
         markLessonAsCompletedLocally(currentLesson.value.id)
    }
}

const formatTime = (time: number) => {
  const m = Math.floor(time / 60)
  const s = Math.floor(time % 60)
  return `${m}:${s.toString().padStart(2, '0')}`
}

const currentTimeDisplay = computed(() => formatTime(currentTime.value))
const durationDisplay = computed(() => formatTime(duration.value || 0))

const seek = (e: MouseEvent) => {
  if (!videoRef.value) return
  const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
  const percent = (e.clientX - rect.left) / rect.width
  videoRef.value.currentTime = percent * videoRef.value.duration
}

onMounted(() => {
  loadCourseData()
})

onBeforeUnmount(() => {

})
</script>

<template>
  <q-layout view="hHh LpR lFf" class="bg-[var(--bg-body)] text-[var(--text-main)]">
    
    <!-- Header -->
    <q-header bordered class="bg-[var(--bg-surface)] border-b border-gray-200 dark:border-white/5 text-[var(--text-main)] h-14">
      <q-toolbar>
        <q-btn flat round dense icon="menu" class="lg:hidden mr-2 text-slate-900 dark:text-white" @click="toggleSidebar" />
        
        <NuxtLink 
          to="/dashboard/my-courses"
          class="inline-flex items-center gap-2 text-slate-900 dark:text-white hover:text-blue-600 dark:hover:text-blue-300 transition-all font-black text-sm md:text-base group mr-4"
        >
          <q-icon name="arrow_back" size="24px" class="transition-transform group-hover:-translate-x-1" />
          <span>{{ $t('classroom.backToDashboard') }}</span>
        </NuxtLink>
        
        <q-toolbar-title class="text-base font-bold text-center lg:text-left truncate text-slate-900 dark:text-white">
           {{ courseData ? getLocalizedText(courseData.course.title) : $t('classroom.loadingTitle') }}
        </q-toolbar-title>

        <div class="flex items-center gap-2">
           <!-- Right actions -->
        </div>
      </q-toolbar>
    </q-header>

    <!-- Sidebar (Curriculum) -->
    <q-drawer
      v-model="sidebarOpen"
      show-if-above
      bordered
      side="left"
      :width="320"
      :breakpoint="1024"
      class="bg-[var(--bg-surface)]"
      content-class="bg-[var(--bg-surface)]"
    >
      <div v-if="courseData" class="h-full scroll">
         <q-list class="pb-10">
            <!-- Announcements Sidebar Item -->
             <q-item 
                clickable 
                v-ripple 
                @click="handleOpenAnnouncements" 
                class="bg-blue-50 dark:bg-blue-900/10 border-b border-blue-100 dark:border-blue-900/20"
             >
                <q-item-section>
                   <q-item-label class="font-bold text-slate-800 dark:text-blue-200 text-sm pl-2">
                       {{ $t('classroom.announcements', 'ประกาศในคอร์ส') }}
                   </q-item-label>
                </q-item-section>
                <q-item-section side v-if="hasUnreadAnnouncements">
                    <q-badge color="red" rounded label="New" />
                </q-item-section>
             </q-item>

            <template v-for="chapter in courseData.chapters" :key="chapter.id">
              <q-item-label header class="bg-slate-100 dark:bg-slate-800 text-[var(--text-main)] font-bold sticky top-0 z-10 border-b dark:border-white/5 text-sm py-4">
                 {{ getLocalizedText(chapter.title) }}
              </q-item-label>

              <q-item
                v-for="lesson in chapter.lessons"
                :key="lesson.id"
                clickable
                v-ripple
                :active="currentLesson?.id === lesson.id"
                active-class="bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-200 font-medium"
                class="border-b border-gray-50 dark:border-white/5"
                @click="!lesson.is_locked && handleLessonSelect(lesson.id)"
                :disable="lesson.is_locked"
              >
                <q-item-section avatar v-if="lesson.is_locked">
                  <q-icon name="lock" size="xs" color="grey" />
                </q-item-section>
                
                <q-item-section>
                  <q-item-label class="text-sm md:text-base line-clamp-2 text-[var(--text-main)]">
                    {{ getLocalizedText(lesson.title) }}
                  </q-item-label>
                </q-item-section>

                <q-item-section side>
                   <q-icon v-if="lesson.is_completed" name="check_circle" color="positive" size="xs" />
                   <q-icon v-else-if="currentLesson?.id === lesson.id" name="play_circle" color="primary" size="xs" />
                   <q-icon v-else name="radio_button_unchecked" color="grey-4" size="xs" />
                </q-item-section>
              </q-item>
            </template>
         </q-list>
      </div>
      <div v-else-if="isLoading" class="p-6 text-center text-slate-500">
         <q-spinner color="primary" size="2em" />
         <div class="mt-2 text-xs">{{ $t('classroom.loadingCurriculum') }}</div>
      </div>
    </q-drawer>

    <!-- Main Content -->
    <q-page-container class="bg-white dark:bg-slate-900">
      <q-page class="flex flex-col h-full bg-slate-50 dark:bg-[#0B0F1A]">
         <!-- Video Player & Content Area -->
         <div class="w-full max-w-7xl mx-auto p-4 md:p-6 flex-grow">
            <!-- Video Player -->
            <div v-if="currentLesson && videoSrc" class="bg-black rounded-xl overflow-hidden shadow-2xl mb-6 aspect-video relative group ring-1 ring-white/10">
               <video
                 ref="videoRef"
                 :src="videoSrc"
                 class="w-full h-full object-contain"
                 @click="togglePlay"
                 @timeupdate="updateProgress"
                 @loadedmetadata="onVideoMetadataLoaded"
                 @ended="onVideoEnded"
               />
               
               <!-- Custom Controls Overlay (Simplified) -->
               <div class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 via-black/40 to-transparent transition-opacity opacity-0 group-hover:opacity-100">
                  <div class="flex items-center gap-4 text-white">
                     <q-btn flat round dense :icon="isPlaying ? 'pause' : 'play_arrow'" @click.stop="togglePlay" />
                     <div class="relative flex-grow h-1.5 bg-white/20 rounded-full cursor-pointer group/progress overflow-hidden" @click="seek">
                        <div class="absolute top-0 left-0 h-full bg-blue-500 rounded-full group-hover/progress:bg-blue-400 transition-all shadow-[0_0_10px_rgba(59,130,246,0.5)]" :style="{ width: videoProgress + '%' }"></div>
                     </div>
                     <span class="text-xs font-mono font-medium opacity-90">{{ currentTimeDisplay }} / {{ durationDisplay }}</span>
                     
                     <!-- Volume Control -->
                     <div class="flex items-center gap-2 group/volume">
                        <q-btn flat round dense :icon="volumeIcon" @click.stop="handleToggleMute" color="white" />
                        <div class="w-0 group-hover/volume:w-20 overflow-hidden transition-all duration-300 flex items-center">
                            <input 
                                type="range" 
                                min="0" 
                                max="1" 
                                step="0.1" 
                                :value="volume" 
                                @input="handleVolumeChange"
                                class="w-20 h-1 bg-white/30 rounded-lg appearance-none cursor-pointer accent-blue-500"
                            />
                        </div>
                     </div>
                  </div>
               </div>
            </div>
            
             <!-- Lesson Info -->
             <div v-if="currentLesson" class="bg-[var(--bg-surface)] p-6 md:p-8 rounded-3xl shadow-sm border border-[var(--border-color)]">
                <!-- ใช้สีจากตัวแปรกลาง: จะแยกโหมดให้อัตโนมัติ (สว่าง=ดำ / มืด=ขาว) -->
                <div class="flex items-start justify-between gap-4 mb-4">
                    <h1 class="text-2xl md:text-3xl font-bold text-slate-900 dark:text-white leading-tight font-display">{{ getLocalizedText(currentLesson.title) }}</h1>
                </div>
                
                <p class="text-slate-600 dark:text-slate-400 text-base md:text-lg leading-relaxed mb-6" v-if="currentLesson.description">{{ getLocalizedText(currentLesson.description) }}</p>
                
                <!-- Lesson Content Area (Text/HTML) -->
                <div v-if="currentLesson.type === 'QUIZ'" class="p-8 bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-slate-800 dark:to-slate-800/50 rounded-2xl border border-blue-100 dark:border-white/5 text-center">
                    <div class="bg-white dark:bg-slate-700 w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-4 shadow-sm text-blue-500 dark:text-blue-300">
                        <q-icon name="quiz" size="40px" />
                    </div>
                    <h2 class="text-xl font-bold mb-2 text-slate-900 dark:text-white">{{ $t('quiz.startTitle', 'แบบทดสอบท้ายบทเรียน') }}</h2>
                    <p class="text-slate-500 dark:text-slate-400 mb-6 max-w-md mx-auto">{{ getLocalizedText(currentLesson.quiz?.description || currentLesson.description) }}</p>
                    
                    <div class="flex justify-center flex-wrap gap-3 text-sm text-slate-600 dark:text-slate-300 mb-8">
                         <span v-if="currentLesson.quiz?.questions?.length" class="px-3 py-1 bg-white dark:bg-slate-900 rounded-full border border-gray-200 dark:border-white/10 shadow-sm flex items-center gap-1.5"><q-icon name="format_list_numbered" size="14px" class="text-blue-500" /> {{ currentLesson.quiz.questions.length }} ข้อ</span>
                         <span v-if="currentLesson.quiz?.time_limit" class="px-3 py-1 bg-white dark:bg-slate-900 rounded-full border border-gray-200 dark:border-white/10 shadow-sm flex items-center gap-1.5"><q-icon name="schedule" size="14px" class="text-orange-500" /> {{ currentLesson.quiz.time_limit }} นาที</span>
                    </div>

                    <q-btn 
                        class="bg-blue-600 text-white shadow-lg shadow-blue-600/30 hover:shadow-blue-600/50 transition-all font-bold px-8"
                        size="lg" 
                        rounded 
                        no-caps
                        :label="$t('quiz.startBtn', 'เริ่มทำแบบทดสอบ')" 
                        icon="play_arrow"
                        @click="$router.push(`/classroom/quiz?course_id=${courseId}&lesson_id=${currentLesson.id}`)"
                    />
                </div>
                <div v-else-if="currentLesson.content" class="prose prose-lg dark:prose-invert max-w-none p-6 md:p-8 bg-gray-50 dark:bg-slate-800/50 rounded-2xl border border-gray-100 dark:border-white/5">
                    <div v-html="getLocalizedText(currentLesson.content)" class="leading-relaxed text-slate-800 dark:text-slate-200"></div>
                </div>

                <!-- Attachments Section -->
                <div v-if="currentLesson.attachments && currentLesson.attachments.length > 0" class="mt-8 pt-6 border-t border-gray-100 dark:border-white/5">
                    <h3 class="text-lg font-bold mb-4 text-slate-900 dark:text-white flex items-center gap-2">
                        <div class="w-8 h-8 rounded-lg bg-orange-100 dark:bg-orange-900/30 text-orange-600 flex items-center justify-center">
                            <q-icon name="attach_file" size="18px" />
                        </div>
                        {{ $t('classroom.attachments') || 'เอกสารประกอบการเรียน' }}
                    </h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <a 
                            v-for="file in currentLesson.attachments" 
                            :key="file.file_name"
                            :href="file.presigned_url"
                            target="_blank"
                            class="flex items-center gap-4 p-4 rounded-xl border border-slate-200 dark:!border-white/10 bg-white dark:!bg-slate-800 hover:border-blue-300 dark:hover:border-blue-700 hover:shadow-md transition-all group relative overflow-hidden"
                        >
                            <div class="w-12 h-12 rounded-xl bg-red-50 dark:bg-red-900/20 text-red-500 flex items-center justify-center flex-shrink-0">
                                <q-icon name="picture_as_pdf" size="24px" />
                            </div>
                            <div class="flex-1 min-w-0 z-10">
                                <div class="font-bold text-slate-900 dark:text-slate-200 truncate group-hover:text-blue-600 transition-colors text-sm md:text-base">
                                    {{ file.file_name }}
                                </div>
                                <div class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">
                                    {{ (file.file_size / 1024 / 1024).toFixed(2) }} MB
                                </div>
                            </div>
                            <div class="absolute inset-0 bg-blue-50/50 dark:bg-blue-900/10 opacity-0 group-hover:opacity-100 transition-opacity"></div>
                            <q-icon name="download" class="text-slate-300 group-hover:text-blue-500 z-10" />
                        </a>
                    </div>
                </div>
            </div>
         </div>
      </q-page>
    </q-page-container>

    <!-- Announcements Modal -->
    <q-dialog v-model="showAnnouncementsModal" backdrop-filter="blur(4px)">
       <q-card class="min-w-[320px] md:min-w-[600px] rounded-3xl overflow-hidden bg-white dark:bg-slate-900 shadow-2xl">
          <q-card-section class="bg-white dark:bg-slate-900 border-b border-gray-100 dark:border-white/5 p-5 flex items-center justify-between sticky top-0 z-10">
             <div>
                 <div class="text-xl font-bold flex items-center gap-2 text-slate-900 dark:text-white">
                    <div class="w-10 h-10 rounded-full bg-blue-50 dark:bg-blue-900/30 text-primary flex items-center justify-center">
                        <q-icon name="campaign" size="22px" />
                    </div>
                    {{ $t('classroom.announcements', 'ประกาศในคอร์สเรียน') }}
                 </div>
                 <div class="text-xs text-slate-500 dark:text-slate-400 ml-12 mt-1">{{ announcements.length }} รายการ</div>
             </div>
             <q-btn icon="close" flat round dense v-close-popup class="text-slate-400 hover:text-slate-700 dark:hover:text-white bg-slate-50 dark:bg-slate-800" />
          </q-card-section>

          <q-card-section class="p-0 scroll max-h-[70vh] bg-slate-50 dark:bg-[#0B0F1A]">
              <div v-if="announcements.length > 0" class="p-4 space-y-4">
                     <div 
                        v-for="(ann, index) in announcements" 
                        :key="index" 
                        class="p-5 rounded-2xl bg-white dark:bg-slate-800 shadow-sm border border-gray-200 dark:border-white/5 transition-all hover:shadow-md relative overflow-hidden group"
                        :class="{'ring-2 ring-orange-200 dark:ring-orange-900/40 bg-orange-50/50 dark:bg-orange-900/10': ann.is_pinned}"
                     >
                        <!-- Pinned Banner -->
                        <div v-if="ann.is_pinned" class="absolute top-0 right-0 p-3">
                            <q-icon name="push_pin" color="orange" size="18px" class="transform rotate-45" />
                        </div>

                        <div class="flex items-start gap-4 mb-3">
                           <q-avatar 
                                :color="ann.is_pinned ? 'orange-100' : 'blue-50'" 
                                :text-color="ann.is_pinned ? 'orange-700' : 'blue-700'" 
                                size="42px" 
                                font-size="20px"
                                class="shadow-sm"
                            >
                                <span class="font-bold">{{ (getLocalizedText(ann.title) || 'A').charAt(0) }}</span>
                            </q-avatar>
                           <div class="flex-1">
                              <div class="font-bold text-lg text-slate-900 dark:text-white leading-tight pr-8 capitalize font-display">
                                {{ getLocalizedText(ann.title) || 'ประกาศ' }}
                              </div>
                              <div class="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-2 mt-1.5">
                                  <span class="flex items-center gap-1 bg-slate-100 dark:bg-slate-700 px-2 py-0.5 rounded-md">
                                    <q-icon name="today" size="12px" />
                                    {{ new Date(ann.created_at || Date.now()).toLocaleDateString('th-TH', { day: 'numeric', month: 'short', year: 'numeric' }) }}
                                  </span>
                                  <span class="flex items-center gap-1 bg-slate-100 dark:bg-slate-700 px-2 py-0.5 rounded-md">
                                    <q-icon name="access_time" size="12px" />
                                    {{ new Date(ann.created_at || Date.now()).toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' }) }}
                                  </span>
                              </div>
                           </div>
                        </div>
                        
                        <div class="text-slate-600 dark:text-slate-300 text-sm leading-relaxed whitespace-pre-line pl-[58px] mb-4">
                           {{ getLocalizedText(ann.content) }}
                        </div>

                        <!-- Attachments in Announcement -->
                        <div v-if="ann.attachments && ann.attachments.length > 0" class="pl-[58px] mt-4 pt-4 border-t border-gray-100 dark:border-white/5">
                            <div class="text-xs font-bold text-slate-500 dark:text-slate-400 mb-3 flex items-center gap-1.5 uppercase tracking-wider">
                                <q-icon name="attach_file" /> {{ $t('classroom.attachments') || 'Attachments' }}
                            </div>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                <a 
                                    v-for="file in ann.attachments" 
                                    :key="file.id"
                                    :href="file.presigned_url"
                                    target="_blank"
                                    class="flex items-center gap-3 p-3 rounded-xl bg-gray-50 dark:bg-slate-700/50 hover:bg-blue-50 dark:hover:bg-blue-900/20 text-sm text-slate-700 dark:text-slate-200 border border-gray-200 dark:border-white/10 hover:border-blue-200 dark:hover:border-blue-700/50 transition-all group/file"
                                >
                                    <div class="w-8 h-8 rounded-lg bg-white dark:bg-slate-600 flex items-center justify-center shadow-sm text-red-500">
                                        <q-icon name="description" size="18px" />
                                    </div>
                                    <span class="truncate flex-1 font-medium">{{ file.file_name }}</span>
                                    <q-icon name="download" size="14px" class="text-slate-400 group-hover/file:text-blue-500" />
                                </a>
                            </div>
                        </div>
                     </div>
              </div>
              <div v-else class="flex flex-col items-center justify-center p-12 text-slate-400 min-h-[300px]">
                 <div class="w-24 h-24 bg-slate-100 dark:bg-slate-800 rounded-full mb-6 flex items-center justify-center">
                    <q-icon name="notifications_off" size="3rem" class="text-slate-300 dark:text-slate-600" />
                 </div>
                 <div class="text-base font-medium text-slate-600 dark:text-slate-400">{{ $t('classroom.noAnnouncements', 'ไม่มีประกาศในขณะนี้') }}</div>
                 <div class="text-sm text-slate-400 mt-2">โพสต์ใหม่ๆ จากผู้สอนจะปรากฏที่นี่</div>
              </div>
          </q-card-section>
       </q-card>
    </q-dialog>

  </q-layout>
</template>

<style>
.mobile-hide-label .q-btn__content span {
  display: none;
}
@media (min-width: 768px) {
  .mobile-hide-label .q-btn__content span {
    display: inline;
    margin-left: 8px;
  }
}
</style>
