<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, markLessonComplete } = 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
  // Reset states before loading new course
  courseData.value = null
  currentLesson.value = null
  announcements.value = []
  
  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 & unload component to force reset
  isPlaying.value = false
  videoProgress.value = 0
  currentTime.value = 0
  currentLesson.value = null // This will unmount VideoPlayer and hide content
  
  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
      
      // Initialize progress object if missing (Critical for New Users)
      if (!currentLesson.value.progress) {
          currentLesson.value.progress = {}
      }
      
      // 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 Player Ref (Component)
const videoPlayerComp = ref(null)

// 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
const currentDuration = ref(0) // Track duration for save logic

// 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
    }
}

// Handler: Video Time Update (from Component)
const handleVideoTimeUpdate = (cTime: number, dur: number) => {
  currentDuration.value = dur || 0
  
  // Update Monotonic Progress
  if (cTime > maxWatchedTime.value) {
      maxWatchedTime.value = cTime
  }
  
  // Logic: Periodic Save 
  if (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)
      // Note: We don't check isPlaying here because if time is updating, it IS playing.
      performSaveProgress(false, false)
  }
}

const onVideoMetadataLoaded = (duration: number) => {
    if (duration > 0) {
        currentDuration.value = duration
    }
}

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 (!lesson || lesson.type !== 'VIDEO') return
    
    // Ensure progress object exists
    if (!lesson.progress) lesson.progress = {}

    // 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(currentDuration.value || 0)

    // 3. Monotonic Check: Allow saving 0 if it's the very first save (lastSavedTime is -1)
    if (!force) {
        if (lastSavedTime.value === -1) {
            // First time save: allow 0 or more
            if (maxSec < 0) return 
        } else if (maxSec <= lastSavedTime.value) {
            // Subsequent saves: must be greater than last saved
            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. 100% or forced end)
    const isFinishing = force || (durationSec > 0 && maxSec >= durationSec)
    
    if (isFinishing) {
        isCompleting.value = true
    }

    try {
        const res = await saveVideoProgress(lesson.id, maxSec, durationSec, keepalive)
        
        // Handle Completion (Rely on Backend's auto-complete 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 videoSrc = computed(() => {
  if (!currentLesson.value) return ''
  let url = ''
  
  // Use explicit video_url from API first
  if (currentLesson.value.video_url) {
    url = currentLesson.value.video_url
  } else {
    // Fallback (deprecated logic)
    const content = getLocalizedText(currentLesson.value.content)
    if (content && (content.startsWith('http') || content.startsWith('/')) && !content.includes(' ')) {
      url = content
    }
  }

  if (!url) return ''

  // Support Resume for YouTube
  const isYoutube = url.toLowerCase().includes('youtube.com') || url.toLowerCase().includes('youtu.be')
  if (isYoutube && initialSeekTime.value > 0) {
      const separator = url.includes('?') ? '&' : '?'
      return `${url}${separator}t=${Math.floor(initialSeekTime.value)}`
  }
  
  return url
})

// เมื่อวิดีโอจบ ให้บันทึกว่าเรียนจบ (Complete)
const onVideoEnded = async () => {
    // Safety check BEFORE trying to save
    const lesson = currentLesson.value
    if (!lesson || !lesson.progress || lesson.progress.is_completed || isCompleting.value) return

    isCompleting.value = true
    try {
        // 1. Force save progress at 100%
        // This will trigger the backend's auto-complete logic
        await performSaveProgress(true, false)
    } catch (err) {
        console.error('Failed to save progress on end:', err)
    } finally {
        isCompleting.value = false
    }
}

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

onBeforeUnmount(() => {
  // Clear state when leaving the page to ensure fresh start on return
  courseData.value = null
  currentLesson.value = null
})
</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" />
        
        <a 
          href="/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 no-underline"
        >
          <q-icon name="arrow_back" size="24px" class="transition-transform group-hover:-translate-x-1" />
          <span>{{ $t('classroom.backToDashboard') }}</span>
        </a>
        
        <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) -->
    <!-- Sidebar (Curriculum) -->
    <CurriculumSidebar
      v-model="sidebarOpen"
      :courseData="courseData"
      :currentLessonId="currentLesson?.id"
      :isLoading="isLoading"
      :hasUnreadAnnouncements="hasUnreadAnnouncements"
      @select-lesson="handleLessonSelect"
      @open-announcements="handleOpenAnnouncements"
    />

    <!-- 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 -->
            <VideoPlayer
               v-if="currentLesson && videoSrc && !isLessonLoading"
               ref="videoPlayerComp"
               :src="videoSrc"
               :initialSeekTime="initialSeekTime"
               @timeupdate="handleVideoTimeUpdate"
               @ended="onVideoEnded"
               @loadedmetadata="(d: number) => onVideoMetadataLoaded(d)"
            />
            
            <!-- Skeleton Loader for Video/Content -->
            <div v-if="isLessonLoading" class="aspect-video bg-slate-200 dark:bg-slate-800 rounded-2xl animate-pulse flex items-center justify-center mb-6 overflow-hidden relative">
                <div class="absolute inset-0 bg-gradient-to-br from-slate-200 to-slate-300 dark:from-slate-700 dark:to-slate-800 opacity-50"></div>
                <div class="z-10 flex flex-col items-center">
                    <q-spinner size="4rem" color="primary" :thickness="4" />
                    <p class="mt-4 text-slate-500 dark:text-slate-400 font-bold animate-bounce">{{ $t('common.loading') }}...</p>
                </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 -->
    <AnnouncementModal
      v-model="showAnnouncementsModal"
      :announcements="announcements"
    />

  </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>
