import {
  ChevronLeft,
  ChevronRight,
  Clock,
  DollarSign,
  Filter,
  Grid,
  List,
  Search,
  Star,
  Users,
  X
} from 'lucide-react';
import { motion } from 'motion/react';
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useCart } from './CartContext';
import { CartItem, CartPopup } from './CartPopup';
import { CourseCard } from './CourseCard';
import { ImageWithFallback } from './figma/ImageWithFallback';
import { navigateTo } from './Router';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
import { Card } from './ui/card';
import { Input } from './ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import {
  courseApi,
  useGetCoursesQuery,
  Course,
  GetCoursesParams,
  useGetCourseCategoriesQuery,
  CourseCategory
} from '../redux/services/courseApi';
import { useDebounce } from '../redux/hooks/useDebounce';

// Helper function to parse rupee price from string (keep as is)
const parsePriceToNumber = (priceStr: string | number): number => {
  if (typeof priceStr === 'number') return priceStr;
  const numericStr = priceStr.toString().replace(/[^0-9.-]/g, '');
  return parseFloat(numericStr) || 0;
};

// Format price with Rupee symbol (keep as is)
const formatPrice = (price: number): string => {
  return `₹${price.toLocaleString('en-IN')}`;
};

export function LearningOnline() {
  // UI state
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>('');
  const [selectedCategoryName, setSelectedCategoryName] = useState('All Categories');
  const [selectedPriceRange, setSelectedPriceRange] = useState('All Prices');
  const [selectedDuration, setSelectedDuration] = useState('All Durations');
  const [selectedRating, setSelectedRating] = useState('All Ratings');
  const [sortBy, setSortBy] = useState(''); // ✅ Changed to match API value
  // const [sortBy, setSortBy] = useState('most_popular'); // ✅ Changed to match API value
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [currentPage, setCurrentPage] = useState(1);
  const coursesPerPage = 9;
  const prefetchCourseById = courseApi.usePrefetch('getcoursebyid');

  // Debounced search term to avoid too many API calls
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  // Fetch course categories
  const { data: categoriesData, isLoading: categoriesLoading } = useGetCourseCategoriesQuery({
    limit: 100,
    offset: 0
  });

  // ✅ Updated sort options to match backend API values
  const sortOptions = [
    { value: 'most_popular', label: 'Most Popular' },
    { value: 'newest', label: 'Newest First' },
    { value: 'title_asc', label: 'Title A-Z' },
    { value: 'price_low', label: 'Price: Low to High' },
    { value: 'price_high', label: 'Price: High to Low' },
    { value: 'highest_rated', label: 'Highest Rated' },
    { value: 'duration', label: 'Duration' }
  ];

  const priceRanges = [
    'All Prices',
    'Under ₹20,000',
    '₹20,000 - ₹35,000',
    '₹35,000 - ₹50,000',
    'Over ₹50,000'
  ];

  const durations = [
    'All Durations',
    'Under 6 hours',
    '6-10 hours',
    '10-15 hours',
    'Over 15 hours'
  ];

  const ratings = [
    'All Ratings',
    '4.5+ Stars',
    '4.0+ Stars',
    '3.5+ Stars'
  ];

  // Build categories list
  const categories = useMemo(() => {
    const cats = [{ id: '', name: 'All Categories' }];
    if (categoriesData?.data?.items) {
      categoriesData.data.items.forEach((cat: CourseCategory) => {
        cats.push({ id: cat.id, name: cat.category_name });
      });
    }
    return cats;
  }, [categoriesData]);

  // ✅ Helper function to convert UI price range to API format
  const getPriceRangeForApi = useCallback((priceRange: string): string | undefined => {
    switch (priceRange) {
      case 'Under ₹20,000':
        return 'under_20000';
      case '₹20,000 - ₹35,000':
        return '20000_35000';
      case '₹35,000 - ₹50,000':
        return '35000_50000';
      case 'Over ₹50,000':
        return 'above_50000';
      default:
        return undefined;
    }
  }, []);

  // ✅ Helper function to convert UI duration to API format
  const getDurationForApi = useCallback((duration: string): string | undefined => {
    switch (duration) {
      case 'Under 6 hours':
        return 'under_6';
      case '6-10 hours':
        return '6_10';
      case '10-15 hours':
        return '10_15';
      case 'Over 15 hours':
        return 'above_15';
      default:
        return undefined;
    }
  }, []);

  // Helper function to convert UI rating to API format
  const getRatingForApi = useCallback((rating: string): number | undefined => {
    switch (rating) {
      case '4.5+ Stars':
        return 4.5;
      case '4.0+ Stars':
        return 4.0;
      case '3.5+ Stars':
        return 3.5;
      default:
        return undefined;
    }
  }, []);

  // ✅ Helper function to convert sort option to API format
  const getSortByForApi = useCallback((sort: string): string | undefined => {
    // sort is already in API format (most_popular, newest, title_asc, etc.)
    // Just return it as is
    return sort;
  }, []);

  // Build API filters based on current UI state
  const apiFilters: GetCoursesParams = useMemo(() => {
    const filters: GetCoursesParams = {
      limit: 100,
      offset: 0,
      status: 'publish'
    };

    // Category filter
    if (selectedCategoryId) {
      filters.course_category = [selectedCategoryId];
    }

    // Search query
    if (debouncedSearchTerm) {
      filters.search_query = debouncedSearchTerm;
    }

    // Price range
    const apiPriceRange = getPriceRangeForApi(selectedPriceRange);
    if (apiPriceRange) {
      filters.price_range = apiPriceRange;
    }

    // Duration range
    const apiDurationRange = getDurationForApi(selectedDuration);
    if (apiDurationRange) {
      filters.duration_range = apiDurationRange;
    }

    // Rating
    const apiRating = getRatingForApi(selectedRating);
    if (apiRating !== undefined) {
      filters.min_rating = apiRating;
    }

    // Sort by
    const apiSortBy = getSortByForApi(sortBy);
    if (apiSortBy && sortBy !== '') {
      filters.sort_by = apiSortBy;
    }

    return filters;
  }, [
    selectedCategoryId,
    debouncedSearchTerm,
    selectedPriceRange,
    selectedDuration,
    selectedRating,
    sortBy,
    getPriceRangeForApi,
    getDurationForApi,
    getRatingForApi,
    getSortByForApi
  ]);

  // Fetch courses with API filters
  const {
    data: coursesData,
    isLoading: coursesLoading,
    isError,
    isFetching // To show loading indicator while fetching
  } = useGetCoursesQuery(apiFilters);

  // Reset to page 1 when filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [
    selectedCategoryId,
    debouncedSearchTerm,
    selectedPriceRange,
    selectedDuration,
    selectedRating,
    sortBy
  ]);

  // Transform API response to course format
  const courses = useMemo(() => {
    if (!coursesData?.data?.items) return [];

    return coursesData.data.items.map((course: Course) => ({
      id: course.id,
      title: course.course_name,
      thumbnail: course.thumbnail_img || 'https://images.unsplash.com/photo-1552664730-d307ca884978?w=400&h=250&fit=crop',
      duration: `${course.total_duration || 0} hours`,
      level: 'Intermediate',
      format: course.retail_type === 'public' ? 'Cohort-based' : 'Self-paced',
      rating: course.avg_rating || 4.5,
      reviews: `${course.total_reviews || 0} review${(course.total_reviews || 0) === 1 ? '' : 's'}`,
      category: course.course_category_name || 'General',
      categoryId: course.course_category_xid || '',
      description: course.course_desc || `Master ${course.course_name} with our comprehensive program.`,
      price: formatPrice(course.best_value || 0),
      originalPrice: formatPrice(course.price || 0),
      course_status: course.course_status
    }));
  }, [coursesData]);

  // Get total courses count from API response
  const totalCoursesCount = coursesData?.data?.pagination_info?.total_count || 0;

  // Paginate the courses (since API returns all courses based on filters, we paginate client-side)
  const totalPages = Math.ceil(totalCoursesCount / coursesPerPage);
  const startIndex = (currentPage - 1) * coursesPerPage;
  const currentCourses = courses.slice(startIndex, startIndex + coursesPerPage);

  // Handle category change
  const handleCategoryChange = (value: string) => {
    const selectedCat = categories.find(cat => cat.name === value);
    if (selectedCat) {
      setSelectedCategoryName(selectedCat.name);
      setSelectedCategoryId(selectedCat.id);
    } else {
      setSelectedCategoryName('All Categories');
      setSelectedCategoryId('');
    }
  };

  const clearAllFilters = () => {
    setSearchTerm('');
    handleCategoryChange('All Categories');
    setSelectedPriceRange('All Prices');
    setSelectedDuration('All Durations');
    setSelectedRating('All Ratings');
    setSortBy(''); 
  };

  const hasActiveFilters = searchTerm ||
    selectedCategoryName !== 'All Categories' ||
    selectedPriceRange !== 'All Prices' ||
    selectedDuration !== 'All Durations' ||
    selectedRating !== 'All Ratings';

  // Cart functionality
  const { addToCart } = useCart();
  const [isCartPopupOpen, setIsCartPopupOpen] = useState(false);
  const [recentlyAddedItem, setRecentlyAddedItem] = useState<CartItem | null>(null);

  const handleAddToCart = (item: CartItem) => {
    addToCart(item);
    setRecentlyAddedItem(item);
    setIsCartPopupOpen(true);
  };

  const handleCloseCartPopup = () => {
    setIsCartPopupOpen(false);
    setRecentlyAddedItem(null);
  };

  const handleCourseClick = useCallback((courseId: string) => {
    prefetchCourseById(courseId, { force: true });
    navigateTo(`/course/${courseId}`);
  }, [prefetchCourseById]);

  // Show loading state
  if (coursesLoading || categoriesLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-gray-600">Loading courses...</p>
        </div>
      </div>
    );
  }

  // Show error state
  if (isError) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-red-600 mb-4">Error Loading Courses</h2>
          <p className="text-gray-600 mb-4">Failed to load courses. Please try again later.</p>
          <Button onClick={() => window.location.reload()}>Retry</Button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ backgroundColor: '#FFFFFF' }}>
      {/* Hero Banner */}
      <section className="relative py-16 overflow-hidden">
        <div
          className="absolute inset-0"
          style={{
            backgroundImage: 'url(https://images.unsplash.com/photo-1522202176988-66273c2fd55f?w=1200&h=600&fit=crop)',
            backgroundSize: 'cover',
            backgroundPosition: 'center'
          }}
        >
          <div className="absolute inset-0 bg-gradient-to-r from-black/80 via-black/60 to-black/40" />
        </div>

        <div className="relative section-margin-x">
          <div className="max-w-6xl text-left">
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8 }}
            >
              <div className="branded-tag-system-white mb-6 justify-start">
                <div className="dot"></div>
                <span className="text">DIGITAL LEARNING PLATFORM</span>
              </div>
              <h1 className="text-h1-white mb-8" style={{ lineHeight: 'var(--line-height-h1)' }}>
                Discover Your Leadership<br />Potential Online
              </h1>
              <div className="max-w-5xl mb-8">
                <p className="text-body-lg-white" style={{ lineHeight: '1.7' }}>
                  Our Leadership Courses are structured packages which are targeted towards building your leadership abilities. Each course is a wholesome package which not only helps you gain awareness about your leadership style but also gives insights to build your leadership abilities. Every course contains curated content targeted towards a specific leadership ability. Each course consists of our proprietary profiling instruments – Leadership Profilers, conceptual videos and experiences of leaders – Leadership Webcasts, as well as additional content to supplement learning.
                </p>
              </div>
            </motion.div>
          </div>
        </div>
      </section>

      {/* Search and Controls Section */}
      <section className="py-8" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="section-margin-x">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
            <div className="relative max-w-md flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                type="text"
                placeholder="Search courses, topics, categories..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 pr-4 py-3 text-body rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 w-full bg-gray-50"
                style={{
                  fontSize: 'var(--font-body)',
                  fontFamily: 'var(--font-family-base)',
                  height: '48px'
                }}
              />
            </div>

            <div className="flex items-center gap-4">
              <div className="flex items-center border border-gray-300 rounded-lg overflow-hidden">
                <button
                  onClick={() => setViewMode('grid')}
                  className={`p-2 transition-colors ${viewMode === 'grid'
                    ? 'text-white'
                    : 'bg-white text-gray-600 hover:bg-gray-50'
                    }`}
                  style={{
                    backgroundColor: viewMode === 'grid' ? 'var(--color-primary)' : undefined
                  }}
                  aria-label="Grid view"
                >
                  <Grid className="w-4 h-4" />
                </button>
                <button
                  onClick={() => setViewMode('list')}
                  className={`p-2 transition-colors ${viewMode === 'list'
                    ? 'text-white'
                    : 'bg-white text-gray-600 hover:bg-gray-50'
                    }`}
                  style={{
                    backgroundColor: viewMode === 'list' ? 'var(--color-primary)' : undefined
                  }}
                  aria-label="List view"
                >
                  <List className="w-4 h-4" />
                </button>
              </div>

              <Select value={sortBy || undefined} onValueChange={setSortBy}>
                <SelectTrigger className="w-40 text-body">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  {sortOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      </section>

      {/* Main Content Section with Sidebar */}
      <section className="pb-16" style={{ backgroundColor: '#FFFFFF' }}>
        <div className="section-margin-x">
          <div className="grid grid-cols-12 gap-8">
            {/* Left Sidebar - Sticky Filters */}
            <div className="col-span-12 lg:col-span-3">
              <div className="sticky top-4">
                <Card className="bg-white border border-gray-200 rounded-lg shadow-md overflow-hidden">
                  {/* Filter Header */}
                  <div className="bg-gray-50 px-4 py-3 border-b border-gray-200">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="p-1.5 rounded-md" style={{ backgroundColor: 'rgba(4, 4, 91, 0.1)' }}>
                          <Filter className="w-3.5 h-3.5" style={{ color: 'var(--color-primary)' }} />
                        </div>
                        <h3 className="text-body font-semibold text-gray-800">
                          Filters
                        </h3>
                      </div>
                      {hasActiveFilters && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={clearAllFilters}
                          className="text-xs px-2 py-1 rounded-md transition-colors filter-clear-btn"
                        >
                          <X className="w-3 h-3 mr-1" />
                          Clear
                        </Button>
                      )}
                    </div>
                  </div>

                  {/* Filter Content */}
                  <div className="p-4">
                    <div className="space-y-4">
                      {/* Category Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Category
                        </label>
                        <Select value={selectedCategoryName} onValueChange={handleCategoryChange}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors">
                            <SelectValue placeholder="All Categories" />
                          </SelectTrigger>
                          <SelectContent>
                            {categories.map((category) => (
                              <SelectItem key={category.name} value={category.name} className="text-small">
                                {category.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Price Range Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Price Range
                        </label>
                        <Select value={selectedPriceRange} onValueChange={setSelectedPriceRange}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors">
                            <SelectValue placeholder="All Prices" />
                          </SelectTrigger>
                          <SelectContent>
                            {priceRanges.map((priceRange) => (
                              <SelectItem key={priceRange} value={priceRange} className="text-small">
                                {priceRange}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Duration Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Duration
                        </label>
                        <Select value={selectedDuration} onValueChange={setSelectedDuration}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors">
                            <SelectValue placeholder="All Durations" />
                          </SelectTrigger>
                          <SelectContent>
                            {durations.map((duration) => (
                              <SelectItem key={duration} value={duration} className="text-small">
                                {duration}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Rating Filter */}
                      <div className="filter-section">
                        <label className="block text-small mb-2 font-medium text-gray-700">
                          Rating
                        </label>
                        <Select value={selectedRating} onValueChange={setSelectedRating}>
                          <SelectTrigger className="w-full text-small h-9 border-gray-300 hover:border-gray-400 transition-colors">
                            <SelectValue placeholder="All Ratings" />
                          </SelectTrigger>
                          <SelectContent>
                            {ratings.map((rating) => (
                              <SelectItem key={rating} value={rating} className="text-small">
                                {rating}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </div>
                </Card>
              </div>
            </div>

            {/* Right Content Area */}
            <div className="col-span-12 lg:col-span-9">
              <div className="mb-4 text-small text-muted flex justify-between items-center">
                <span>Showing {currentCourses.length} of {totalCoursesCount} courses</span>
                {isFetching && (
                  <span className="text-xs text-blue-600 animate-pulse">Updating results...</span>
                )}
              </div>

              {/* Courses Results */}
              {currentCourses.length === 0 ? (
                <div className="text-center py-12">
                  <p className="text-body-lg text-muted">
                    No courses found matching your criteria.
                  </p>
                  {hasActiveFilters && (
                    <Button
                      variant="outline"
                      onClick={clearAllFilters}
                      className="mt-4"
                    >
                      Clear Filters
                    </Button>
                  )}
                </div>
              ) : (
                <>
                  {/* Grid View */}
                  {viewMode === 'grid' && (
                    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                      {currentCourses.map((course) => (
                        <div key={course.id} className="w-full">
                          <CourseCard
                            course={course}
                            className="h-[560px] flex flex-col w-full"
                            onClick={() => handleCourseClick(course.id)}
                            onAddToCart={handleAddToCart}
                          />
                        </div>
                      ))}
                    </div>
                  )}

                  {/* List View */}
                  {viewMode === 'list' && (
                    <div className="space-y-4">
                      {currentCourses.map((course) => (
                        <Card
                          key={course.id}
                          className="overflow-hidden hover:shadow-lg transition-all duration-300 cursor-pointer group"
                          onClick={() => handleCourseClick(course.id)}
                        >
                          <div className="flex flex-col md:flex-row">
                            <div className="md:w-80 flex-shrink-0">
                              <div className="aspect-video md:aspect-square w-full bg-gray-100 overflow-hidden relative">
                                <ImageWithFallback
                                  src={course.thumbnail}
                                  alt={course.title}
                                  className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                />

                                {/* Duration and Level Badge */}
                                <div className="absolute top-2 left-2 flex gap-2">
                                  <Badge variant="secondary" className="bg-black/60 text-white text-xs">
                                    <Clock className="w-3 h-3 mr-1" />
                                    {course.duration}
                                  </Badge>
                                  <Badge variant="secondary" className="bg-black/60 text-white text-xs">
                                    {course.level}
                                  </Badge>
                                </div>

                                {/* Format Badge */}
                                <div className="absolute top-2 right-2">
                                  <Badge variant="outline" className="bg-white text-xs">
                                    {course.format}
                                  </Badge>
                                </div>
                              </div>
                            </div>

                            <div className="flex-1 p-6 flex flex-col">
                              <div className="flex-1">
                                {/* Category */}
                                <Badge variant="outline" className="mb-3 text-xs border-blue-200 text-blue-700">
                                  {course.category}
                                </Badge>

                                {/* Title */}
                                <h3 className="text-h4 mb-3 group-hover:text-blue-600 transition-colors">
                                  {course.title}
                                </h3>

                                {/* Description */}
                                <p className="text-body text-gray-600 mb-4 line-clamp-2">
                                  {course.description}
                                </p>

                                {/* Stats */}
                                <div className="flex items-center gap-4 mb-4">
                                  <div className="flex items-center gap-1">
                                    <Star className="w-4 h-4 text-yellow-400 fill-current" />
                                    <span className="text-small font-medium">{course.rating}</span>
                                  </div>
                                  <div className="flex items-center gap-1">
                                    <Users className="w-4 h-4 text-gray-400" />
                                    <span className="text-small text-gray-600">{course.reviews}</span>
                                  </div>
                                </div>
                              </div>

                              {/* Bottom Row - Price and Button */}
                              <div className="flex items-center justify-between pt-4 border-t border-gray-100">
                                <div className="flex items-center gap-3">
                                  <span className="text-h4 text-gray-900">{course.price}</span>
                                  <span className="text-small text-gray-500 line-through">{course.originalPrice}</span>
                                </div>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={(e: React.MouseEvent) => {
                                    e.stopPropagation();
                                    handleAddToCart({
                                      id: course.id,
                                      title: course.title,
                                      price: course.price,
                                      originalPrice: course.originalPrice,
                                      thumbnail: course.thumbnail,
                                      category: course.category,
                                      level: course.level,
                                      type: 'course'
                                    });
                                  }}
                                  className="flex items-center gap-2 hover:bg-blue-50 hover:border-blue-300"
                                >
                                  <DollarSign className="w-4 h-4" />
                                  Add to Cart
                                </Button>
                              </div>
                            </div>
                          </div>
                        </Card>
                      ))}
                    </div>
                  )}

                  {/* Pagination */}
                  {totalPages > 1 && (
                    <div className="flex items-center justify-center gap-2 mt-8">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                        disabled={currentPage === 1}
                        className="flex items-center gap-2"
                      >
                        <ChevronLeft className="w-4 h-4" />
                        Previous
                      </Button>

                      <div className="flex items-center gap-2">
                        {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                          <Button
                            key={page}
                            variant={currentPage === page ? "default" : "outline"}
                            size="sm"
                            onClick={() => setCurrentPage(page)}
                            className="min-w-[40px]"
                          >
                            {page}
                          </Button>
                        ))}
                      </div>

                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                        disabled={currentPage === totalPages}
                        className="flex items-center gap-2"
                      >
                        Next
                        <ChevronRight className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                </>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* Cart Popup */}
      <CartPopup
        isOpen={isCartPopupOpen}
        onClose={handleCloseCartPopup}
        recentlyAddedItem={recentlyAddedItem}
      />
    </div>
  );
}