'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/AuthContext';
import { toast } from '@/context/ToastContext';
import AuthModal from '@/components/AuthModal';
import RegistrationModal, { RegistrationModalSelectedItem } from '@/components/RegistrationModal';
import {
  ArrowLeft,
  Sparkles,
  Layers,
  Video,
  Clock,
  CheckCircle2,
  ArrowRight,
  BookOpen,
  ChevronDown,
  ShieldCheck,
  GraduationCap,
  Award,
  Zap,
  PlayCircle,
  Calendar,
} from 'lucide-react';

interface CourseItem {
  _id: string;
  title: string;
  slug: string;
  level?: string;
  courseType: 'full_level' | 'sub_course' | 'individual_lesson';
  parentCourse?: {
    _id: string;
    title: string;
    level?: string;
    slug?: string;
  } | string;
  regularPrice: number;
  offerPrice?: number;
  description?: string;
  isPublished?: boolean;
  validityMonths?: number;
}

interface LessonItem {
  _id: string;
  title: string;
  slug: string;
  level?: string;
  course?: {
    _id: string;
    title: string;
  } | string;
  durationMinutes?: number;
  regularPrice: number;
  offerPrice?: number;
  price?: number;
}

export default function CourseDetailPage({
  params,
}: {
  params: { id: string } | Promise<{ id: string }>;
}) {
  const { user } = useAuth();
  const [courseId, setCourseId] = useState<string>('');
  const [mainCourse, setMainCourse] = useState<CourseItem | null>(null);
  const [subCourses, setSubCourses] = useState<CourseItem[]>([]);
  const [allLessons, setAllLessons] = useState<LessonItem[]>([]);
  const [allCourses, setAllCourses] = useState<CourseItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  // Interactive UI State
  const [expandedSubCourses, setExpandedSubCourses] = useState<Record<string, boolean>>({});

  // Registration & Auth Modal State
  const [isRegistrationOpen, setIsRegistrationOpen] = useState(false);
  const [authModalOpen, setAuthModalOpen] = useState(false);
  const [selectedItemForReg, setSelectedItemForReg] = useState<RegistrationModalSelectedItem | null>(null);

  useEffect(() => {
    if (!params) return;
    if (typeof (params as any).then === 'function') {
      (params as any).then((p: { id: string }) => {
        if (p?.id) setCourseId(p.id);
      });
    } else if ((params as any).id) {
      setCourseId((params as any).id);
    }
  }, [params]);

  const [userSubscriptions, setUserSubscriptions] = useState<any[]>([]);

  useEffect(() => {
    if (!courseId) return;

    const fetchDetailData = async () => {
      setLoading(true);
      setError('');

      try {
        const promises: Promise<any>[] = [
          apiRequest(`/courses/${courseId}`),
          apiRequest('/courses'),
          apiRequest('/lessons'),
        ];

        if (user && user.role !== 'admin' && user.role !== 'super_admin') {
          promises.push(apiRequest('/subscriptions'));
        }

        const [courseRes, allCoursesRes, lessonsRes, subRes] = await Promise.all(promises);

        if (courseRes.success && courseRes.course) {
          setMainCourse(courseRes.course);
        } else {
          setError(courseRes.error || 'Course not found');
        }

        if (allCoursesRes.success && Array.isArray(allCoursesRes.courses)) {
          setAllCourses(allCoursesRes.courses);
          // Filter sub-courses belonging to this main course
          const subs = allCoursesRes.courses.filter((c: CourseItem) => {
            if (c.courseType !== 'sub_course') return false;
            const parentId = typeof c.parentCourse === 'object' ? c.parentCourse?._id : c.parentCourse;
            return parentId === courseId;
          });
          setSubCourses(subs);

          // Expand all sub-courses by default for quick view
          const initialExpandState: Record<string, boolean> = {};
          subs.forEach((s) => {
            initialExpandState[s._id] = true;
          });
          setExpandedSubCourses(initialExpandState);
        }

        if (lessonsRes.success && Array.isArray(lessonsRes.lessons)) {
          setAllLessons(lessonsRes.lessons);
        }

        if (subRes && subRes.success && Array.isArray(subRes.subscriptions)) {
          setUserSubscriptions(subRes.subscriptions);
        }
      } catch (err: any) {
        setError(err.message || 'Failed to load course details');
      } finally {
        setLoading(false);
      }
    };

    fetchDetailData();
  }, [courseId, user]);

  // Check if active unexpired subscription covers target item (course, subcourse, or lesson)
  const isItemPurchased = (itemId: string, itemType: 'course' | 'sub_course' | 'lesson') => {
    if (!user || userSubscriptions.length === 0) return false;

    return userSubscriptions.some((sub: any) => {
      if (sub.status !== 'active') return false;

      // Check date validity
      if (sub.expiresAt && new Date(sub.expiresAt) < new Date()) {
        return false;
      }

      const subCourseId = typeof sub.course === 'object' ? sub.course?._id : sub.course;

      // 1. If user bought full main level course, ALL sub-courses and lessons in this course are marked purchased
      if (subCourseId === mainCourse?._id) return true;

      // 2. Direct match
      if (subCourseId === itemId) return true;

      // 3. If checking a sub-course module, also check if sub.course is parent of this sub-course module
      if (itemType === 'sub_course') {
        const targetSubCourse = subCourses.find((s) => s._id === itemId);
        if (targetSubCourse) {
          const parentId = typeof targetSubCourse.parentCourse === 'object' ? targetSubCourse.parentCourse?._id : targetSubCourse.parentCourse;
          if (parentId === subCourseId) return true;
        }
      }

      // 4. If checking an individual lesson
      if (itemType === 'lesson') {
        const targetLesson = allLessons.find((l) => l._id === itemId);
        if (targetLesson) {
          const lessonCourseId = typeof targetLesson.course === 'object' ? targetLesson.course?._id : targetLesson.course;

          // Check if user bought the parent sub-course module of this lesson
          if (lessonCourseId === subCourseId) return true;

          // Check if user bought the main level course of the parent sub-course
          const parentSubCourse = allCourses.find((c) => c._id === lessonCourseId);
          if (parentSubCourse) {
            const grandParentId = typeof parentSubCourse.parentCourse === 'object' ? parentSubCourse.parentCourse?._id : parentSubCourse.parentCourse;
            if (grandParentId === subCourseId) return true;
          }
        }

        // Explicit lesson list check
        if (sub.lessons && sub.lessons.length > 0) {
          return sub.lessons.some((lId: any) => (typeof lId === 'string' ? lId : lId._id || lId.toString()) === itemId);
        }
      }

      return false;
    });
  };

  const toggleSubCourse = (id: string) => {
    setExpandedSubCourses((prev) => ({
      ...prev,
      [id]: !prev[id],
    }));
  };

  const handleEnroll = (item: RegistrationModalSelectedItem) => {
    if (!user || user.role === 'admin' || user.role === 'super_admin') {
      toast.error('Student login is required to enroll in a course.');
      setAuthModalOpen(true);
      return;
    }
    setSelectedItemForReg(item);
    setIsRegistrationOpen(true);
  };

  const courseOptions = allCourses.map((c) => {
    const price = c.offerPrice ?? c.regularPrice;
    return {
      label: `${c.title}${price ? ` - ${price} €` : ''}`,
      value: c._id,
      price,
    };
  });

  const renderPriceTag = (offerPrice?: number, regularPrice?: number) => {
    const finalPrice = offerPrice !== undefined && offerPrice !== null ? offerPrice : regularPrice;
    if (finalPrice === undefined || finalPrice === null || isNaN(Number(finalPrice))) {
      return null;
    }
    return `€${finalPrice}`;
  };

  // Direct lessons attached to this main course
  const directLessons = allLessons.filter((l) => {
    const cid = typeof l.course === 'object' ? l.course?._id : l.course;
    return cid === courseId;
  });

  // Calculate statistics
  const totalSubCoursesCount = subCourses.length;
  const subCourseIds = new Set(subCourses.map((s) => s._id));
  const subLessonsCount = allLessons.filter((l) => {
    const cid = typeof l.course === 'object' ? l.course?._id : l.course;
    return cid && subCourseIds.has(cid);
  }).length;
  const totalLessonsCount = directLessons.length + subLessonsCount;

  const calculateSavings = (regularPrice?: number, offerPrice?: number) => {
    if (regularPrice && offerPrice && regularPrice > offerPrice) {
      const savings = regularPrice - offerPrice;
      const percentage = Math.round((savings / regularPrice) * 100);
      return { savings, percentage };
    }
    return null;
  };

  const savingsInfo = mainCourse ? calculateSavings(mainCourse.regularPrice, mainCourse.offerPrice) : null;

  const activeMainSub = userSubscriptions.find((sub: any) => {
    const subCourseId = typeof sub.course === 'object' ? sub.course?._id : sub.course;
    return subCourseId === mainCourse?._id && sub.status === 'active';
  });

  return (
    <div className="w-full min-h-screen bg-[#FAF9F5] text-gray-900 pt-32 sm:pt-40 md:pt-44 pb-24">
      <div className="w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-5 space-y-8">

        {/* Navigation Breadcrumb */}
        <div>
          <Link
            href="/#courses"
            className="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-white border border-amber-200/80 text-gray-700 hover:text-black hover:border-amber-400 font-bold text-xs sm:text-sm shadow-xs hover:shadow-sm transition-all group"
          >
            <ArrowLeft className="w-4 h-4 text-amber-600 group-hover:-translate-x-0.5 transition-transform" />
            <span>Back to Course Catalog</span>
          </Link>
        </div>

        {loading ? (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start my-6 animate-pulse">
            {/* Left Content Column Skeleton */}
            <div className="lg:col-span-7 xl:col-span-8 space-y-8">
              {/* Header Hero Skeleton */}
              <div className="bg-white rounded-3xl border border-amber-200/70 p-6 sm:p-8 space-y-6 shadow-xs">
                <div className="flex gap-2">
                  <div className="h-6 w-24 bg-amber-200/60 rounded-full" />
                  <div className="h-6 w-32 bg-amber-100 rounded-full" />
                </div>
                <div className="h-10 w-3/4 bg-gray-200/80 rounded-xl" />
                <div className="space-y-2">
                  <div className="h-4 w-full bg-gray-100 rounded-md" />
                  <div className="h-4 w-5/6 bg-gray-100 rounded-md" />
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 pt-2">
                  <div className="h-16 bg-amber-50/80 rounded-2xl border border-amber-100/70" />
                  <div className="h-16 bg-amber-50/80 rounded-2xl border border-amber-100/70" />
                  <div className="h-16 bg-amber-50/80 rounded-2xl border border-amber-100/70 col-span-2 sm:col-span-1" />
                </div>
              </div>

              {/* Curriculum Modules Accordion Skeleton */}
              <div className="space-y-4">
                <div className="h-8 w-48 bg-gray-200/80 rounded-lg mb-4" />
                {[1, 2, 3].map((n) => (
                  <div key={n} className="bg-white rounded-2xl border border-amber-200/70 p-6 space-y-3 shadow-xs">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-xl bg-amber-200/60" />
                        <div className="h-6 w-48 bg-gray-200/80 rounded-lg" />
                      </div>
                      <div className="h-9 w-28 bg-[#FECE00]/40 rounded-xl" />
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Right Sticky Sidebar Skeleton */}
            <div className="lg:col-span-5 xl:col-span-4 space-y-6">
              <div className="bg-white rounded-3xl border-2 border-amber-200/80 p-6 sm:p-8 space-y-6 shadow-md">
                <div className="h-6 w-36 bg-amber-200/60 rounded-full" />
                <div className="h-12 w-44 bg-gray-200/80 rounded-xl" />
                <div className="h-14 w-full bg-[#FECE00]/50 rounded-2xl" />
                <div className="space-y-3 pt-2">
                  <div className="h-4 w-32 bg-gray-200/60 rounded-md" />
                  <div className="h-4 w-full bg-gray-100 rounded-md" />
                  <div className="h-4 w-full bg-gray-100 rounded-md" />
                  <div className="h-4 w-4/5 bg-gray-100 rounded-md" />
                </div>
              </div>
            </div>
          </div>
        ) : error || !mainCourse ? (
          <div className="bg-white rounded-3xl border border-red-200 p-12 text-center shadow-xs space-y-4 max-w-xl mx-auto my-12">
            <div className="w-12 h-12 rounded-full bg-red-100 text-red-600 flex items-center justify-center mx-auto font-bold text-lg">!</div>
            <h3 className="text-xl font-bold text-gray-900">Course Unavailable</h3>
            <p className="text-sm text-gray-600">{error || 'The course you are looking for could not be found.'}</p>
            <Link
              href="/#courses"
              className="inline-flex items-center justify-center px-6 py-3 rounded-xl bg-[#FECE00] hover:bg-[#e5b800] text-black font-extrabold text-xs tracking-wide uppercase transition shadow-sm"
            >
              Return to Catalog
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">

            {/* LEFT COLUMN: Course Details & Curriculum (7 / 12) */}
            <div className="lg:col-span-7 xl:col-span-8 space-y-8">

              {/* Header Hero Section */}
              <div className="bg-white rounded-3xl border border-amber-200/80 shadow-xs p-6 sm:p-8 relative overflow-hidden">
                <div className="absolute -top-12 -right-12 w-64 h-64 bg-[#FECE00]/15 rounded-full blur-3xl pointer-events-none" />

                {/* Level & Category Badges */}
                {/* <div className="flex flex-wrap items-center gap-2.5 mb-6">
                  {mainCourse.level && (
                    <span className="px-3.5 py-1 rounded-full bg-black text-[#FECE00] text-xs font-black uppercase tracking-wider shadow-xs flex items-center gap-1.5">
                      <GraduationCap className="w-3.5 h-3.5" />
                      Level {mainCourse.level}
                    </span>
                  )}
                  <span className="px-3.5 py-1 rounded-full bg-amber-100 text-amber-900 text-xs font-bold uppercase tracking-wider flex items-center gap-1.5">
                    <Award className="w-3.5 h-3.5 text-amber-700" />
                    Full Level Curriculum
                  </span>
                  {savingsInfo && (
                    <span className="px-3 py-1 rounded-full bg-red-500 text-white text-xs font-black uppercase tracking-wider animate-pulse">
                      SAVE {savingsInfo.percentage}%
                    </span>
                  )}
                </div> */}

                {/* Title */}
                <h1 className="text-3xl sm:text-4xl lg:text-5xl font-extrabold text-gray-900 tracking-tight leading-tight !m-0 !p-0">
                  {mainCourse.title}
                </h1>

                {/* Description */}
                {mainCourse.description ? (
                  <p className="text-gray-700 text-base sm:text-lg leading-relaxed font-normal mt-4">
                    {mainCourse.description}
                  </p>
                ) : (
                  <p className="text-gray-500 text-sm italic mt-4">
                    Master German language skills with this comprehensive structured course curriculum.
                  </p>
                )}

                {/* Quick Meta Stats Grid */}
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 pt-2">
                  <div className="p-3.5 bg-amber-50/60 rounded-2xl border border-amber-100/80 flex items-center gap-3">
                    <div className="w-9 h-9 rounded-xl bg-amber-100 text-amber-800 flex items-center justify-center shrink-0">
                      <Layers className="w-4 h-4" />
                    </div>
                    <div>
                      <div className="text-xs text-gray-500 font-semibold">Modules</div>
                      <div className="text-sm font-extrabold text-gray-900">{totalSubCoursesCount} Sub-Courses</div>
                    </div>
                  </div>

                  <div className="p-3.5 bg-amber-50/60 rounded-2xl border border-amber-100/80 flex items-center gap-3">
                    <div className="w-9 h-9 rounded-xl bg-amber-100 text-amber-800 flex items-center justify-center shrink-0">
                      <Video className="w-4 h-4" />
                    </div>
                    <div>
                      <div className="text-xs text-gray-500 font-semibold">Lessons</div>
                      <div className="text-sm font-extrabold text-gray-900">{totalLessonsCount} Video Lessons</div>
                    </div>
                  </div>

                  <div className="p-3.5 bg-amber-50/60 rounded-2xl border border-amber-100/80 flex items-center gap-3 col-span-2 sm:col-span-1">
                    <div className="w-9 h-9 rounded-xl bg-amber-100 text-amber-800 flex items-center justify-center shrink-0">
                      <Calendar className="w-4 h-4" />
                    </div>
                    <div>
                      <div className="text-xs text-gray-500 font-semibold">{activeMainSub ? 'Expires on' : 'Access'}</div>
                      <div className="text-sm font-extrabold text-gray-900">
                        {activeMainSub 
                          ? new Date(activeMainSub.expiryDate).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }) 
                          : mainCourse.validityMonths ? `${mainCourse.validityMonths} Months` : 'Full Access'}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* What You'll Learn / Key Highlights Box */}
              {/* <div className="bg-white rounded-3xl border border-amber-200/80 shadow-xs p-6 sm:p-8 space-y-4">
                <h3 className="text-lg font-extrabold text-gray-900 flex items-center gap-2">
                  <Sparkles className="w-5 h-5 text-amber-600" />
                  <span>Why Choose This Course?</span>
                </h3>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm text-gray-700 font-medium">
                  <div className="flex items-start gap-2.5 p-2 rounded-xl">
                    <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
                    <span>Structured step-by-step curriculum for rapid progress</span>
                  </div>
                  <div className="flex items-start gap-2.5 p-2 rounded-xl">
                    <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
                    <span>High-definition video lessons by expert German instructors</span>
                  </div>
                  <div className="flex items-start gap-2.5 p-2 rounded-xl">
                    <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
                    <span>Option to buy full course or individual modules</span>
                  </div>
                  <div className="flex items-start gap-2.5 p-2 rounded-xl">
                    <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
                    <span>Study at your own pace anytime on desktop or mobile</span>
                  </div>
                </div>
              </div> */}

              {/* Curriculum Breakdown Header */}
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-2xl bg-[#FECE00] text-black font-extrabold flex items-center justify-center shadow-xs">
                      <BookOpen className="w-5 h-5" />
                    </div>
                    <div>
                      <h2 className="text-2xl font-extrabold text-gray-900 tracking-tight">
                        Course Curriculum
                      </h2>
                      <p className="text-xs sm:text-sm text-gray-600 font-medium">
                        Explore all sub-course modules and lessons. Expand modules to see topics.
                      </p>
                    </div>
                  </div>
                </div>

                {subCourses.length === 0 && directLessons.length === 0 ? (
                  <div className="bg-white rounded-3xl border border-amber-200/80 p-12 text-center text-sm font-semibold text-gray-500">
                    No sub-course modules or video lessons uploaded for this course yet.
                  </div>
                ) : (
                  <div className="space-y-4">
                    {/* Sub-Courses Accordion Breakdown */}
                    {subCourses.map((subCourse, subIdx) => {
                      const subLessons = allLessons.filter((l) => {
                        const cid = typeof l.course === 'object' ? l.course?._id : l.course;
                        return cid === subCourse._id;
                      });

                      const isExpanded = !!expandedSubCourses[subCourse._id];

                      return (
                        <div
                          key={subCourse._id}
                          className="bg-white rounded-2xl border border-amber-200/80 shadow-xs overflow-hidden transition-all duration-200 hover:border-amber-300"
                        >
                          {/* Module Header Bar */}
                          <div
                            onClick={() => toggleSubCourse(subCourse._id)}
                            className="p-5 sm:p-6 bg-white hover:bg-amber-50/30 cursor-pointer transition flex flex-wrap items-center justify-between gap-4 select-none"
                          >
                            <div className="flex items-start sm:items-center gap-3.5 flex-1 min-w-[240px]">
                              <div className="w-8 h-8 rounded-xl bg-amber-100 text-amber-900 flex items-center justify-center shrink-0 font-black text-xs mt-0.5 sm:mt-0">
                                {subIdx + 1}
                              </div>
                              <div>
                                <div className="flex items-center gap-2">
                                  <span className="text-[10px] font-black uppercase text-amber-700 tracking-wider">
                                    Sub-Course Module
                                  </span>
                                </div>
                                <h3 className="text-lg font-extrabold text-gray-900 leading-snug">
                                  {subCourse.title}
                                </h3>
                                <p className="text-xs text-gray-500 font-medium mt-0.5">
                                  Includes {subLessons.length} video lesson{subLessons.length !== 1 ? 's' : ''}
                                </p>
                              </div>
                            </div>

                            {/* Price & Actions Right */}
                            <div className="flex items-center gap-3 shrink-0 ml-auto" onClick={(e) => e.stopPropagation()}>
                              {renderPriceTag(subCourse.offerPrice, subCourse.regularPrice) && (
                                <span className="text-base font-extrabold text-gray-900">
                                  {renderPriceTag(subCourse.offerPrice, subCourse.regularPrice)}
                                </span>
                              )}

                              {subLessons.length > 0 && (
                                <>
                                  {isItemPurchased(subCourse._id, 'sub_course') ? (
                                    <Link
                                      href="/student/dashboard"
                                      className="px-4 py-2 rounded-xl bg-emerald-50 border border-emerald-300 text-emerald-800 text-xs font-black shadow-xs flex items-center gap-1.5 hover:bg-emerald-100 transition"
                                    >
                                      <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                                      <span>Purchased</span>
                                    </Link>
                                  ) : (
                                    <button
                                      type="button"
                                      onClick={() =>
                                        handleEnroll({
                                          id: subCourse._id,
                                          title: subCourse.title,
                                          price: subCourse.offerPrice ?? subCourse.regularPrice,
                                          type: 'sub_course',
                                          level: subCourse.level,
                                        })
                                      }
                                      className="px-4 py-2 rounded-xl bg-[#FECE00] hover:bg-black text-black hover:text-[#FECE00] text-xs font-extrabold shadow-xs transition flex items-center gap-1.5 cursor-pointer active:scale-95"
                                    >
                                      <span>Enroll Module</span>
                                      <ArrowRight className="w-3.5 h-3.5" />
                                    </button>
                                  )}
                                </>
                              )}

                              <button
                                type="button"
                                onClick={() => toggleSubCourse(subCourse._id)}
                                className="p-2 rounded-xl hover:bg-amber-100 text-gray-500 hover:text-gray-900 transition"
                                title={isExpanded ? 'Collapse' : 'Expand'}
                              >
                                <ChevronDown
                                  className={`w-5 h-5 transition-transform duration-200 ${isExpanded ? 'rotate-180 text-amber-700' : ''
                                    }`}
                                />
                              </button>
                            </div>
                          </div>

                          {/* Nested Video Lessons (Collapsible) */}
                          {isExpanded && (
                            <div className="border-t border-amber-100 bg-amber-50/20 p-4 sm:p-6 space-y-3">
                              <h4 className="text-xs font-black uppercase tracking-wider text-gray-500 flex items-center gap-1.5 mb-2">
                                <PlayCircle className="w-4 h-4 text-amber-600" />
                                <span>Lessons in this Module</span>
                              </h4>

                              {subLessons.length === 0 ? (
                                <p className="text-xs text-gray-400 italic py-2">
                                  No individual video lessons uploaded yet for this module.
                                </p>
                              ) : (
                                <div className="space-y-2.5">
                                  {subLessons.map((lesson, idx) => (
                                    <div
                                      key={lesson._id}
                                      className="p-3.5 bg-white hover:bg-amber-50/70 rounded-xl border border-amber-200/60 flex flex-wrap items-center justify-between gap-3 text-xs transition shadow-2xs"
                                    >
                                      <div className="flex items-center gap-3">
                                        <div className="w-7 h-7 rounded-lg bg-gray-100 text-gray-800 flex items-center justify-center shrink-0 font-extrabold text-xs">
                                          {idx + 1}
                                        </div>
                                        <div>
                                          <span className="font-extrabold text-gray-900 text-sm block">
                                            {lesson.title}
                                          </span>
                                          {lesson.durationMinutes ? (
                                            <span className="text-[11px] font-medium text-gray-500 flex items-center gap-1 mt-0.5">
                                              <Clock className="w-3.5 h-3.5 text-amber-600" />
                                              <span>{lesson.durationMinutes} mins</span>
                                            </span>
                                          ) : null}
                                        </div>
                                      </div>

                                      <div className="flex items-center gap-3">
                                        {(() => {
                                          const lessonPrice = lesson.price ?? lesson.offerPrice ?? lesson.regularPrice;
                                          if (lessonPrice !== undefined && lessonPrice !== null && !isNaN(Number(lessonPrice))) {
                                            return (
                                              <span className="font-extrabold text-gray-900 text-xs">
                                                €{lessonPrice}
                                              </span>
                                            );
                                          }
                                          return (
                                            <span className="font-semibold text-gray-400 text-[11px]">
                                              Included in Module
                                            </span>
                                          );
                                        })()}

                                        {isItemPurchased(lesson._id, 'lesson') ? (
                                          <Link
                                            href="/student/dashboard"
                                            className="px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-300 text-emerald-800 font-extrabold text-[11px] flex items-center gap-1 hover:bg-emerald-100 transition"
                                          >
                                            <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
                                            <span>Purchased</span>
                                          </Link>
                                        ) : (
                                          <button
                                            type="button"
                                            onClick={() => {
                                              const lessonPrice = lesson.price ?? lesson.offerPrice ?? lesson.regularPrice;
                                              handleEnroll({
                                                id: lesson._id,
                                                title: lesson.title,
                                                price: lessonPrice,
                                                type: 'lesson',
                                                level: lesson.level,
                                              });
                                            }}
                                            className="px-3 py-1.5 rounded-lg bg-black hover:bg-[#FECE00] text-[#FECE00] hover:text-black font-extrabold text-[11px] transition flex items-center gap-1 cursor-pointer active:scale-95"
                                          >
                                            <span>Enroll</span>
                                          </button>
                                        )}
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      );
                    })}

                    {/* Direct Lessons under Main Course */}
                    {directLessons.length > 0 && (
                      <div className="bg-white rounded-2xl border border-amber-200/80 shadow-xs p-6 space-y-4">
                        <h3 className="text-base font-extrabold text-gray-900 flex items-center gap-2">
                          <Video className="w-5 h-5 text-amber-600" />
                          <span>Direct Video Lessons</span>
                        </h3>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                          {directLessons.map((lesson, idx) => {
                            const lessonPrice = lesson.price ?? lesson.offerPrice ?? lesson.regularPrice;
                            return (
                              <div
                                key={lesson._id}
                                className="p-3.5 bg-amber-50/30 hover:bg-amber-100/40 rounded-xl border border-amber-200/60 flex items-center justify-between text-xs transition"
                              >
                                <div className="flex items-center gap-3">
                                  <div className="w-7 h-7 rounded-lg bg-black text-[#FECE00] flex items-center justify-center shrink-0 font-bold text-xs">
                                    {idx + 1}
                                  </div>
                                  <div>
                                    <span className="font-extrabold text-gray-900 block text-xs">
                                      {lesson.title}
                                    </span>
                                    {lesson.durationMinutes ? (
                                      <span className="text-[11px] font-medium text-gray-500 flex items-center gap-1 mt-0.5">
                                        <Clock className="w-3 h-3 text-gray-400" />
                                        <span>{lesson.durationMinutes} mins</span>
                                      </span>
                                    ) : null}
                                  </div>
                                </div>

                                <div className="flex items-center gap-3">
                                  {lessonPrice !== undefined && lessonPrice !== null && !isNaN(Number(lessonPrice)) ? (
                                    <span className="font-extrabold text-gray-900 text-xs">
                                      €{lessonPrice}
                                    </span>
                                  ) : null}

                                  {isItemPurchased(lesson._id, 'lesson') ? (
                                    <Link
                                      href="/student/dashboard"
                                      className="px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-300 text-emerald-800 font-extrabold text-[11px] flex items-center gap-1 shrink-0 hover:bg-emerald-100 transition"
                                    >
                                      <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" />
                                      <span>Purchased</span>
                                    </Link>
                                  ) : (
                                    <button
                                      type="button"
                                      onClick={() =>
                                        handleEnroll({
                                          id: lesson._id,
                                          title: lesson.title,
                                          price: lessonPrice,
                                          type: 'lesson',
                                          level: lesson.level,
                                        })
                                      }
                                      className="px-3 py-1.5 rounded-lg bg-black hover:bg-[#FECE00] text-[#FECE00] hover:text-black font-extrabold text-[11px] transition shrink-0 cursor-pointer"
                                    >
                                      <span>Enroll</span>
                                    </button>
                                  )}
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>

            </div>

            {/* RIGHT COLUMN: Sticky Purchase Sidebar (5 / 12) */}
            <div className="lg:col-span-5 xl:col-span-4 sticky top-28 space-y-6">
              <div className="bg-white rounded-3xl border-2 border-amber-300 shadow-xl p-6 sm:p-8 space-y-6 relative overflow-hidden">
                <div className="absolute top-0 right-0 w-32 h-32 bg-[#FECE00]/20 rounded-full blur-2xl pointer-events-none" />

                <div className="space-y-2 border-b border-amber-100 pb-5 !m-0">
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-black uppercase text-amber-700 tracking-wider">
                      Full Level Course Package
                    </span>
                    {/* {savingsInfo && (
                      <span className="px-2.5 py-0.5 rounded-full bg-red-100 text-red-700 text-[11px] font-black">
                        Save €{savingsInfo.savings}
                      </span>
                    )} */}
                  </div>

                  <div className="flex items-baseline gap-3">
                    {renderPriceTag(mainCourse.offerPrice, mainCourse.regularPrice) ? (
                      <span className="text-4xl font-black text-gray-900 tracking-tight">
                        {renderPriceTag(mainCourse.offerPrice, mainCourse.regularPrice)}
                      </span>
                    ) : (
                      <span className="text-2xl font-extrabold text-gray-900">
                        Contact for Pricing
                      </span>
                    )}

                    {mainCourse.offerPrice !== undefined && mainCourse.offerPrice !== null && mainCourse.regularPrice && (
                      <span className="text-lg text-gray-400 line-through font-semibold">
                        €{mainCourse.regularPrice}
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-gray-500 font-medium">One-time payment • Instant lifetime access</p>
                </div>

                {totalLessonsCount > 0 ? (
                  isItemPurchased(mainCourse._id, 'course') ? (
                    <Link
                      href="/student/dashboard"
                      className="w-full py-4 rounded-2xl bg-emerald-50 border-2 border-emerald-400 text-emerald-800 font-black text-sm uppercase tracking-wider shadow-md transition-all flex items-center justify-center gap-2 group hover:bg-emerald-100"
                    >
                      <CheckCircle2 className="w-5 h-5 text-emerald-600" />
                      <span>Purchased / Go to Dashboard</span>
                      <ArrowRight className="w-4 h-4 text-emerald-700 group-hover:translate-x-1 transition-transform" />
                    </Link>
                  ) : (
                    <button
                      type="button"
                      onClick={() =>
                        handleEnroll({
                          id: mainCourse._id,
                          title: mainCourse.title,
                          price: mainCourse.offerPrice ?? mainCourse.regularPrice,
                          type: 'course',
                          level: mainCourse.level,
                        })
                      }
                      className="w-full py-4 rounded-2xl bg-[#FECE00] hover:bg-black text-black hover:text-[#FECE00] font-black text-sm uppercase tracking-wider shadow-lg transition-all transform active:scale-95 cursor-pointer flex items-center justify-center gap-2 group"
                    >
                      <span>Enroll Full Course Now</span>
                      <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                    </button>
                  )
                ) : (
                  <div className="w-full py-4 rounded-2xl bg-gray-100 text-gray-500 font-extrabold text-xs uppercase tracking-wider text-center border-2 border-gray-200 border-dashed">
                    Lessons Coming Soon
                  </div>
                )}

                {/* Features List Included */}
                <div className="space-y-3 pt-2">
                  <span className="text-xs font-extrabold uppercase tracking-wider text-gray-900 block">
                    What's included in full course:
                  </span>
                  <ul className="space-y-2.5 text-xs font-semibold text-gray-700">
                    <li className="flex items-center gap-2.5">
                      <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
                      <span>Access to all {totalSubCoursesCount} Sub-Course Modules</span>
                    </li>
                    <li className="flex items-center gap-2.5">
                      <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
                      <span>{totalLessonsCount} High quality video lessons</span>
                    </li>
                    <li className="flex items-center gap-2.5">
                      <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
                      <span>{activeMainSub 
                          ? `Expires on ${new Date(activeMainSub.expiryDate).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' })}` 
                          : mainCourse.validityMonths ? `${mainCourse.validityMonths} Months full platform access` : 'Unlimited lifetime access'}
                      </span>
                    </li>
                    <li className="flex items-center gap-2.5">
                      <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
                      <span>Course completion certificate</span>
                    </li>
                  </ul>
                </div>

                {/* Security Guarantee Badge */}
                <div className="pt-4 border-t border-amber-100 flex items-center gap-3 text-xs text-gray-600 font-medium">
                  <ShieldCheck className="w-8 h-8 text-amber-600 shrink-0" />
                  <span>Verified course materials provided by Apka German School.</span>
                </div>
              </div>
            </div>

          </div>
        )}
      </div>

      {/* Registration Modal Popup */}
      <RegistrationModal
        isOpen={isRegistrationOpen}
        onClose={() => setIsRegistrationOpen(false)}
        selectedItem={selectedItemForReg}
        coursesOptions={courseOptions}
      />

      {/* Auth Modal Popup for mandatory student login */}
      <AuthModal
        isOpen={authModalOpen}
        onClose={() => setAuthModalOpen(false)}
        initialMode="login"
      />
    </div>
  );
}

