"use client" import Link from "next/link" import { useState, useEffect } from "react" import { useAuth } from "@/context/auth-context" import { useRouter } from "next/navigation" import { toast } from "react-hot-toast" import type { Lesson } from "@/lib/types" import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Loader2, Play, BookOpen, Clock } from "lucide-react" import ReactMarkdown from "react-markdown" interface LessonViewerProps { courseId: string lessonId: string } interface LessonData { id: string title: string type: string video_url: string embed_url: string duration: string description: string content: string course_id: string completed?: boolean } export function LessonViewer({ courseId, lessonId }: LessonViewerProps) { const { user, firebaseUser, isLoadingAuth, authMethod, token } = useAuth() const router = useRouter() const [lesson, setLesson] = useState(null) const [isLoadingLesson, setIsLoadingLesson] = useState(true) const [isMarkingCompleted, setIsMarkingCompleted] = useState(false) const [error, setError] = useState(null) useEffect(() => { if (!isLoadingAuth && !user && !firebaseUser) { toast.error("Please login to view lessons.") router.push("/") return } const fetchLesson = async () => { setIsLoadingLesson(true) setError(null) try { console.log(`Fetching lesson: ${courseId}/${lessonId}`) // Debug log const response = await fetch(`http://127.0.0.1:5000/api/courses/${courseId}/lessons/${lessonId}`, { method: 'GET', headers: { 'Content-Type': 'application/json', // Add auth header if token exists ...(token && { 'Authorization': `Bearer ${token}` }) } }) if (!response.ok) { throw new Error(`Failed to fetch lesson: ${response.status}`) } const lessonData = await response.json() console.log('Lesson data received:', lessonData) // Debug log setLesson(lessonData) } catch (err: any) { console.error("Failed to fetch lesson:", err) setError(err.message || "Failed to load lesson.") toast.error(err.message || "Failed to load lesson.") } finally { setIsLoadingLesson(false) } } if (user || firebaseUser) { fetchLesson() } }, [user, firebaseUser, isLoadingAuth, router, courseId, lessonId, token]) const markLessonCompleted = async () => { if (!lesson || lesson.completed || !token) { toast.error("Please connect your MetaMask wallet to mark lessons as completed.") return } setIsMarkingCompleted(true) try { const response = await fetch(`http://127.0.0.1:5000/api/courses/${courseId}/lessons/${lessonId}/complete`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } }) if (response.ok) { setLesson((prev) => (prev ? { ...prev, completed: true } : null)) toast.success("Lesson marked as completed!") } else { throw new Error('Failed to mark lesson as completed') } } catch (err: any) { console.error("Failed to mark lesson completed:", err) toast.error("Failed to mark lesson completed.") } finally { setIsMarkingCompleted(false) } } // Fixed: Function to render markdown-like content with proper string handling const renderContent = (content: string) => { const lines = content.split('\n') const result = [] let inCodeBlock = false let codeBlockContent: string[] = [] for (let index = 0; index < lines.length; index++) { const line = lines[index] // Handle code blocks properly if (line.startsWith('```')) { if (!inCodeBlock) { // Opening code block inCodeBlock = true codeBlockContent = [] } else { // Closing code block - render accumulated content inCodeBlock = false result.push(
💻 Code Example:
                {codeBlockContent.join('\n')}
              
) codeBlockContent = [] } continue } // If we're inside a code block, accumulate content if (inCodeBlock) { codeBlockContent.push(line) continue } // Handle other markdown elements if (line.startsWith('# ')) { result.push(

{line.substring(2)}

) } else if (line.startsWith('## ')) { result.push(

{line.substring(3)}

) } else if (line.startsWith('- ')) { result.push(
  • {line.substring(2)}
  • ) } else if (line.trim() === '') { result.push(
    ) } else if (line.trim() !== '') { result.push(

    {line}

    ) } } return result } if (isLoadingAuth || isLoadingLesson) { return (
    Loading lesson...
    ) } if (error) { return (

    {error}

    ) } if (!lesson) { return (

    Lesson not found.

    ) } return (
    {/* Lesson Header Card */} {lesson.title} {lesson.description && (

    {lesson.description}

    )}
    {lesson.type === 'video' ? : } {lesson.type === 'video' ? 'Video Lesson' : lesson.type === 'code' ? 'Coding Exercise' : 'Reading'} {lesson.duration && ( {lesson.duration} )} {lesson.completed && ( ✅ Completed )}
    {/* Authentication Warning */} {authMethod === "firebase" && !token && (

    Limited Access

    You are logged in with email. Full functionality, including progress tracking and data persistence, requires connecting your MetaMask wallet.

    )} {/* Video Player */} {lesson.type === "video" && lesson.embed_url && (

    Video Tutorial