﻿<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 { t } = useI18n()
const { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, markLessonComplete, checkLessonAccess } = useCourse()

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

// ==========================================
// 1. ตัวแปร State (สถานะของ UI)
// ==========================================
// courseData: เก็บข้อมูลโครงสร้างคอร์ส (บทเรียนต่างๆ)
const courseData = ref<any>(null)
// 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)
const saveProgressInterval = ref<any>(null) // ตัวแปรเก็บ setInterval สำหรับบันทึกความคืบหน้าอัตโนมัติ

// 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)
        }
      }
    }
  } 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) {
        alert(t('classroom.notAvailable'))
        isLessonLoading.value = false
        return
    }

    const res = await fetchLessonContent(courseId.value, lessonId)
    if (res.success) {
      currentLesson.value = res.data
      
      // Restore progress if available
      if (res.progress) {
          // Wait for video metadata to load usually, but set state
          // We might set currentTime once metadata loaded
           if (res.progress.video_progress_seconds > 0) {
               currentTime.value = res.progress.video_progress_seconds
               // We will apply this to videoRef locally when it is ready
           }
      }
    }
  } catch (error) {
    console.error('Error loading lesson:', error)
  } finally {
    isLessonLoading.value = false
  }
}

const onVideoMetadataLoaded = () => {
   if (videoRef.value && currentLesson.value) {
       // Restore time if needed
       if (currentTime.value > 0) {
           videoRef.value.currentTime = currentTime.value
       }
   }
}

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

const updateProgress = () => {
  if (!videoRef.value) return
  currentTime.value = videoRef.value.currentTime
  duration.value = videoRef.value.duration
  videoProgress.value = (currentTime.value / duration.value) * 100
  
  // Throttle save progress logic is handled in watcher or separate interval usually, 
  // but let's check if we should save periodically here for simplicity or use specific events
}

const videoSrc = computed(() => {
  if (!currentLesson.value) return ''
  const content = getLocalizedText(currentLesson.value.content)
  // Check if content looks like a URL (starts with http/https or /)
  // And doesn't contain obvious text indicators
  if (content && (content.startsWith('http') || content.startsWith('/')) && !content.includes(' ')) {
    return content
  }
  return ''
})

// ==========================================
// 3. ระบบบันทึกความคืบหน้า (Progress Tracking)
// ==========================================
// บันทึกอัตโนมัติทุกๆ 10 วินาทีเมื่อเล่นวิดีโอ
watch(() => isPlaying.value, (playing) => {
    if (playing) {
        saveProgressInterval.value = setInterval(() => {
            if (videoRef.value && currentLesson.value) {
                // Send integers to avoid potential backend float issues
                saveVideoProgress(
                    currentLesson.value.id, 
                    Math.floor(videoRef.value.currentTime), 
                    Math.floor(videoRef.value.duration || 0)
                )
            }
        }, 10000) // Every 10 seconds
    } else {
        clearInterval(saveProgressInterval.value)
         // Save one last time on pause
        if (videoRef.value && currentLesson.value) {
            saveVideoProgress(
                currentLesson.value.id, 
                Math.floor(videoRef.value.currentTime), 
                Math.floor(videoRef.value.duration || 0)
            )
        }
    }
})

// เมื่อวิดีโอจบ ให้บันทึกว่าเรียนจบ (Complete)
const onVideoEnded = async () => {
    isPlaying.value = false
    if (currentLesson.value) {
        await markLessonComplete(courseId.value, currentLesson.value.id)
        // โหลดข้อมูลคอร์สใหม่เพื่ออัปเดตสถานะติ๊กถูกด้านข้าง
        await loadCourseData()
        
        // Auto play next logic could go here
    }
}

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(() => {
    clearInterval(saveProgressInterval.value)
})
</script>

<template>
  <q-layout view="hHh LpR lFf" class="bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100 font-inter">
    
    <!-- Header -->
    <q-header bordered class="bg-white dark:bg-slate-900 border-b border-gray-200 dark:border-white/5 text-slate-900 dark:text-white h-14">
      <q-toolbar>
        <q-btn flat round dense icon="menu" class="lg:hidden mr-2" @click="toggleSidebar" />
        
        <q-btn flat dense no-caps icon="arrow_back" :label="$t('classroom.backToDashboard')" to="/dashboard/my-courses" class="text-slate-600 dark:text-slate-300 mobile-hide-label" />
        
        <q-toolbar-title class="text-sm font-bold text-center lg:text-left truncate">
           {{ 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-white dark:bg-slate-900"
    >
      <div v-if="courseData" class="h-full scroll">
         <q-list class="pb-10">
            <template v-for="chapter in courseData.chapters" :key="chapter.id">
              <q-item-label header class="bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 font-bold sticky top-0 z-10 border-b dark:border-white/5 text-xs py-3">
                 {{ 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-xs md:text-sm line-clamp-2">
                    {{ getLocalizedText(lesson.title) }}
                  </q-item-label>
                </q-item-section>

                <q-item-section side>
                   <q-icon v-if="lesson.progress?.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" class="bg-black rounded-xl overflow-hidden shadow-lg mb-6 aspect-video relative group">
               <video
                 ref="videoRef"
                 v-if="videoSrc"
                 :src="videoSrc"
                 class="w-full h-full object-contain"
                 @click="togglePlay"
                 @timeupdate="updateProgress"
                 @loadedmetadata="onVideoMetadataLoaded"
                 @ended="onVideoEnded"
               />
               <div v-else class="flex items-center justify-center h-full text-white/50 bg-slate-900">
                  <div class="text-center">
                    <q-icon name="article" size="xl" />
                    <p class="mt-2">{{ $t('classroom.readingMaterial') }}</p>
                  </div>
               </div>
               
               <!-- Custom Controls Overlay (Simplified) -->
               <div class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 to-transparent transition-opacity opacity-0 group-hover:opacity-100" v-if="videoSrc">
                  <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 bg-white/30 rounded cursor-pointer" @click="seek">
                        <div class="absolute top-0 left-0 h-full bg-blue-500 rounded" :style="{ width: videoProgress + '%' }"></div>
                     </div>
                     <span class="text-xs font-mono">{{ currentTimeDisplay }} / {{ durationDisplay }}</span>
                  </div>
               </div>
            </div>
            
            <!-- Lesson Info -->
             <div v-if="currentLesson" class="bg-white dark:bg-slate-800 p-6 rounded-2xl shadow-sm border border-slate-100 dark:border-white/5">
                <h1 class="text-2xl font-bold mb-2">{{ getLocalizedText(currentLesson.title) }}</h1>
                <p class="text-slate-500 dark:text-slate-400" v-if="currentLesson.description">{{ currentLesson.description }}</p>
                
                <!-- Lesson Content Area -->
                <div v-if="!videoSrc && currentLesson.content" class="mt-6 prose dark:prose-invert max-w-none p-6 bg-slate-50 dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-white/5">
                    <div v-html="getLocalizedText(currentLesson.content)"></div>
                </div>
            </div>
         </div>
      </q-page>
    </q-page-container>

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