<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 { 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 (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('บทเรียนนี้ยังไม่เปิดให้เข้าชม')
        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>
  <div class="learning-shell font-main antialiased selection:bg-blue-500/30 dark:!bg-[#0F172A] dark:!text-slate-200 transition-colors">
    <!-- Header: Custom top bar for learning context -->
    <header class="learning-header px-2 md:px-4 h-14 md:h-[56px] border-b border-slate-200 dark:border-white/5 flex items-center justify-between gap-2 md:gap-4 dark:!bg-slate-800 transition-colors">
      <div class="flex items-center gap-1 md:gap-6 min-w-0 flex-1">
        <!-- Mobile Sidebar Toggle -->
        <button class="md:hidden text-slate-900 dark:text-white p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-lg flex-shrink-0 transition-colors" @click="toggleSidebar">
          <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="M4 6h16M4 12h16M4 18h16" /></svg>
        </button>
        <!-- Back Navigation -->
        <NuxtLink to="/dashboard/my-courses" class="text-slate-700 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white transition-colors flex items-center gap-2 flex-shrink-0 p-2 md:p-0">
          <span class="text-lg md:text-base">←</span>
          <span class="hidden md:inline text-[11px] font-bold">กลับไปหน้าหลัก</span>
        </NuxtLink>
        <div class="w-[1px] h-4 bg-slate-200 dark:bg-white/10 hidden md:block flex-shrink-0"/>
        <h1 class="text-[13px] md:text-sm font-black text-slate-900 dark:text-white tracking-tight truncate min-w-0 pr-2">
            {{ courseData ? getLocalizedText(courseData.course.title) : 'กำลังโหลด...' }}
        </h1>
      </div>
      
      <!-- Right Header Actions (Progress) -->
      <div class="flex items-center gap-2 md:gap-10 pr-2 md:pr-0">
        <!-- Progress bar removed as it was static/mock data -->
      </div>
    </header>

    <!-- Sidebar: Course Curriculum list -->
    <aside class="learning-sidebar dark:!bg-gray-900 dark:!border-r-white/5 transition-colors" :class="{ 'open': sidebarOpen }">
      <div class="py-2" v-if="courseData">
         <!-- Chapters & Lessons List -->
         <div v-for="chapter in courseData.chapters" :key="chapter.id" class="mt-4">
            <div class="chapter-header px-4 py-2 dark:!bg-slate-900 dark:!text-white dark:!border-b-white/5">
                {{ getLocalizedText(chapter.title) }}
            </div>
            <div 
              v-for="lesson in chapter.lessons" 
              :key="lesson.id" 
              class="lesson-item px-4 dark:!text-slate-300 dark:!border-b-white/5 hover:dark:!bg-white/5 hover:dark:!text-white transition-colors"
              :class="{ 
                'active-lesson': currentLesson?.id === lesson.id,
                'completed': lesson.progress?.is_completed,
                'locked': lesson.is_locked
              }"
              @click="!lesson.is_locked && handleLessonSelect(lesson.id)"
            >
              <div class="flex items-center gap-2 overflow-hidden">
                  <span class="flex-shrink-0 text-slate-400 text-xs" v-if="lesson.is_locked">🔒</span>
                  <span class="text-[12px] font-medium tracking-tight truncate pr-4">
                      {{ getLocalizedText(lesson.title) }}
                  </span>
              </div>
              <span class="icon-status flex-shrink-0" :class="{ 'text-emerald-500': lesson.progress?.is_completed, 'text-blue-500': currentLesson?.id === lesson.id }">
                <span v-if="lesson.progress?.is_completed">✓</span>
                <span v-else-if="currentLesson?.id === lesson.id">▶</span>
              </span>
            </div>
         </div>
      </div>
      <div v-else-if="isLoading" class="p-6 text-center text-slate-500 text-sm">
          กำลังโหลดเนื้อหา...
      </div>
    </aside>

    <!-- Sidebar Overlay for mobile -->
    <div v-if="sidebarOpen" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-[85] md:hidden" @click="toggleSidebar"/>

   
  </div>
</template>

<style scoped>
.learning-shell {
    display: grid;
    grid-template-columns: 320px 1fr;
    grid-template-rows: 56px 1fr;
    height: 100vh;
    overflow: hidden;
    background: #ffffff;
    color: #1e293b;
    transition: background 0.2s, color 0.2s;
}

:global(.dark) .learning-shell {
    background: #0F172A;
    color: #F8FAFC;
}

.learning-header {
    grid-column: 1 / -1;
    background: #ffffff;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 100;
    transition: background 0.2s, border-color 0.2s;
}

:global(.dark) .learning-header {
    background: #1e293b;
    border-bottom-color: rgba(255, 255, 255, 0.05);
}

.learning-sidebar {
    grid-row: 2;
    grid-column: 1;
    background: #ffffff;
    border-right: 1px solid #e2e8f0;
    overflow-y: auto;
    z-index: 90;
    transition: background 0.2s, border-color 0.2s;
}

:global(.dark) .learning-sidebar {
    background: #111827;
    border-right-color: rgba(255, 255, 255, 0.05);
}

.main-container {
    grid-row: 2;
    grid-column: 2;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    background: #ffffff;
    transition: background 0.2s;
}

:global(.dark) .main-container {
    background: #0B0F1A;
}

@media (max-width: 1024px) {
    .main-container {
        grid-column: 1;
    }
}

.lesson-item {
    padding: 14px 24px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.2s;
    color: #000000;
    border-bottom: 1px solid #e2e8f0;
}
.lesson-item:hover { 
    background-color: #f1f5f9;
    color: #000000;
}

:global(.dark) .lesson-item {
    color: #e2e8f0;
    border-bottom-color: rgba(255, 255, 255, 0.01);
}

:global(.dark) .lesson-item:hover { 
    background-color: rgba(255, 255, 255, 0.03);
    color: #ffffff;
}

.active-tab { 
    background: rgba(59, 130, 246, 0.1); 
    color: #2563eb;
    font-weight: 700;
}
.active-lesson { 
    background-color: #f3f4f6; 
    color: #000000; 
    box-shadow: inset 4px 0 0 #3B82F6;
}

:global(.dark) .active-lesson {
    background-color: #1E293B;
    color: #fff;
}

.chapter-header {
    background: #f3f4f6;
    color: #000000;
    font-weight: 800;
    font-size: 13px;
    border-bottom: 1px solid #d1d5db;
    transition: all 0.2s;
    letter-spacing: 0.05em;
}

:global(.dark) .chapter-header {
    background: #0F172A;
    color: #ffffff;
    border-bottom-color: rgba(255, 255, 255, 0.05);
}

.learning-footer {
    position: sticky;
    bottom: 0;
    z-index: 50;
}

.animate-fade-in {
  animation: fadeIn 0.4s ease-out forwards;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(8px); }
  to { opacity: 1; transform: translateY(0); }
}

.custom-scrollbar::-webkit-scrollbar {
    width: 4px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
}

@media (max-width: 1024px) {
    .learning-shell { grid-template-columns: 1fr; }
    .learning-sidebar {
        position: fixed;
        left: -320px;
        top: 56px;
        bottom: 0;
        width: 320px;
        transition: transform 0.3s ease;
    }
    .learning-sidebar.open { transform: translateX(320px); }
}
</style>

