"use client" import { useEffect, useState } from "react" import { useRouter, useParams } from "next/navigation" import { Loader2, Play, Clock, BookOpen, ChevronDown, ChevronRight, User, Users, Star, Award, TrendingUp, CheckCircle, ArrowRight } from "lucide-react" import { toast } from "react-hot-toast" import api from "@/lib/api" import { useAuth } from "@/context/auth-context" import { CertificateModal } from "@/components/certificate-modal" type Course = { id: string title: string description: string subject: string difficulty: string mentor: string students: number embed_url?: string video_url?: string } type Module = { id: string course_id: string title: string description: string order: number created_at?: string } type Lesson = { id: string module_id: string course_id: string title: string description: string video_url: string embed_url: string order: number duration?: string type: string content?: string } export default function CoursePage() { const { user, firebaseUser, isLoading: authLoading } = useAuth() const params = useParams() const router = useRouter() const courseId = params?.courseId as string const [course, setCourse] = useState(null) const [modules, setModules] = useState([]) const [lessons, setLessons] = useState<{ [moduleId: string]: Lesson[] }>({}) const [loading, setLoading] = useState(true) const [modulesLoading, setModulesLoading] = useState(false) const [error, setError] = useState(null) // Navigation state const [selectedModuleId, setSelectedModuleId] = useState(null) const [selectedLessonId, setSelectedLessonId] = useState(null) const [expandedModules, setExpandedModules] = useState<{ [moduleId: string]: boolean }>({}) const [completed, setCompleted] = useState(false) // Certificate Modal State const [showCertificateModal, setShowCertificateModal] = useState(false) useEffect(() => { if (!authLoading && !user && !firebaseUser) { toast.error("Please login to view courses.") router.replace("/") return } if ((user || firebaseUser) && courseId) { fetchCourseData() } }, [authLoading, user, firebaseUser, courseId, router]) const fetchCourseData = async () => { setLoading(true) setError(null) try { console.log('🔍 Starting to fetch course data for:', courseId) const courseResponse = await api.get(`/api/courses/${courseId}?t=${Date.now()}`) const courseData = courseResponse.data console.log('✅ Course data loaded:', courseData) setCourse(courseData) await fetchModulesAndLessons(courseId) } catch (err: any) { console.error('❌ Error fetching course data:', err) setError(err.message || "Failed to load course data.") toast.error("Failed to load course data.") } finally { setLoading(false) } } const fetchModulesAndLessons = async (courseId: string) => { setModulesLoading(true) try { console.log('🔍 Fetching modules for course:', courseId) let modulesData = null let modulesResponse = null try { modulesResponse = await fetch(`http://127.0.0.1:5000/api/admin/courses/${courseId}/modules`, { headers: { 'Authorization': 'Bearer admin-secret-key', 'Content-Type': 'application/json' } }) if (modulesResponse.ok) { modulesData = await modulesResponse.json() console.log('✅ Modules loaded from admin endpoint:', modulesData) } } catch (adminError) { console.log('⚠️ Admin endpoint failed, trying public endpoint') } if (!modulesData || !modulesResponse?.ok) { try { modulesResponse = await fetch(`http://127.0.0.1:5000/api/courses/${courseId}/modules`, { headers: { 'Content-Type': 'application/json' } }) if (modulesResponse.ok) { modulesData = await modulesResponse.json() console.log('✅ Modules loaded from public endpoint:', modulesData) } } catch (publicError) { console.error('❌ Both module endpoints failed') } } if (modulesData) { let modulesList: Module[] = [] if (modulesData.success && modulesData.modules && Array.isArray(modulesData.modules)) { modulesList = modulesData.modules } else if (modulesData.modules && Array.isArray(modulesData.modules)) { modulesList = modulesData.modules } else if (Array.isArray(modulesData)) { modulesList = modulesData } else if (modulesData.data && Array.isArray(modulesData.data)) { modulesList = modulesData.data } modulesList = modulesList.sort((a, b) => a.order - b.order) console.log('🔍 Processed modules list:', modulesList) setModules(modulesList) if (modulesList.length > 0) { await fetchLessonsForAllModules(modulesList) } } else { console.log('⚠️ No modules data received') setModules([]) setLessons({}) } } catch (error) { console.error('❌ Error in fetchModulesAndLessons:', error) setModules([]) setLessons({}) } finally { setModulesLoading(false) } } const fetchLessonsForAllModules = async (modulesList: Module[]) => { const lessonsData: { [moduleId: string]: Lesson[] } = {} const expandedState: { [moduleId: string]: boolean } = {} for (const module of modulesList) { try { console.log('🔍 Fetching lessons for module:', module.id) let lessonsResponse = await fetch(`http://127.0.0.1:5000/api/admin/modules/${module.id}/lessons`, { headers: { 'Authorization': 'Bearer admin-secret-key', 'Content-Type': 'application/json' } }) if (!lessonsResponse.ok) { lessonsResponse = await fetch(`http://127.0.0.1:5000/api/modules/${module.id}/lessons`, { headers: { 'Content-Type': 'application/json' } }) } if (lessonsResponse.ok) { const lessonData = await lessonsResponse.json() console.log(`✅ Lessons loaded for module ${module.id}:`, lessonData) let lessonsList: Lesson[] = [] if (lessonData.success && lessonData.lessons && Array.isArray(lessonData.lessons)) { lessonsList = lessonData.lessons } else if (lessonData.lessons && Array.isArray(lessonData.lessons)) { lessonsList = lessonData.lessons } else if (Array.isArray(lessonData)) { lessonsList = lessonData } else if (lessonData.data && Array.isArray(lessonData.data)) { lessonsList = lessonData.data } lessonsList = lessonsList.sort((a, b) => a.order - b.order) lessonsData[module.id] = lessonsList if (!selectedModuleId && lessonsList.length > 0) { expandedState[module.id] = true } } else { console.log(`⚠️ No lessons found for module ${module.id}`) lessonsData[module.id] = [] } } catch (error) { console.error(`❌ Error fetching lessons for module ${module.id}:`, error) lessonsData[module.id] = [] } } setLessons(lessonsData) setExpandedModules(expandedState) if (!selectedModuleId && modulesList.length > 0) { const firstModule = modulesList[0] const firstModuleLessons = lessonsData[firstModule.id] || [] setSelectedModuleId(firstModule.id) if (firstModuleLessons.length > 0) { setSelectedLessonId(firstModuleLessons[0].id) } } } function getEmbedUrl(url?: string): string | undefined { if (!url) return undefined const regExp = /(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/))([^#&?]{11})/ const match = url.match(regExp) if (match && match[1]) { return `https://www.youtube.com/embed/${match[1]}?rel=0&modestbranding=1` } return url } const toggleModule = (moduleId: string) => { setExpandedModules(prev => ({ ...prev, [moduleId]: !prev[moduleId] })) } const selectLesson = (moduleId: string, lessonId: string) => { setSelectedModuleId(moduleId) setSelectedLessonId(lessonId) setExpandedModules(prev => ({ ...prev, [moduleId]: true })) } const getCurrentLesson = (): Lesson | null => { if (!selectedModuleId || !selectedLessonId) return null const moduleLessons = lessons[selectedModuleId] || [] return moduleLessons.find(lesson => lesson.id === selectedLessonId) || null } const getAllLessons = (): Lesson[] => { const allLessons: Lesson[] = [] modules.forEach(module => { const moduleLessons = lessons[module.id] || [] allLessons.push(...moduleLessons) }) return allLessons } const navigateLesson = (direction: 'prev' | 'next') => { const allLessons = getAllLessons() const currentIndex = allLessons.findIndex(lesson => lesson.id === selectedLessonId) if (direction === 'prev' && currentIndex > 0) { const prevLesson = allLessons[currentIndex - 1] selectLesson(prevLesson.module_id, prevLesson.id) } else if (direction === 'next' && currentIndex < allLessons.length - 1) { const nextLesson = allLessons[currentIndex + 1] selectLesson(nextLesson.module_id, nextLesson.id) } } const isFirstLesson = () => { const allLessons = getAllLessons() return allLessons.length > 0 && allLessons[0].id === selectedLessonId } const isLastLesson = () => { const allLessons = getAllLessons() return allLessons.length > 0 && allLessons[allLessons.length - 1].id === selectedLessonId } const markComplete = () => { setCompleted(true) setShowCertificateModal(true) } const getTotalLessons = () => { return Object.values(lessons).reduce((total, moduleLessons) => total + moduleLessons.length, 0) } const currentLesson = getCurrentLesson() if (authLoading || loading) { return (
{/* Animated background elements */}

Loading your learning journey...

) } if (error) { return (
⚠️

Oops! Something went wrong

{error}

) } if (!course) { return (
🔍

Course Not Found

The course you're looking for doesn't exist or may have been removed.

) } return (
{/* Animated Background Elements */}
{/* Header */}
OL

{course.title}

by {course.mentor}

{modules.length} modules
{getTotalLessons()} lessons
{course.students.toLocaleString()} students
{/* Sidebar - Now takes up 2 columns on large screens */} {/* Main Content - Now takes up 3 columns on large screens for full width */}
{currentLesson ? ( <> {/* Video Player */} {(currentLesson.embed_url || currentLesson.video_url) && (