import { useState, useEffect } from 'react';
import { Head, Link, router } from '@inertiajs/react';
import { 
    ChevronLeft, 
    CheckCircle2, 
    Circle, 
    Play, 
    FileText, 
    ChevronRight, 
    Menu, 
    X,
    Lock,
    ArrowLeft,
    CheckCircle,
    ChevronDown,
    Layers
} from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { Progress } from '@/Components/ui/progress';
import { Sheet, SheetContent } from '@/Components/ui/sheet';
import QuizPlayer from '@/Components/Learning/QuizPlayer';
import StudyDeck from '@/Components/Learning/StudyDeck';

interface Question {
    id: number;
    type: 'multiple_choice' | 'flashcard';
    question_text: string;
    options: string[] | null;
    correct_answer: string;
    explanation: string | null;
}

interface Lesson {
    id: number;
    title: string;
    slug: string;
    content: string | null;
    video_url: string | null;
    duration: number | null;
    quiz_pass_mark?: number;
    questions?: Question[];
    materials?: {
        id: number;
        title: string;
        file_path: string;
        file_type: string;
        file_size: string;
    }[];
}

interface Module {
    id: number;
    title: string;
    lessons: Lesson[];
    quiz_pass_mark?: number;
    questions?: Question[];
}

interface Course {
    id: number;
    name: string;
    slug: string;
    modules: Module[];
}

interface ProgressItem {
    course_lesson_id: number;
}

interface Attempt {
    id: number;
    score: number;
    total_questions: number;
    passed: boolean;
    answers: Record<number, string>;
    course_module_id: number;
}

interface Props {
    course: Course;
    currentLesson?: Lesson;
    currentModuleQuiz?: Module;
    currentStudyDeck?: Module;
    progress: ProgressItem[];
    quizAttempts: Attempt[];
}

export default function Player({ course, currentLesson, currentModuleQuiz, currentStudyDeck, progress, quizAttempts }: Props) {
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [openModules, setOpenModules] = useState<number[]>([]);
    const [isDesktop, setIsDesktop] = useState(true);

    useEffect(() => {
        const handleResize = () => {
            setIsDesktop(window.innerWidth >= 1024);
        };
        // Set initial value
        handleResize();
        
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    useEffect(() => {
        // Only set default sidebar state once on mount
        if (window.innerWidth >= 1024) {
            setSidebarOpen(true);
        } else {
            setSidebarOpen(false);
        }

        // Open current module by default once on mount
        const activeLesson = (!currentModuleQuiz && !currentStudyDeck) ? (currentLesson || course.modules[0]?.lessons[0]) : undefined;
        const currentModule = currentModuleQuiz || currentStudyDeck || course.modules.find(m => m.lessons.some(l => l.id === activeLesson?.id));
        if (currentModule) {
            setOpenModules([currentModule.id]);
        }
    }, [course.id]); // Only run when switching courses, not lessons

    const toggleModule = (moduleId: number) => {
        setOpenModules(prev => 
            prev.includes(moduleId) 
                ? prev.filter(id => id !== moduleId) 
                : [...prev, moduleId]
        );
    };
    
    const activeLesson = (currentModuleQuiz || currentStudyDeck) ? undefined : (currentLesson || course.modules[0]?.lessons[0]);
    const moduleAttempts = currentModuleQuiz ? (quizAttempts?.filter(a => a.course_module_id === currentModuleQuiz.id) || []) : [];
    const lastAttempt = moduleAttempts.length > 0 ? moduleAttempts[moduleAttempts.length - 1] : null;
    
    const isCompleted = (lessonId: number) => {
        return progress.some(p => p.course_lesson_id === lessonId);
    };

    const totalLessons = course.modules.reduce((acc, m) => {
        const hasMCQs = m.questions && m.questions.some(q => q.type === 'multiple_choice');
        return acc + m.lessons.length + (hasMCQs ? 1 : 0);
    }, 0);
    const completedLessons = progress.length + course.modules.reduce((acc, m) => {
        const hasMCQs = m.questions && m.questions.some(q => q.type === 'multiple_choice');
        if (!hasMCQs) return acc;
        const passed = moduleAttempts.some(a => a.course_module_id === m.id && a.passed);
        return acc + (passed ? 1 : 0);
    }, 0);
    const progressPercentage = Math.round((completedLessons / totalLessons) * 100);

    // Helper to find next lesson or quiz
    type CurriculumStep = 
        | { type: 'lesson'; lesson: Lesson; module_id: number; slug: string; title: string; id: number }
        | { type: 'study_deck'; module: Module; module_id: number; slug: string; title: string; id: number }
        | { type: 'quiz'; module: Module; module_id: number; slug: string; title: string; id: number };

    const curriculumSteps: CurriculumStep[] = course.modules.flatMap(m => {
        const steps: CurriculumStep[] = [];
        m.lessons.forEach(l => steps.push({ type: 'lesson', lesson: l, module_id: m.id, slug: l.slug, title: l.title, id: l.id }));
        
        const hasFlashcards = m.questions && m.questions.some(q => q.type === 'flashcard');
        const hasMCQs = m.questions && m.questions.some(q => q.type === 'multiple_choice');

        if (hasFlashcards) {
            steps.push({ type: 'study_deck', module: m, module_id: m.id, slug: `study-deck-${m.id}`, title: 'Study Deck', id: m.id });
        }
        if (hasMCQs) {
            steps.push({ type: 'quiz', module: m, module_id: m.id, slug: `quiz-${m.id}`, title: 'Module Quiz', id: m.id });
        }
        return steps;
    });

    const currentStepIndex = curriculumSteps.findIndex(s => 
        (activeLesson && s.type === 'lesson' && s.id === activeLesson.id) ||
        (currentModuleQuiz && s.type === 'quiz' && s.id === currentModuleQuiz.id) ||
        (currentStudyDeck && s.type === 'study_deck' && s.id === currentStudyDeck.id)
    );

    const prevStep = currentStepIndex > 0 ? curriculumSteps[currentStepIndex - 1] : null;
    const nextStep = currentStepIndex !== -1 && currentStepIndex < curriculumSteps.length - 1 ? curriculumSteps[currentStepIndex + 1] : null;

    const getStepUrl = (step: CurriculumStep) => {
        if (step.type === 'lesson') {
            return route('learning.lesson', [course.slug, step.slug]);
        }
        if (step.type === 'study_deck') {
            return route('learning.module.study-deck', [course.slug, step.module_id]);
        }
        return route('learning.module.quiz', [course.slug, step.module_id]);
    };

    // Scroll to top when active lesson or module changes
    useEffect(() => {
        const mainEl = document.querySelector('main');
        if (mainEl) {
            mainEl.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }, [activeLesson?.id, currentModuleQuiz?.id]);

    // Embed Video Helper
    const getEmbedUrl = (url: string) => {
        if (!url) return '';
        
        // YouTube Regex to match: watch?v=ID, embed/ID, shorts/ID, youtu.be/ID
        const ytRegex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|shorts\/)([^#\&\?]*).*/;
        const ytMatch = url.match(ytRegex);
        
        if (ytMatch && ytMatch[2].length === 11) {
            const id = ytMatch[2];
            return `https://www.youtube.com/embed/${id}?modestbranding=1&rel=0&showinfo=0&iv_load_policy=3&controls=1&autohide=1&disablekb=1&autoplay=1`;
        }
        
        if (url.includes('vimeo.com')) {
            const vimeoRegex = /(?:vimeo\.com\/|video\/)(\d+)/;
            const vimeoMatch = url.match(vimeoRegex);
            if (vimeoMatch) {
                return `https://player.vimeo.com/video/${vimeoMatch[1]}?autoplay=1`;
            }
        }
        return url;
    };

    return (
        <div className="flex flex-col h-screen bg-cream grain">
            <Head title={activeLesson ? `${activeLesson.title} - ${course.name}` : course.name} />
            
            {/* Top Header */}
            <header className="h-16 border-b border-[#E8E6DF] flex items-center justify-between px-6 bg-white/90 backdrop-blur-md z-20 flex-shrink-0">
                <div className="flex items-center gap-4">
                    <Link 
                        href={route('learning.index')}
                        className="p-2 hover:bg-[#F5F3EF] rounded-xl transition-colors text-ink"
                    >
                        <ArrowLeft className="h-5 w-5" />
                    </Link>
                    <div className="hidden sm:block">
                        <h1 className="text-[14px] font-bold text-ink truncate max-w-[300px]">
                            {course.name}
                        </h1>
                        <div className="flex items-center gap-2 mt-0.5">
                            <div className="w-32">
                                <Progress value={progressPercentage} className="h-1" />
                            </div>
                            <span className="text-[10px] font-bold text-[#8C92AC] uppercase tracking-wider">
                                {progressPercentage}% Complete
                            </span>
                        </div>
                    </div>
                </div>

                <div className="flex items-center gap-3">
                    <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => setSidebarOpen(!sidebarOpen)}
                        className={`rounded-xl font-bold text-[12px] gap-2 transition-all ${sidebarOpen ? 'bg-primary/5 text-primary' : 'text-[#8C92AC]'}`}
                    >
                        {sidebarOpen ? <X className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
                        <span className="hidden sm:inline">{sidebarOpen ? 'Close Menu' : 'Curriculum'}</span>
                        <span className="sm:hidden">Curriculum</span>
                    </Button>
                </div>
            </header>

            <div className="flex flex-1 overflow-hidden">
                {/* Main Content Area */}
                <main className="flex-1 overflow-y-auto bg-cream grain">
                    {currentStudyDeck ? (
                        <div className="max-w-5xl mx-auto py-12 px-6 lg:px-12">
                            <div className="mb-12">
                                <h2 className="font-display text-[2rem] text-ink leading-tight mb-2">
                                    {currentStudyDeck.title} - Study Deck
                                </h2>
                                <p className="text-[#8C92AC]">Review key concepts before taking the quiz.</p>
                            </div>
                            <StudyDeck 
                                moduleId={currentStudyDeck.id}
                                questions={currentStudyDeck.questions || []}
                                onCompleted={() => {
                                    if (nextStep) {
                                        router.visit(getStepUrl(nextStep));
                                    } else {
                                        router.visit(route('learning.index'));
                                    }
                                }}
                            />
                        </div>
                    ) : currentModuleQuiz ? (
                        <div className="max-w-5xl mx-auto py-12 px-6 lg:px-12">
                            <div className="mb-12">
                                <h2 className="font-display text-[2rem] text-ink leading-tight mb-2">
                                    {currentModuleQuiz.title} - Module Quiz
                                </h2>
                                <p className="text-[#8C92AC]">Test your knowledge on the module contents.</p>
                            </div>
                            <QuizPlayer 
                                moduleId={currentModuleQuiz.id}
                                questions={currentModuleQuiz.questions || []}
                                lastAttempt={lastAttempt}
                                passMark={currentModuleQuiz.quiz_pass_mark || 70}
                                onCompleted={() => {
                                    if (nextStep) {
                                        router.visit(getStepUrl(nextStep));
                                    } else {
                                        router.visit(route('learning.index'));
                                    }
                                }}
                            />
                        </div>
                    ) : activeLesson ? (
                        <div className="max-w-5xl mx-auto py-12 px-6 lg:px-12">
                            {/* Video Player */}
                            {activeLesson.video_url && (
                                <div className="aspect-video w-full rounded-3xl overflow-hidden bg-black border border-[#E8E6DF] mb-12">
                                    <iframe 
                                        src={getEmbedUrl(activeLesson.video_url)}
                                        className="w-full h-full"
                                        allowFullScreen
                                    />
                                </div>
                            )}

                            {/* Course Completion Celebration */}
                            {progressPercentage === 100 && (
                                <div className="mb-8 p-6 bg-emerald-50/50 border border-emerald-100 rounded-3xl flex flex-col sm:flex-row items-center gap-6 animate-in fade-in slide-in-from-top-4 duration-700">
                                    <div className="h-16 w-16 bg-emerald-500 rounded-xl flex items-center justify-center flex-shrink-0">
                                        <CheckCircle className="h-8 w-8 text-white" />
                                    </div>
                                    <div className="text-center sm:text-left flex-1">
                                        <h3 className="text-lg font-bold text-emerald-900">Congratulations! Course Completed!</h3>
                                        <p className="text-emerald-700/80 text-sm font-medium">You've successfully completed all the lessons in this course.</p>
                                    </div>
                                    <Link 
                                        href={route('learning.index')}
                                        className="h-12 px-8 bg-emerald-500 text-white font-bold text-sm rounded-xl hover:bg-emerald-600 transition-all flex items-center gap-2"
                                    >
                                        Back to Dashboard
                                    </Link>
                                </div>
                            )}

                            {/* Lesson Content */}
                            <div className="space-y-12">
                                <div>
                                    <h2 className="font-display text-[2rem] text-ink leading-tight mb-2">
                                        {activeLesson.title}
                                    </h2>
                                    {activeLesson.duration !== null && activeLesson.duration > 0 && (
                                        <span className="text-[11px] font-bold text-[#8C92AC] uppercase tracking-wider">
                                            Duration: {activeLesson.duration} minutes
                                        </span>
                                    )}
                                </div>

                                {activeLesson.materials && activeLesson.materials.length > 0 && (
                                    <div className="bg-[#F5F3EF] rounded-2xl p-6 md:p-8">
                                        <h3 className="text-[13px] font-bold text-ink uppercase tracking-wider mb-4">Study Materials</h3>
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            {activeLesson.materials.map(material => (
                                                <a 
                                                    key={material.id}
                                                    href={route('learning.material.download', material.id)}
                                                    target="_blank"
                                                    className="flex items-center justify-between p-4 bg-white rounded-xl border border-[#E8E6DF] hover:border-primary/50 hover:shadow-md transition-all group"
                                                >
                                                    <div className="flex items-center gap-4">
                                                        <div className="h-10 w-10 bg-primary/10 rounded-lg flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-white transition-colors">
                                                            <FileText className="h-5 w-5" />
                                                        </div>
                                                        <div>
                                                            <p className="text-[14px] font-bold text-ink">{material.title}</p>
                                                            <p className="text-[11px] text-[#8C92AC] font-medium uppercase tracking-wider mt-0.5">
                                                                {material.file_type} • {material.file_size}
                                                            </p>
                                                        </div>
                                                    </div>
                                                </a>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                <div className="prose prose-ink max-w-none prose-p:text-lg prose-p:leading-relaxed prose-headings:font-display">
                                    {activeLesson.content ? (
                                        <div dangerouslySetInnerHTML={{ __html: activeLesson.content }} />
                                    ) : (
                                        <p className="text-[#8C92AC] italic">No text content for this lesson.</p>
                                    )}
                                </div>

                                {/* Bottom Completion Section */}
                                {!isCompleted(activeLesson.id) && (
                                    <div className="mt-12 p-8 bg-primary/5 rounded-2xl border border-primary/10 text-center flex flex-col items-center">
                                        <h4 className="text-lg font-bold text-ink mb-4">Finished with this lesson?</h4>
                                        <Button 
                                            onClick={() => {
                                                const nextUrl = nextStep ? getStepUrl(nextStep) : route('learning.index');
                                                router.post(route('learning.complete', activeLesson.id), { next_url: nextUrl }, { 
                                                    preserveScroll: false, 
                                                    preserveState: false 
                                                });
                                            }}
                                            className="h-12 px-6 w-full sm:w-auto rounded-xl bg-primary text-white font-bold text-[14px] hover:brightness-110"
                                        >
                                            Complete Lesson & Continue
                                        </Button>
                                    </div>
                                )}

                                {/* Navigation Footer */}
                                <div className="mt-12 pt-8 border-t border-[#E8E6DF] flex flex-col sm:flex-row items-center justify-between gap-4">
                                    {prevStep ? (
                                        <Link 
                                            href={getStepUrl(prevStep)}
                                            className="inline-flex h-12 w-full sm:w-auto items-center justify-center gap-3 px-8 bg-white border border-[#E8E6DF] rounded-xl text-[13px] font-bold text-ink hover:border-primary/50 transition-all"
                                            preserveScroll
                                            preserveState
                                        >
                                            <ChevronLeft className="h-5 w-5" />
                                            {prevStep.type === 'lesson' ? 'Previous Lesson' : 'Previous: Quiz'}
                                        </Link>
                                    ) : <div className="hidden sm:block" />}

                                    {nextStep ? (
                                        <button 
                                            onClick={() => {
                                                if (!isCompleted(activeLesson!.id)) {
                                                    router.post(route('learning.complete', activeLesson!.id), {
                                                        next_url: getStepUrl(nextStep)
                                                    }, {
                                                        preserveScroll: true,
                                                        preserveState: true
                                                    });
                                                } else {
                                                    router.visit(getStepUrl(nextStep), {
                                                        preserveScroll: true,
                                                        preserveState: true
                                                    });
                                                }
                                            }}
                                            className="inline-flex h-12 w-full sm:w-auto items-center justify-center gap-3 px-8 bg-white border border-[#E8E6DF] rounded-xl text-[13px] font-bold text-ink hover:border-primary/50 transition-all"
                                        >
                                            <span className="truncate">Next: {nextStep.title}</span>
                                            <ChevronRight className="h-4 w-4 flex-shrink-0" />
                                        </button>
                                    ) : (
                                        <Link 
                                            href={route('learning.index')}
                                            className="inline-flex h-12 w-full sm:w-auto items-center justify-center gap-3 px-8 bg-emerald-500 rounded-xl text-[13px] font-bold text-white hover:bg-emerald-600 transition-all"
                                        >
                                            <span className="truncate">Go to Dashboard</span>
                                            <CheckCircle className="h-4 w-4 flex-shrink-0" />
                                        </Link>
                                    )}
                                </div>
                            </div>
                        </div>
                    ) : (
                        <div className="flex flex-col items-center justify-center h-full text-center p-6">
                            <Lock className="h-16 w-16 text-[#C0BDBA] mb-4" />
                            <h2 className="text-2xl font-bold text-ink">No lesson selected</h2>
                            <p className="text-[#8C92AC]">Please select a lesson from the curriculum sidebar to start learning.</p>
                        </div>
                    )}
                </main>

                {/* Mobile Curriculum Drawer (Sheet) */}
                {!isDesktop && (
                    <div className="lg:hidden">
                        <Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
                            <SheetContent side="right" className="w-[85%] max-w-[400px] p-0 border-l border-[#E8E6DF] bg-white sm:max-w-sm [&>button]:hidden">
                                <div className="h-full flex flex-col overflow-hidden">
                                    <div className="p-6 border-b border-[#E8E6DF] flex items-center justify-between flex-shrink-0">
                                        <div className="flex items-center gap-3">
                                            <button 
                                                onClick={() => setSidebarOpen(false)}
                                                className="p-2 hover:bg-[#F5F3EF] rounded-lg transition-colors text-ink -ml-2"
                                            >
                                                <ArrowLeft className="h-5 w-5" />
                                            </button>
                                            <div>
                                                <h3 className="font-bold text-ink text-lg">Course Curriculum</h3>
                                                <p className="text-[11px] text-[#8C92AC] font-bold uppercase tracking-wider mt-1">
                                                    {completedLessons} / {totalLessons} Lessons Completed
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="flex-1 overflow-y-auto">
                                        <CurriculumList 
                                            course={course}
                                            activeLesson={activeLesson}
                                            currentModuleQuiz={currentModuleQuiz}
                                            currentStudyDeck={currentStudyDeck}
                                            openModules={openModules}
                                            toggleModule={toggleModule}
                                            isDesktop={isDesktop}
                                            setSidebarOpen={setSidebarOpen}
                                            isCompleted={isCompleted}
                                            quizAttempts={quizAttempts}
                                        />
                                    </div>
                                </div>
                            </SheetContent>
                        </Sheet>
                    </div>
                )}

                {/* Desktop Curriculum Sidebar */}
                <aside 
                    className={`
                        hidden lg:flex flex-col bg-white transition-all duration-300 ease-in-out
                        shadow-none border-l border-[#E8E6DF] flex-shrink-0 overflow-hidden
                        ${sidebarOpen ? 'w-[400px] min-w-[400px]' : 'w-0 min-w-0 border-none p-0'}
                    `}
                >
                    <div className="w-[400px] flex-shrink-0 h-full flex flex-col overflow-hidden">
                        <div className="p-6 border-b border-[#E8E6DF] flex items-center justify-between flex-shrink-0">
                            <div className="flex items-center gap-3">
                                <button 
                                    onClick={() => setSidebarOpen(false)}
                                    className="p-2 hover:bg-[#F5F3EF] rounded-lg transition-colors text-ink -ml-2"
                                >
                                    <ArrowLeft className="h-5 w-5" />
                                </button>
                                <div>
                                    <h3 className="font-bold text-ink text-lg">Course Curriculum</h3>
                                    <p className="text-[11px] text-[#8C92AC] font-bold uppercase tracking-wider mt-1">
                                        {completedLessons} / {totalLessons} Lessons Completed
                                    </p>
                                </div>
                            </div>
                        </div>
                        <div className="flex-1 overflow-y-auto">
                            <CurriculumList 
                                course={course}
                                activeLesson={activeLesson}
                                currentModuleQuiz={currentModuleQuiz}
                                currentStudyDeck={currentStudyDeck}
                                openModules={openModules}
                                toggleModule={toggleModule}
                                isDesktop={isDesktop}
                                setSidebarOpen={setSidebarOpen}
                                isCompleted={isCompleted}
                                quizAttempts={quizAttempts}
                            />
                        </div>
                    </div>
                </aside>
            </div>
        </div>
    );
}

// Sub-component defined outside to prevent remounting
const CurriculumList = ({ 
    course, 
    activeLesson,
    currentModuleQuiz,
    currentStudyDeck,
    openModules, 
    toggleModule, 
    isDesktop, 
    setSidebarOpen,
    isCompleted,
    quizAttempts
}: {
    course: Course;
    activeLesson: Lesson | undefined;
    currentModuleQuiz: Module | undefined;
    currentStudyDeck: Module | undefined;
    openModules: number[];
    toggleModule: (id: number) => void;
    isDesktop: boolean;
    setSidebarOpen: (open: boolean) => void;
    isCompleted: (id: number) => boolean;
    quizAttempts?: Attempt[];
}) => (
    <div className="p-4 space-y-2">
        {course.modules.map((module) => {
            const isOpen = openModules.includes(module.id);
            return (
                <div key={module.id} className="space-y-1">
                    <button 
                        onClick={() => toggleModule(module.id)}
                        className="w-full flex items-center justify-between px-4 py-3 text-[11px] font-bold text-[#8C92AC] uppercase tracking-widest bg-[#FAFAF8] rounded-xl hover:bg-[#F5F3EF] transition-colors"
                    >
                        {module.title}
                        <ChevronDown className={`h-4 w-4 transition-transform duration-300 ${isOpen ? 'rotate-180' : ''}`} />
                    </button>
                    
                    {isOpen && (
                        <div className="space-y-1 pt-1">
                            {module.lessons.map((lesson) => (
                                <Link
                                    key={lesson.id}
                                    href={route('learning.lesson', [course.slug, lesson.slug])}
                                    onClick={() => {
                                        if (!isDesktop) {
                                            setSidebarOpen(false);
                                        }
                                    }}
                                    preserveScroll
                                    preserveState
                                    className={`flex items-center gap-3 p-4 rounded-2xl transition-all group ${
                                        activeLesson?.id === lesson.id 
                                            ? 'bg-primary/5 border border-primary/20' 
                                            : 'hover:bg-[#F5F3EF] border border-transparent'
                                    }`}
                                >
                                    {isCompleted(lesson.id) ? (
                                        <CheckCircle2 className="h-5 w-5 text-emerald-500 fill-emerald-50" />
                                    ) : (
                                        <div className={`h-5 w-5 rounded-full border-2 ${
                                            activeLesson?.id === lesson.id ? 'border-primary' : 'border-[#E8E6DF]'
                                        } flex items-center justify-center`}>
                                            {lesson.video_url ? <Play className={`h-2.5 w-2.5 ${
                                                activeLesson?.id === lesson.id ? 'fill-primary text-primary' : 'text-transparent'
                                            }`} /> : <div className="h-1.5 w-1.5 bg-transparent rounded-full" />}
                                        </div>
                                    )}
                                    <div className="flex-1 min-w-0">
                                        <p className={`text-[13px] font-bold truncate ${
                                            activeLesson?.id === lesson.id ? 'text-primary' : 'text-ink'
                                        }`}>
                                            {lesson.title}
                                        </p>
                                        {lesson.duration !== null && lesson.duration > 0 && (
                                            <span className="text-[10px] text-[#8C92AC] font-bold">
                                                {lesson.duration}m
                                            </span>
                                        )}
                                    </div>
                                </Link>
                            ))}
                            {module.questions && module.questions.some(q => q.type === 'flashcard') && (
                                <Link
                                    href={route('learning.module.study-deck', [course.slug, module.id])}
                                    onClick={() => {
                                        if (!isDesktop) setSidebarOpen(false);
                                    }}
                                    preserveScroll
                                    preserveState
                                    className={`flex items-center gap-3 p-4 rounded-2xl transition-all group mt-1 ${
                                        currentStudyDeck?.id === module.id 
                                            ? 'bg-primary/5 border border-primary/20' 
                                            : 'hover:bg-[#F5F3EF] border border-transparent'
                                    }`}
                                >
                                    <div className={`h-5 w-5 flex items-center justify-center`}>
                                        <Layers className={`h-4 w-4 ${currentStudyDeck?.id === module.id ? 'text-primary' : 'text-[#8C92AC]'}`} />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <p className={`text-[13px] font-bold truncate ${
                                            currentStudyDeck?.id === module.id ? 'text-primary' : 'text-ink'
                                        }`}>
                                            Study Deck
                                        </p>
                                    </div>
                                </Link>
                            )}
                            {module.questions && module.questions.some(q => q.type === 'multiple_choice') && (
                                <Link
                                    href={route('learning.module.quiz', [course.slug, module.id])}
                                    onClick={() => {
                                        if (!isDesktop) setSidebarOpen(false);
                                    }}
                                    preserveScroll
                                    preserveState
                                    className={`flex items-center gap-3 p-4 rounded-2xl transition-all group mt-1 ${
                                        currentModuleQuiz?.id === module.id 
                                            ? 'bg-primary/5 border border-primary/20' 
                                            : 'hover:bg-[#F5F3EF] border border-transparent'
                                    }`}
                                >
                                    {quizAttempts?.some((a: Attempt) => a.course_module_id === module.id && a.passed) ? (
                                        <CheckCircle2 className="h-5 w-5 text-emerald-500 fill-emerald-50" />
                                    ) : (
                                        <div className={`h-5 w-5 rounded-full border-2 ${
                                            currentModuleQuiz?.id === module.id ? 'border-primary' : 'border-[#E8E6DF]'
                                        } flex items-center justify-center`}>
                                            <div className="h-1.5 w-1.5 bg-transparent rounded-full" />
                                        </div>
                                    )}
                                    <div className="flex-1 min-w-0">
                                        <p className={`text-[13px] font-bold truncate ${
                                            currentModuleQuiz?.id === module.id ? 'text-primary' : 'text-ink'
                                        }`}>
                                            Module Quiz
                                        </p>
                                    </div>
                                </Link>
                            )}
                        </div>
                    )}
                </div>
            );
        })}
    </div>
);
