'use client';
import { cn } from '@/lib/cn';
import { VideoInfo } from '@/types/dashboard';
import { useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { useState, useMemo, useEffect, useRef } from 'react';

import {
    Video,
    VideoOff,
    List,
    Clock,
    FileDown,
    ChevronRight,
    ChevronLeft,
    ChevronDown,
    ChevronUp,
    Maximize,
    ArrowLeft,
    ArrowRight,
    BookOpen,
    Calendar,
    Gamepad2,
    FileQuestion,
    Star,
    Award,
    Download,
    Loader,
    Lock,
    TvMinimal
} from 'lucide-react';
import { toast } from '@/hooks/use-toast';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from "@/components/ui/accordion";

import { VideoBox } from './video-box';
import { VideoPlayer } from './video-player';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ExamInterface } from './exam/exam-interface';
import { ExamResult } from './exam/exam-result';
import { ExamItem } from './exam/exam-item';
import { getExamData, getExamResult } from '../_actions/exams';
import { LanguageSwitcher } from '@/components/appearance/language';
import { ReviewInterface } from './review/review-interface';
import { ReviewResult } from './review/review-result';
import { ReviewItem } from './review/review-item';
import { getReviewData, getReviewResult } from '../_actions/reviews';
import { ActivityInterface } from './activity/activity-interface';
import { ActivityResult } from './activity/activity-result';
import { ActivityItem } from './activity/activity-item';
import { getActivityData, getActivityResult } from '../_actions/activities';
import { useFormSubmission } from '@/hooks/use-form-submission';
import { getGroupProgress, markSessionPresent } from '../_actions/progress';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ForumsInterface } from './forums/forums-interface';
import { MessageSquare } from 'lucide-react';

export function ProgramSessions({ 
    sessions, 
    courseName, 
    groupId, 
    isPreviewMode = false, 
    initialSessionId, 
    initialExamId, 
    initialReviewId, 
    initialActivityId, 
    lessonCount, 
    modulesCount, 
    activitiesCount, 
    examsCount, 
    reviewsCount,
    canDownloadCertificate = false
}: { 
    sessions: any[], 
    courseName?: string, 
    groupId: string, 
    isPreviewMode?: boolean, 
    initialSessionId?: number, 
    initialExamId?: number, 
    initialReviewId?: number, 
    initialActivityId?: number, 
    lessonCount?: number, 
    modulesCount?: number, 
    activitiesCount?: number, 
    examsCount?: number, 
    reviewsCount?: number,
    canDownloadCertificate?: boolean
}) {
    const t = useTranslations('programs');
    const router = useRouter();
    const locale = useLocale();
    const isArabic = locale === "ar";
    const queryClient = useQueryClient();
    
    // Track completed items locally for instant UI updates (optimistic feedback)
    const [completedItemIds, setCompletedItemIds] = useState<Set<number>>(new Set());

    // Curriculum Items
    const curriculumItems = useMemo(() => {
        const all: any[] = [];
        
        sessions.forEach((item) => {
            if (item.model === 'module') {
                const subItems = item.content_items || item.session_groups || [];
                if (Array.isArray(subItems)) {
                    subItems.forEach((sub: any) => {
                        all.push({
                            ...sub,
                            moduleTitle: item.title,
                            moduleId: item.id
                        });
                    });
                }
            } else {
                all.push(item);
            }
        });

        if (isPreviewMode) {
            return all.filter(item => item.model === 'session' && (item.is_free === 1 || item.id === initialSessionId));
        }

        return all;
    }, [sessions, isPreviewMode, initialSessionId]);

    const navigatableItems = useMemo(() => {
        return curriculumItems.filter(item => {
            if (item.model === 'session') return !!item.join_url;
            return true;
        });
    }, [curriculumItems]);

    const [selectedSession, setSelectedSession] = useState(() => {
        // Do not select a session by default if user is returning to an exam, activity, or review
        if (initialExamId || initialActivityId || initialReviewId) {
            return null;
        }
        // If initialSessionId is provided, find and select that session
        if (initialSessionId) {
            const foundSession = navigatableItems.find(s => s.model === 'session' && s.id === initialSessionId);
            if (foundSession) return foundSession;
        }
        // Otherwise, select the first session (if first navigatable is a session)
        const first = navigatableItems[0];
        return first && first.model === 'session' ? first : null;
    });

    const [selectedExam, setSelectedExam] = useState<any>(null);
    const [selectedExamResult, setSelectedExamResult] = useState<any>(null);
    const [selectedReview, setSelectedReview] = useState<any>(null);
    const [selectedReviewResult, setSelectedReviewResult] = useState<any>(null);
    const [selectedActivity, setSelectedActivity] = useState<any>(null);
    const [selectedActivityResult, setSelectedActivityResult] = useState<any>(null);

    // Preview state for showing the "Join" button
    const [previewItem, setPreviewItem] = useState<{ type: 'exam' | 'activity' | 'review'; data: any } | null>(null);
    
    // Active states (actually entering the interface)
    const [activeExam, setActiveExam] = useState<any>(null);
    const [activeReview, setActiveReview] = useState<any>(null);
    const [activeActivity, setActiveActivity] = useState<any>(null);

    const [showForums, setShowForums] = useState(false);

    const [expandedModules, setExpandedModules] = useState<string[]>(() => {
        // If initialSessionId is provided, find and open the module containing that session
        if (initialSessionId) {
            const foundModule = sessions.find(module => 
                module.model === 'module' && (
                    (module.session_groups?.some((s: any) => s.id === initialSessionId)) ||
                    (module.content_items?.some((s: any) => s.id === initialSessionId))
                )
            );
            if (foundModule) return [foundModule.id.toString()];
        }
        // Otherwise, open first module by default
        const firstModule = sessions.find(item => item.model === 'module');
        return firstModule ? [firstModule.id.toString()] : [];
    });
    const [examResults, setExamResults] = useState<Record<string, any>>({});
    const [isSidebarOpen, setIsSidebarOpen] = useState(true);

    // ✅ Handle initial deep-linked items (exams, activities, reviews)
    useEffect(() => {
        if (initialExamId) {
            const found = navigatableItems.find(item => item.model === 'exam' && item.id === initialExamId);
            if (found) {
                handleExamClick(found);
                // Also expand the module if it belongs to one
                const parentModule = sessions.find(m => m.model === 'module' && (m.content_items || m.session_groups || []).some((i: any) => i.id === initialExamId));
                if (parentModule) setExpandedModules(prev => Array.from(new Set([...prev, parentModule.id.toString()])));
            }
        } else if (initialActivityId) {
            const found = navigatableItems.find(item => item.model === 'activity' && item.id === initialActivityId);
            if (found) {
                handleActivityClick(found);
                const parentModule = sessions.find(m => m.model === 'module' && (m.content_items || m.session_groups || []).some((i: any) => i.id === initialActivityId));
                if (parentModule) setExpandedModules(prev => Array.from(new Set([...prev, parentModule.id.toString()])));
            }
        } else if (initialReviewId) {
            const found = navigatableItems.find(item => item.model === 'review' && item.id === initialReviewId);
            if (found) {
                handleReviewClick(found);
                const parentModule = sessions.find(m => m.model === 'module' && (m.content_items || m.session_groups || []).some((i: any) => i.id === initialReviewId));
                if (parentModule) setExpandedModules(prev => Array.from(new Set([...prev, parentModule.id.toString()])));
            }
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const seeIfYoutubeOrVimeo = (url: string): VideoInfo => {
        if (!url) return { type: null, id: '', embedUrl: '' };

        // youTube
        const youtubeRegex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
        const youtubeMatch = url.match(youtubeRegex);
        if (youtubeMatch) {
            const videoId = youtubeMatch[1];
            return {
                type: 'youtube',
                id: videoId,
                embedUrl: `https://www.youtube.com/embed/${videoId}`
            };
        }

        // vimeo
        const vimeoRegex = /(?:vimeo\.com\/)(?:.*\/)?(\d+)/;
        const vimeoMatch = url.match(vimeoRegex);
        if (vimeoMatch) {
            const videoId = vimeoMatch[1];
            return {
                type: 'vimeo',
                id: videoId,
                embedUrl: `https://player.vimeo.com/video/${videoId}`
            };
        }

        return { type: null, id: '', embedUrl: '' };
    };

    const currentItemIndex = useMemo(() => {
        if (selectedSession) {
            return navigatableItems.findIndex(item => item.model === 'session' && item.id === selectedSession.id);
        }
        if (previewItem) {
            return navigatableItems.findIndex(item => item.model === previewItem.type && item.id === previewItem.data.id);
        }
        if (activeExam) {
            return navigatableItems.findIndex(item => item.model === 'exam' && (item.id === activeExam._submissionId || item.id === activeExam.id));
        }
        if (activeReview) {
            return navigatableItems.findIndex(item => item.model === 'review' && (item.id === activeReview.reviewItemId || item.id === activeReview.id));
        }
        if (activeActivity) {
            return navigatableItems.findIndex(item => item.model === 'activity' && (item.id === activeActivity.activityItemId || item.id === activeActivity.id));
        }
        return -1;
    }, [navigatableItems, selectedSession, previewItem, activeExam, activeReview, activeActivity]);

    const currentNavItem = currentItemIndex !== -1 ? navigatableItems[currentItemIndex] : null;
    const currentVideoInfo = selectedSession ? seeIfYoutubeOrVimeo(selectedSession?.join_url) : null;

    // --- Navigation Lock Strategy ---
    const [secondsSpent, setSecondsSpent] = useState(0);

    // Reset timer when the current item changes
    useEffect(() => {
        setSecondsSpent(0);
    }, [currentNavItem?.id, currentNavItem?.model]);

    // Timer interval logic
    useEffect(() => {
        // Only track time if there's a duration and it's not completed
        if (!currentNavItem || currentNavItem.model !== 'session') return;
        
        const isCompleted = currentNavItem.is_completed || completedItemIds.has(currentNavItem.id);
        if (isCompleted) return;

        const timer = setInterval(() => {
            setSecondsSpent(prev => prev + 1);
        }, 1000);

        return () => clearInterval(timer);
    }, [currentNavItem?.id, currentNavItem?.model, completedItemIds]);

    const formatTime = (seconds: number) => {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    };

    const parseDurationToSeconds = (duration: any) => {
        if (!duration) return 0;
        if (typeof duration === 'number') return duration * 60;
        
        const parts = String(duration).trim().split(':');
        if (parts.length === 3) {
            // HH:MM:SS
            return (parseInt(parts[0]) || 0) * 3600 + (parseInt(parts[1]) || 0) * 60 + (parseInt(parts[2]) || 0);
        }
        if (parts.length === 2) {
            // MM:SS
            return (parseInt(parts[0]) || 0) * 60 + (parseInt(parts[1]) || 0);
        }
        // Assume minutes if just a number string
        return (parseInt(duration) || 0) * 60;
    };

    const secondsRemaining = useMemo(() => {
        if (!currentNavItem || currentNavItem.model !== 'session' || !currentNavItem.duration) return 0;
        
        // Check if already completed
        const isCompleted = currentNavItem.is_completed || completedItemIds.has(currentNavItem.id);
        if (isCompleted) return 0;

        const requiredSeconds = parseDurationToSeconds(currentNavItem.duration);
        if (requiredSeconds <= 0) return 0;

        return Math.max(0, requiredSeconds - secondsSpent);
    }, [currentNavItem, secondsSpent, completedItemIds]);

    const isNextDisabled = useMemo(() => {
        if (currentItemIndex === navigatableItems.length - 1) return true;
        return secondsRemaining > 0;
    }, [currentItemIndex, navigatableItems.length, secondsRemaining]);


    // Get progress for current group using server action
    const { data: progressData } = useQuery({
        queryKey: ['group-progress', groupId],
        queryFn: async () => {
            if (!groupId) return { success: false, progress: 0 };
            return await getGroupProgress(groupId);
        },
        enabled: !!groupId,
    });

    const progress = (progressData?.progress || 0) as number;

    const toggleModule = (moduleId: string) => {
        setExpandedModules(prev =>
            prev.includes(moduleId)
                ? prev.filter(id => id !== moduleId)
                : [...prev, moduleId]
        );
    };

    // ── Attendance: mark session present whenever the user selects a session ──
    const lastMarkedSessionRef = useRef<number | null>(null);

    useEffect(() => {
        if (!selectedSession?.id) return;
        
        const isCompleted = selectedSession.is_completed || completedItemIds.has(selectedSession.id);
        const durationSeconds = parseDurationToSeconds(selectedSession.duration);
        const isOnline = selectedSession.type === 'online';
        
        // If it's already completed, just update the ref to prevent re-marking
        if (isCompleted) {
            lastMarkedSessionRef.current = selectedSession.id;
            return;
        }

        // Logic: Mark immediately for Online/Zoom or if duration is 0. 
        // For recorded sessions, WAIT until secondsRemaining is 0.
        const shouldMarkNow = isOnline || durationSeconds <= 0 || secondsRemaining === 0;

        if (shouldMarkNow && lastMarkedSessionRef.current !== selectedSession.id) {
            console.log(`[session-present] 🖥️ Client: triggering attendance for session ${selectedSession.id}`);
            lastMarkedSessionRef.current = selectedSession.id;
            
            markSessionPresent(selectedSession.id).then(() => {
                // Instantly show the checkmark for this session
                setCompletedItemIds(prev => new Set([...prev, selectedSession.id]));

                // Refresh group progress after marking present
                queryClient.invalidateQueries({ queryKey: ['group-progress', groupId] });
            });
        }
    }, [selectedSession?.id, secondsRemaining, groupId, queryClient, completedItemIds]);

    // Scroll to selected item and auto-expand module
    useEffect(() => {
        let itemId = "";
        let relevantItem: any = null;
        
        if (selectedSession?.id) {
            itemId = `session-${selectedSession.id}`;
            relevantItem = selectedSession;
        } else if (previewItem) {
            itemId = `${previewItem.type}-${previewItem.data.id}`;
            relevantItem = previewItem.data;
        } else if (activeExam) {
            itemId = `exam-${activeExam._submissionId || activeExam.id}`;
            relevantItem = activeExam;
        } else if (activeReview) {
            itemId = `review-${activeReview.reviewItemId || activeReview.id}`;
            relevantItem = activeReview;
        } else if (activeActivity) {
            itemId = `activity-${activeActivity.activityItemId || activeActivity.id}`;
            relevantItem = activeActivity;
        } else if (!selectedSession) {
            // Fallback to initial IDs for scrolling to highlighted items when resuming
            if (initialExamId) itemId = `exam-${initialExamId}`;
            else if (initialActivityId) itemId = `activity-${initialActivityId}`;
            else if (initialReviewId) itemId = `review-${initialReviewId}`;
        }

        if (itemId) {
            // Handle module expansion
            if (relevantItem) {
                const parentModule = sessions.find(m => {
                    if (m.model !== 'module') return false;
                    const items = m.content_items || m.session_groups || [];
                    return items.some((item: any) => item.id === (relevantItem.id || relevantItem._submissionId || relevantItem.reviewItemId || relevantItem.activityItemId));
                });
                
                if (parentModule) {
                    const moduleId = parentModule.id.toString();
                    if (!expandedModules.includes(moduleId)) {
                        setExpandedModules(prev => [...prev, moduleId]);
                    }
                }
            }

            // Scroll item into view with a slight delay to allow for accordion animations
            const timer = setTimeout(() => {
                const element = document.getElementById(itemId);
                if (element) {
                    element.scrollIntoView({ behavior: 'smooth', block: 'center' }); // Using center block for better visibility
                }
            }, 300);

            return () => clearTimeout(timer);
        }
    }, [selectedSession?.id, previewItem, activeExam, activeReview, activeActivity, sessions, initialExamId, initialActivityId, initialReviewId]);


    const tr = useTranslations();
    const downloadCertificate = useFormSubmission({
        endPoint: `/user/certification/group/${groupId}`,
        method: "GET",
        onError: (err) => {
            const errorData = (err as any)?.response?.data;
            toast({
                variant: "destructive",
                title: errorData?.error || errorData?.message || tr('custom.failed') || "Failed to download certificate"
            });
            return { handled: true };
        },
        onSuccess: (response) => {
            const pdfUrl = response?.pdf_url;
            if (pdfUrl) {
                window.open(pdfUrl, "_blank");
            } else {
                toast({
                    variant: "destructive",
                    title: response?.error || response?.message || tr('custom.failed') || "Failed to download certificate"
                });
            }
        }
    });

    const handleNavigateToItem = (item: any) => {
        if (!item) return;
        if (item.model === 'session') {
            handleSessionSelect(item);
        } else if (item.model === 'exam') {
            handleExamClick(item);
        } else if (item.model === 'activity') {
            handleActivityClick(item);
        } else if (item.model === 'review') {
            handleReviewClick(item);
        }
    };

    const goToNextItem = () => {
        if (currentItemIndex >= navigatableItems.length - 1) return;
        handleNavigateToItem(navigatableItems[currentItemIndex + 1]);
    };

    const goToPreviousItem = () => {
        if (currentItemIndex <= 0) return;
        handleNavigateToItem(navigatableItems[currentItemIndex - 1]);
    };

    const handleSessionSelect = (session: any) => {
        setShowForums(false);
        setSelectedSession(session);
        // Clear other view states to ensure video shows
        setPreviewItem(null);
        setActiveExam(null);
        setSelectedExamResult(null);
        setActiveReview(null);
        setSelectedReviewResult(null);
        setActiveActivity(null);
        setSelectedActivityResult(null);
    };


    const handleExamClick = (exam: any) => {
        setShowForums(false);
        setPreviewItem({ type: 'exam', data: exam });
        setSelectedSession(null);
        setSelectedExamResult(null);
        setSelectedReviewResult(null);
        setSelectedActivityResult(null);
        setActiveExam(null);
        setActiveReview(null);
        setActiveActivity(null);
    };


    const handleJoinExam = async (exam: any) => {
        try {
            // Trigger presence update on click
            markSessionPresent(exam.id).then(() => {
                queryClient.invalidateQueries({ queryKey: ['group-progress', groupId] });
            });
            // Use the server action to fetch exam data
            const examData = await getExamData(exam.id);
            setActiveExam({ ...examData, _submissionId: exam.id });
            setPreviewItem(null);
        } catch (error) {
            console.error('Error fetching exam data:', error);
        }
    };

    const showResult = useFormSubmission({
        endPoint: "",
        method: "POST"
    });

    const handleShowResultMain = () => {
        showResult.mutate({});
    };

    const handleShowResult = async (exam: any) => {
        try {
            // Use the server action to fetch exam result
            const id = exam._submissionId || exam.id;
            const resultData = await getExamResult(id);
            setSelectedExamResult(resultData);
            setPreviewItem(null);
            setActiveExam(null);
        } catch (error) {
            console.error('Error fetching exam result:', error);
        }
    };

    const checkIfExamHasResult = async (exam: any) => {
        try {
            // Check if exam has result by calling the API
            const resultData = await getExamResult(exam.id);
            return resultData && resultData.success && resultData.questions && resultData.questions.length > 0;
        } catch (error) {
            console.error('Error checking exam result:', error);
            return false;
        }
    };

    const handleReviewClick = (review: any) => {
        setShowForums(false);
        setPreviewItem({ type: 'review', data: review });
        setSelectedSession(null);
        setSelectedExamResult(null);
        setSelectedReviewResult(null);
        setSelectedActivityResult(null);
        setActiveExam(null);
        setActiveReview(null);
        setActiveActivity(null);
    };


    const handleJoinReview = async (review: any) => {
        try {
            // Trigger presence update on click
            markSessionPresent(review.id).then(() => {
                queryClient.invalidateQueries({ queryKey: ['group-progress', groupId] });
            });
            const reviewData = await getReviewData(review.id);
            setActiveReview({ ...reviewData, reviewItemId: review.id });
            setPreviewItem(null);
        } catch (error) {
            console.error('Error fetching review data:', error);
        }
    };

    const handleShowReviewResult = async (review: any) => {
        try {
            const resultData = await getReviewResult(review.id);
            setSelectedReviewResult(resultData);
            setPreviewItem(null);
            setActiveReview(null);
        } catch (error) {
            console.error('Error fetching review result:', error);
        }
    };

    const checkIfReviewHasResult = async (review: any) => {
        try {
            const resultData = await getReviewResult(review.id);
            return resultData && resultData.answers;
        } catch (error) {
            console.error('Error checking review result:', error);
            return false;
        }
    };

    const handleActivityClick = (activity: any) => {
        setShowForums(false);
        setPreviewItem({ type: 'activity', data: activity });
        setSelectedSession(null);
        setSelectedExamResult(null);
        setSelectedReviewResult(null);
        setSelectedActivityResult(null);
        setActiveExam(null);
        setActiveReview(null);
        setActiveActivity(null);
    };


    const handleJoinActivity = async (activity: any) => {
        try {
            // Trigger presence update on click
            markSessionPresent(activity.id).then(() => {
                queryClient.invalidateQueries({ queryKey: ['group-progress', groupId] });
            });
            const activityData = await getActivityData(activity.id);
            setActiveActivity({ ...activityData, activityItemId: activity.id });
            setPreviewItem(null);
        } catch (error) {
            console.error('Error fetching activity data:', error);
        }
    };

    const handleShowActivityResult = async (activity: any) => {
        try {
            const resultData = await getActivityResult(activity.id);
            setSelectedActivityResult(resultData);
            setPreviewItem(null);
            setActiveActivity(null);
        } catch (error) {
            console.error('Error fetching activity result:', error);
        }
    };

    const checkIfActivityHasResult = async (activity: any) => {
        try {
            const resultData = await getActivityResult(activity.id);
            return resultData && resultData.success && (resultData.message || resultData.data);
        } catch (error) {
            console.error('Error checking activity result:', error);
            return false;
        }
    };

    // If an exam result is selected, show exam result (Fullscreen)
    if (selectedExamResult) {
        return <ExamResult resultData={selectedExamResult} courseName={courseName} />;
    }

    if (selectedReviewResult) {
        return <ReviewResult resultData={selectedReviewResult} courseName={courseName} />;
    }

    if (activeReview) {
        return (
            <ReviewInterface 
                reviewData={activeReview} 
                courseName={courseName} 
                reviewItemId={activeReview.reviewItemId}
                onReviewSubmitted={() => {
                    queryClient.invalidateQueries({ queryKey: ['group-progress', groupId] });
                }}
            />
        );
    }

    if (selectedActivityResult) {
        return <ActivityResult resultData={selectedActivityResult} courseName={courseName} />;
    }

    if (activeActivity) {
        return (
            <ActivityInterface 
                activityData={activeActivity} 
                courseName={courseName} 
                activityItemId={activeActivity.activityItemId}
                onActivitySubmitted={() => {
                    queryClient.invalidateQueries({ queryKey: ['group-progress', groupId] });
                    // Force refresh all activity view queries to show the "View Result" button
                    queryClient.invalidateQueries({ 
                        predicate: (query) => !!query.queryKey[0]?.toString().includes('/user/activities/view')
                    });
                }}
            />
        );
    }

    if (activeExam) {
        return (
            <ExamInterface 
                examData={activeExam} 
                courseName={courseName} 
                onExamSubmitted={async () => {
                    // Refresh group progress after exam
                    queryClient.invalidateQueries({ queryKey: ['group-progress', groupId] });
                    // Fetch result and show it
                    await handleShowResult(activeExam.exam || activeExam);
                    setActiveExam(null);
                }}
            />
        );
    }

    const renderMainView = () => {
        if (showForums) {
            return <ForumsInterface groupId={groupId} courseName={courseName} />;
        }

        // Default: Video, Zoom Link or Item Preview

        return (
            <div className='bg-white rounded-lg overflow-hidden border border-gray-100'>
                {previewItem ? (
                    <div className="min-h-[600px] flex flex-col items-center justify-center gap-6 bg-gradient-to-br from-purple-50 to-indigo-50 p-8 text-center">
                            <div className="bg-white rounded-2xl shadow-xl p-10 flex flex-col items-center gap-6 max-w-md w-full border border-purple-100">
                            <div className={cn(
                                "size-24 rounded-3xl flex items-center justify-center shadow-lg transform transition-transform hover:scale-105",
                                previewItem.type === 'exam' ? "bg-blue-600 shadow-blue-200" : 
                                previewItem.type === 'activity' ? "bg-orange-500 shadow-orange-200" : 
                                "bg-yellow-500 shadow-yellow-200"
                            )}>
                                {previewItem.type === 'exam' ? <FileQuestion className="h-12 w-12 text-white" /> : 
                                    previewItem.type === 'activity' ? <Gamepad2 className="h-12 w-12 text-white" /> : 
                                    <Star className="h-12 w-12 text-white" />}
                            </div>
                            <div>
                                <h3 className="text-2xl font-bold text-gray-900 mb-2">
                                    {previewItem.data.name || previewItem.data.topic || previewItem.data.title || (previewItem.type === 'exam' ? t('exams') : previewItem.type === 'activity' ? t('activities') : t('reviews'))}
                                </h3>
                                <p className="text-gray-500 text-sm max-w-xs mx-auto">
                                    {previewItem.type === 'exam' ? (isArabic ? 'هذا الاختبار يحتوي على ' + (previewItem.data.nb_questions || 0) + ' سؤال.' : `This exam contains ${previewItem.data.nb_questions || 0} questions.`) : 
                                        isArabic ? 'الرجاء الضغط على الزر أدناه للبدء' : 'Please click the button below to start.'}
                                </p>
                            </div>
                            <Button 
                                size="lg"
                                onClick={() => {
                                    if (previewItem.type === 'exam') handleJoinExam(previewItem.data);
                                    else if (previewItem.type === 'activity') handleJoinActivity(previewItem.data);
                                    else if (previewItem.type === 'review') handleJoinReview(previewItem.data);
                                }}
                                className={cn(
                                    "w-full h-14 text-lg font-bold rounded-xl shadow-lg hover:shadow-xl active:scale-95 transition-all gap-2",
                                    previewItem.type === 'exam' ? "bg-blue-600 hover:bg-blue-700" : 
                                    previewItem.type === 'activity' ? "bg-orange-500 hover:bg-orange-600" : 
                                    "bg-yellow-500 hover:bg-yellow-600"
                                )}
                            >
                                {previewItem.type === 'exam' ? (isArabic ? 'انضم للاختبار' : 'Join Exam') : 
                                    previewItem.type === 'activity' ? (isArabic ? 'انضم للنشاط' : 'Join Activity') : 
                                    (isArabic ? 'انضم للتقييم' : 'Join Review')}
                                {isArabic ? <ChevronLeft className="size-5" /> : <ChevronRight className="size-5" />}
                            </Button>
                            </div>
                    </div>
                ) : selectedSession && currentVideoInfo?.type ? (
                    // ── YouTube or Vimeo ─────────────────────────
                    <VideoPlayer
                        embedUrl={currentVideoInfo.embedUrl}
                        type={currentVideoInfo.type}
                        sessionId={selectedSession.id}
                        title={selectedSession.topic || selectedSession.title}
                    />
                ) : selectedSession?.join_url ? (
                    // ── External / Zoom link ──────────────────────
                    <div className="min-h-[500px] flex flex-col items-center justify-center gap-6 bg-gradient-to-br from-blue-50 to-indigo-50 p-8">
                        <div className="bg-white rounded-2xl shadow-lg p-8 flex flex-col items-center gap-5 max-w-sm w-full">
                            {/* Zoom-style icon */}
                            <div className="size-20 rounded-2xl bg-blue-600 flex items-center justify-center shadow-md">
                                <Video className="h-10 w-10 text-white" />
                            </div>
                            <div className="text-center">
                                <h3 className="text-lg font-bold text-gray-900 mb-1">
                                    {selectedSession.topic || selectedSession.title || t('selectVideo')}
                                </h3>
                                <div className="space-y-2 mb-2">
                                    <p className="text-sm text-gray-600 font-medium flex items-center justify-start gap-2">
                                        <Calendar className="size-4 text-blue-600" />
                                        {selectedSession.date}
                                    </p>
                                    {selectedSession.start_time && (
                                        <p className="text-sm text-gray-600 font-medium flex items-center justify-start gap-2">
                                            <Clock className="size-4 text-blue-600" />
                                            {selectedSession.start_time.substring(0, 5)} 
                                            {selectedSession.end_time && ` - ${selectedSession.end_time.substring(0, 5)}`}
                                        </p>
                                    )}
                                    <p className="text-sm text-gray-500 flex items-center justify-start gap-2 ">
                                        <Video className="size-4 text-blue-600 shrink-0" />
                                        <span>
                                            {selectedSession.type === 'online' ? (isArabic ? 'جلسة أونلاين' : 'Online Session') : (isArabic ? 'جلسة' : 'Session')}
                                            {selectedSession.duration ? ` · ${selectedSession.duration} ${t('min')}` : ''}
                                        </span>
                                    </p>
                                </div>
                            </div>
                            <a
                                href={selectedSession.join_url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="w-full flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 active:scale-95 text-white font-bold py-3 px-6 rounded-xl transition-all duration-200 shadow-md hover:shadow-lg"
                            >
                                <Maximize className="h-4 w-4" />
                                {isArabic ? 'انضم للجلسة' : 'Join Session'}
                            </a>
                        </div>
                    </div>
                ) : (
                    // ── No session selected ───────────────────────
                    <div className="py-40 text-center bg-gradient-to-br from-gray-50 to-gray-100 min-h-[600px] flex flex-col items-center justify-center">
                        <div className="bg-white rounded-full p-8 w-fit mx-auto mb-8 shadow-sm">
                            <Video className="h-16 w-16 text-purple-600" />
                        </div>
                        <h3 className="text-xl font-semibold text-gray-800 mb-3">{t('selectVideo')}</h3>
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className='min-h-screen'>
            {curriculumItems.length === 0 ? (
                <Card className='min-h-screen grid place-items-center'>
                    <CardContent className="py-16 text-center">
                        <VideoOff className="size-14 text-gray-300 mx-auto mb-4" />
                        <h3 className="text-xl font-semibold mb-2">{t('noSessions')}</h3>
                        <p className="text-gray-600 mb-6">{t('noSessionsDescription')}</p>
                        <Button 
                            variant="outline"
                            asChild
                            className="gap-2"
                        >
                            <Link href="/dashboard/programs">
                                {isArabic ? <ArrowRight className="size-4" /> : <ArrowLeft className="size-4" />}
                                {t('back')}
                            </Link>
                        </Button>
                    </CardContent>
                </Card>
            ) : (
                <>
                    {/* Header with gradient background - Full Width */}
                    <div className="bg-gradient-to-r from-purple-600 via-purple-700 to-indigo-700 text-white px-6 py-4 sticky top-0 z-40 w-full">
                        <div className="flex items-center justify-between flex-wrap gap-4">
                            {/* Left side - Video info */}
                            <div className="flex-1 flex items-center gap-3">
                                <Button 
                                    variant="ghost" 
                                    size="icon" 
                                    className="text-white bg-white/20 shrink-0"
                                    asChild
                                >
                                    <Link href="/dashboard">
                                        <TvMinimal className="size-5" />
                                    </Link>
                                </Button>
                                {courseName && (
                                    <h1 className="text-sm font-semibold opacity-90">
                                        {courseName}
                                    </h1>
                                )}
                            </div>

                            {/* Right side - Navigation buttons + Language Switcher */}
                            <div className="flex items-center gap-3 flex-wrap justify-center ">
                                {currentNavItem && (
                                    <>
                                        <Button
                                            onClick={goToPreviousItem}
                                            disabled={currentItemIndex === 0}
                                            variant="secondary"
                                            size="sm"
                                            className="bg-white/20 hover:bg-white/30 text-white border-0"
                                        >
                                            {isArabic ? <ChevronRight className="size-4" /> : <ChevronLeft className="size-4" />}
                                            {t('previous')}
                                        </Button>
                                        <div className="text-sm font-medium px-3 py-1 bg-white/20 rounded">
                                            {currentItemIndex + 1} / {navigatableItems.length}
                                        </div>
                                        <Button
                                            onClick={goToNextItem}
                                            disabled={isNextDisabled}
                                            variant="secondary"
                                            size="sm"
                                            className={`bg-white/20 hover:bg-white/30 text-white border-0 transition-all ${isNextDisabled ? 'opacity-50 grayscale' : ''}`}
                                        >
                                            <span className="flex items-center gap-1.5">
                                                {t('next')}
                                                {secondsRemaining > 0 && (
                                                    <span className="text-[10px] bg-black/20 px-1.5 py-0.5 rounded-full font-mono">
                                                        {formatTime(secondsRemaining)}
                                                    </span>
                                                )}
                                            </span>
                                            {isArabic ? <ChevronLeft className="size-4" /> : <ChevronRight className="size-4" />}
                                        </Button>
                                        {selectedSession?.file && (
                                            <Button
                                                variant="secondary"
                                                size="sm"
                                                className="bg-white/20 hover:bg-white/30 text-white border-0"
                                                asChild
                                            >
                                                <a
                                                    href={`https://tr.ivorytraining.com/${selectedSession.file}`}
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                >
                                                    <FileDown className="size-4" />
                                                </a>
                                            </Button>
                                        )}
                                    </>
                                )}
                                
                                {/* Circular Progress Bar */}
                                <div className="relative flex items-center justify-center">
                                    <svg className="size-12 -rotate-90" viewBox="0 0 48 48">
                                        <circle
                                            cx="24"
                                            cy="24"
                                            r="20"
                                            fill="none"
                                            stroke="rgba(255, 255, 255, 0.2)"
                                            strokeWidth="4"
                                        />
                                        <circle
                                            cx="24"
                                            cy="24"
                                            r="20"
                                            fill="none"
                                            stroke="white"
                                            strokeWidth="4"
                                            strokeDasharray={`${2 * Math.PI * 20}`}
                                            strokeDashoffset={`${2 * Math.PI * 20 * (1 - progress / 100)}`}
                                            strokeLinecap="round"
                                            className="transition-all duration-500"
                                        />
                                    </svg>
                                    <div className="absolute inset-0 flex items-center justify-center">
                                        <span className="text-xs font-bold text-white">{progress}%</span>
                                    </div>
                                </div>



                                <LanguageSwitcher className="bg-white/20 hover:bg-white/30 text-white border-0" seeLang={true} />
                            </div>
                        </div>
                    </div>

                    <div className={`grid ${isSidebarOpen ? 'md:grid-cols-[350px_1fr]' : 'grid-cols-1'} max-md:gap-8 relative`}>
                        {/* Show sidebar button when closed */}

                        {!isSidebarOpen && (
                            <Button
                                variant="ghost"
                                size="icon"
                                className="absolute top-4 right-4 z-50 h-10 w-10 bg-white shadow-md hover:bg-gray-50"
                                onClick={() => setIsSidebarOpen(true)}
                            >
                                <List className="size-5" />
                            </Button>
                        )}

                        {/* Content sidebar */}
                        {isSidebarOpen && (
                            <Card className="h-fit sticky top-6 border-0 shadow-none">
                                <CardHeader className="flex flex-row items-center justify-start gap-2 space-y-0 pb-4 border-b mb-4">
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8 text-gray-500 hover:text-gray-900"
                                        onClick={() => setIsSidebarOpen(!isSidebarOpen)}
                                    >
                                        <Maximize className="size-5" />
                                    </Button>
                                    <div className="flex items-center gap-4">
                                        <button 
                                            onClick={() => setShowForums(false)}
                                            className={cn(
                                                "text-sm font-bold transition-colors",
                                                !showForums ? "text-purple-600 border-b-2 border-purple-600 pb-1" : "text-gray-500 hover:text-gray-700"
                                            )}
                                        >
                                            {t('curriculum')}
                                        </button>
                                        <button 
                                            onClick={() => setShowForums(true)}
                                            className={cn(
                                                "text-sm font-bold transition-colors",
                                                showForums ? "text-purple-600 border-b-2 border-purple-600 pb-1" : "text-gray-500 hover:text-gray-700"
                                            )}
                                        >
                                            {t('forums')}
                                        </button>
                                    </div>

                                </CardHeader>
                                <CardContent className="px-2 pt-0">
                                    <div className="space-y-4 overflow-y-scroll px-1 max-h-[calc(100vh-180px)] max-md:max-h-96 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
                                        
                                        {sessions.map((item, index) => {
                                            if (item.model === 'session') {
                                                if (isPreviewMode && item.is_free !== 1 && item.id !== initialSessionId) return null;
                                                const isSelected = selectedSession?.id === item.id;
                                                const videoInfo = seeIfYoutubeOrVimeo(item.join_url);
                                                return (
                                                    <VideoBox
                                                        key={`session-${item.id}`}
                                                        session={item}
                                                        videoInfo={videoInfo}
                                                        index={index} 
                                                        isSelected={isSelected}
                                                        setSelectedSession={handleSessionSelect}
                                                        moduleTitle={courseName}
                                                    />
                                                );
                                            }

                                            if (item.model === 'module') {
                                                const moduleContent = item.content_items || item.session_groups || [];
                                                
                                                let filteredContent = moduleContent;
                                                if (isPreviewMode) {
                                                    filteredContent = moduleContent.filter((s: any) => s.is_free === 1 || s.id === initialSessionId);
                                                    if (filteredContent.length === 0) return null;
                                                }

                                                const hasVideos = filteredContent.some((s: any) => s.model === 'session' && s.join_url);
                                                const isExpanded = expandedModules.includes(item.id.toString());

                                                return (
                                                    <Accordion key={`module-${item.id}`} type='single' collapsible value={isExpanded ? item.id.toString() : undefined}>
                                                        <AccordionItem value={item.id.toString()} className="border border-gray-200 rounded-lg overflow-hidden shadow-sm">
                                                            <AccordionTrigger 
                                                                onClick={() => toggleModule(item.id.toString())}
                                                                className="p-3 bg-white hover:bg-gray-50 transition-colors hover:no-underline"
                                                            >
                                                                <span className="flex items-center justify-between w-full pr-2">
                                                                    <span className="flex items-center gap-2">
                                                                        {item.is_completed && (
                                                                            <div className="size-5 rounded-full bg-blue-100 flex items-center justify-center flex-shrink-0">
                                                                                <svg className="size-3 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M5 13l4 4L19 7" />
                                                                                </svg>
                                                                            </div>
                                                                        )}
                                                                        <span className="font-semibold text-gray-800 text-sm text-start">
                                                                            {item.title}
                                                                        </span>
                                                                    </span>
                                                                    <span className="flex items-center gap-2">
                                                                        {hasVideos && (
                                                                            <span className="text-[10px] bg-purple-50 text-purple-600 px-2 py-0.5 rounded-full font-medium border border-purple-100 flex items-center gap-1">
                                                                                <span className="size-1.5 rounded-full bg-purple-500 block" />
                                                                                {filteredContent.length}
                                                                            </span>
                                                                        )}
                                                                    </span>
                                                                </span>
                                                            </AccordionTrigger>
                                                            <AccordionContent className="border-t bg-gray-50/50 pt-0">
                                                                <div className="flex flex-col gap-1 p-1">
                                                                {filteredContent.map((subItem: any, subIndex: number) => {
                                                                    if (subItem.model === 'session') {
                                                                        const isSelected = selectedSession?.id === subItem.id;
                                                                        const isCompleted = subItem.is_completed || completedItemIds.has(subItem.id);
                                                                        const videoInfo = seeIfYoutubeOrVimeo(subItem.join_url);
                                                                        return (
                                                                            <VideoBox
                                                                                key={`session-${subItem.id}`}
                                                                                session={{...subItem, is_completed: isCompleted}}
                                                                                videoInfo={videoInfo}
                                                                                index={subIndex}
                                                                                isSelected={isSelected}
                                                                                setSelectedSession={handleSessionSelect}
                                                                                moduleTitle={item.title}
                                                                            />
                                                                        );
                                                                    } else if (subItem.model === 'exam') {
                                                                        const isSelected = previewItem?.type === 'exam' && previewItem.data.id === subItem.id;
                                                                        return (
                                                                            <ExamItem
                                                                                key={`exam-${subItem.id}`}
                                                                                exam={subItem}
                                                                                onExamClick={handleExamClick}
                                                                                onShowResult={handleShowResult}
                                                                                isSelected={isSelected}
                                                                            />
                                                                        );
                                                                    } else if (subItem.model === 'activity') {
                                                                        const isSelected = previewItem?.type === 'activity' && previewItem.data.id === subItem.id;
                                                                        return (
                                                                            <ActivityItem
                                                                                key={`activity-${subItem.id}`}
                                                                                activity={subItem}
                                                                                onActivityClick={handleActivityClick}
                                                                                onShowResult={handleShowActivityResult}
                                                                                isSelected={isSelected}
                                                                            />
                                                                        );
                                                                    } else if (subItem.model === 'review') {
                                                                        const isSelected = previewItem?.type === 'review' && previewItem.data.id === subItem.id;
                                                                        return (
                                                                            <ReviewItem
                                                                                key={`review-${subItem.id}`}
                                                                                review={subItem}
                                                                                onReviewClick={handleReviewClick}
                                                                                onShowResult={handleShowReviewResult}
                                                                                isSelected={isSelected}
                                                                            />
                                                                        );
                                                                    }
                                                                    return null;
                                                                })}
                                                                </div>
                                                            </AccordionContent>
                                                        </AccordionItem>
                                                    </Accordion>
                                                );
                                            }

                                            if (item.model === 'exam') {
                                                if (isPreviewMode) return null;
                                                const isSelected = previewItem?.type === 'exam' && previewItem.data.id === item.id;
                                                return (
                                                    <ExamItem
                                                        key={`exam-${item.id}`}
                                                        exam={item}
                                                        onExamClick={handleExamClick}
                                                        onShowResult={handleShowResult}
                                                        isSelected={isSelected || (!selectedSession && !previewItem && initialExamId === item.id)}
                                                    />
                                                );
                                            }

                                            if (item.model === 'activity') {
                                                if (isPreviewMode) return null;
                                                const isSelected = previewItem?.type === 'activity' && previewItem.data.id === item.id;
                                                return (
                                                    <ActivityItem
                                                        key={`activity-${item.id}`}
                                                        activity={item}
                                                        onActivityClick={handleActivityClick}
                                                        onShowResult={handleShowActivityResult}
                                                        isSelected={isSelected || (!selectedSession && !previewItem && initialActivityId === item.id)}
                                                    />
                                                );
                                            }

                                            if (item.model === 'review') {
                                                if (isPreviewMode) return null;
                                                const isSelected = previewItem?.type === 'review' && previewItem.data.id === item.id;
                                                return (
                                                    <ReviewItem
                                                        key={`review-${item.id}`}
                                                        review={item}
                                                        onReviewClick={handleReviewClick}
                                                        onShowResult={handleShowReviewResult}
                                                        isSelected={isSelected || (!selectedSession && !previewItem && initialReviewId === item.id)}
                                                    />
                                                );
                                            }

                                            return null;
                                        })}

                                        {/* Certificate Section - Always Visible as Motivator */}
                                        <div className={`p-4 rounded-xl border shadow-sm mt-4 mb-4 transition-all duration-500 ${
                                            canDownloadCertificate 
                                                ? "bg-gradient-to-br from-purple-50 to-indigo-50 border-purple-100" 
                                                : "bg-gray-50 border-gray-200 opacity-80"
                                        }`}>
                                            <div className="flex items-start gap-3 mb-3">
                                                <div className={` p-2 rounded-full shadow-lg ${
                                                    canDownloadCertificate 
                                                        ? "bg-purple-600 text-white shadow-purple-100" 
                                                        : "bg-gray-400 text-white shadow-gray-100"
                                                }`}>
                                                    {canDownloadCertificate ? <Award className="size-5" /> : <Lock className="size-5" />}
                                                </div>
                                                <div className="flex-1">
                                                    <h4 className={`font-bold text-sm leading-tight ${
                                                        canDownloadCertificate ? "text-purple-900" : "text-gray-700"
                                                    }`}>
                                                        {canDownloadCertificate 
                                                            ? (isArabic ? "أنت أكملت الدورة بنجاح!" : "You have successfully completed the course!")
                                                            : (isArabic ? "الشهادة الاحترافية" : "Professional Certificate")
                                                        }
                                                    </h4>
                                                    <p className={`text-[11px] mt-1 font-medium ${
                                                        canDownloadCertificate ? "text-purple-700" : "text-gray-500"
                                                    }`}>
                                                        {canDownloadCertificate 
                                                            ? (isArabic ? "حمل شهادتك الآن" : "Download your certificate now")
                                                            : (isArabic ? "أكمل متطلبات الدورة لفتح الشهادة" : "Complete course requirements to unlock")
                                                        }
                                                    </p>
                                                </div>
                                            </div>
                                            <Button
                                                onClick={() => canDownloadCertificate && downloadCertificate.mutate({})}
                                                disabled={downloadCertificate.isPending || !canDownloadCertificate}
                                                className={`w-full font-bold gap-2 shadow-md transition-all ${
                                                    canDownloadCertificate 
                                                        ? "bg-purple-600 hover:bg-purple-700 text-white border-0 active:scale-95" 
                                                        : "bg-gray-200 text-gray-500 border-gray-300 cursor-not-allowed"
                                                }`}
                                                size="sm"
                                            >
                                                {downloadCertificate.isPending ? (
                                                    <Loader className="size-4 animate-spin" />
                                                ) : (
                                                    canDownloadCertificate ? <Download className="size-4" /> : <Lock className="size-4" />
                                                )}
                                                {isArabic ? "حمل الشهادة" : "Download Certificate"}
                                            </Button>
                                        </div>
                                        
                                        {/* Spacer to ensure the bottom content is accessible */}
                                        <div className="h-20" />
                                    </div>
                                </CardContent>
                            </Card>
                        )}

                        {/* Main Content Area */}
                        <div className='max-md:order-first p-4 md:p-6 h-full max-h-[calc(100vh-100px)] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200'>
                            <div className="flex flex-col gap-6 ">
                                {renderMainView()}
                            </div>
                        </div>

                    </div>
                </>
            )}
        </div>
    );
}