import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Music, 
  Clock, 
  TrendingUp, 
  Calendar, 
  Play, 
  Award,
  BarChart3,
  Sparkles,
  ChevronLeft,
  ChevronRight,
  Moon,
  Sun,
  Zap,
  Target,
  Users,
  Heart,
  Star,
  Activity
} from 'lucide-react';
import { useStore } from '../store/useStore';
import { apiGet } from '../utils/api';
import { formatDuration } from '../utils/cn';
import { getThemeClasses, getThemeHueShift } from '../utils/theme';
import { WrappedData, WrappedSlide } from '../types';
import DarkVeil from '../components/DarkVeil';
import toast from 'react-hot-toast';

export const WrappedPage = () => {
  const { currentUser, partnerUser, theme } = useStore();
  const themeClasses = getThemeClasses(theme);
  const [wrappedData, setWrappedData] = useState<WrappedData | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [currentSlide, setCurrentSlide] = useState(0);
  const [timeRange, setTimeRange] = useState('all');
  const [artistImages, setArtistImages] = useState<Record<string, string>>({});

  // Generate slides from wrapped data
  const generateSlides = (data: WrappedData): WrappedSlide[] => {
    const slides: WrappedSlide[] = [];

    // Intro slide with data collection start
    const startDate = new Date(data.dataCollectionStart);
    const daysSinceStart = Math.floor((Date.now() - data.dataCollectionStart) / (1000 * 60 * 60 * 24));
    const hoursListened = Math.floor(data.totalListeningTime / (1000 * 60 * 60));
    
    slides.push({
      id: 'intro',
      type: 'intro',
      title: 'Your Music Wrapped',
      subtitle: `${data.timeRange === 'all' ? 'All Time' : data.timeRange.charAt(0).toUpperCase() + data.timeRange.slice(1)} Edition`,
      gradient: 'from-purple-500 via-pink-500 to-red-500',
      data: { 
        totalTracks: data.totalTracks,
        hoursListened,
        daysSinceStart,
        startDate: startDate.toLocaleDateString()
      }
    });

    // Data collection start slide
    slides.push({
      id: 'dataStart',
      type: 'intro',
      title: 'Your Musical Journey',
      subtitle: `Started ${startDate.toLocaleDateString()}`,
      gradient: 'from-blue-500 via-purple-500 to-pink-500',
      data: { 
        hoursListened,
        daysSinceStart,
        averagePerDay: daysSinceStart > 0 ? Math.round(data.totalTracks / daysSinceStart) : 0
      }
    });

    // Top Songs slide
    if (data.topSongs.length > 0) {
      slides.push({
        id: 'topSongs',
        type: 'topSongs',
        title: 'Your Top Songs',
        subtitle: `You played ${data.topSongs[0]?.playCount || 0} times`,
        gradient: 'from-green-400 via-blue-500 to-purple-600',
        data: data.topSongs.slice(0, 5)
      });
    }

    // Top Artists slide with profile pictures
    if (data.topArtists.length > 0) {
      slides.push({
        id: 'topArtists',
        type: 'topArtists',
        title: 'Your Top Artists',
        subtitle: `${data.topArtists[0]?.name || 'Unknown'} was your #1`,
        gradient: 'from-yellow-400 via-red-500 to-pink-500',
        data: data.topArtists.slice(0, 5)
      });
    }

    // Unique categories slides
    slides.push({
      id: 'listeningHabits',
      type: 'listeningPatterns',
      title: 'Your Listening Habits',
      subtitle: 'When you vibe the most',
      gradient: 'from-teal-400 via-green-500 to-blue-500',
      data: {
        mostActiveHour: data.listeningPatterns.mostActiveHour,
        mostActiveDay: data.listeningPatterns.mostActiveDay,
        listeningStreak: data.listeningPatterns.listeningStreak,
        lateNight: data.uniqueCategories.lateNightListener,
        earlyBird: data.uniqueCategories.earlyBird,
        weekendWarrior: data.uniqueCategories.weekendWarrior
      }
    });

    // Discovery slide
    slides.push({
      id: 'discovery',
      type: 'listeningPatterns',
      title: 'Music Explorer',
      subtitle: 'Your discovery journey',
      gradient: 'from-indigo-500 via-purple-500 to-pink-500',
      data: {
        discoveryRate: data.uniqueCategories.discoveryRate,
        averageSongLength: data.uniqueCategories.averageSongLength,
        listeningVelocity: data.uniqueCategories.listeningVelocity
      }
    });

    // Longest session slide
    if (data.uniqueCategories.longestSession.duration > 0) {
      slides.push({
        id: 'longestSession',
        type: 'listeningTime',
        title: 'Your Longest Session',
        subtitle: 'When you couldn\'t stop listening',
        gradient: 'from-orange-400 via-red-500 to-pink-500',
        data: {
          totalTime: data.uniqueCategories.longestSession.duration,
          totalTracks: Math.floor(data.uniqueCategories.longestSession.duration / (data.uniqueCategories.averageSongLength || 180000)), // Estimate tracks based on average song length
          averagePerTrack: data.uniqueCategories.averageSongLength || 180000
        }
      });
    }

    // Most diverse day slide
    if (data.uniqueCategories.mostDiverseDay.artistCount > 0) {
      slides.push({
        id: 'mostDiverseDay',
        type: 'listeningPatterns',
        title: 'Your Most Diverse Day',
        subtitle: 'When you explored the most',
        gradient: 'from-cyan-400 via-blue-500 to-indigo-600',
        data: {
          date: data.uniqueCategories.mostDiverseDay.date,
          artistCount: data.uniqueCategories.mostDiverseDay.artistCount
        }
      });
    }

    // Partner comparison slides
    if (data.partnerData) {
      slides.push({
        id: 'partnerComparison',
        type: 'listeningTime',
        title: 'You vs Your Partner',
        subtitle: 'Musical journey together',
        gradient: 'from-pink-400 via-purple-500 to-indigo-500',
        data: {
          yourTracks: data.totalTracks,
          partnerTracks: data.partnerData.totalTracks,
          yourTime: data.totalListeningTime,
          partnerTime: data.partnerData.totalListeningTime
        }
      });

      // Shared artists
      const yourArtists = new Set(data.topArtists.slice(0, 10).map(a => a.id));
      const partnerArtists = new Set(data.partnerData.topArtists.map(a => a.id));
      const sharedArtists = Array.from(yourArtists).filter(id => partnerArtists.has(id));
      
      if (sharedArtists.length > 0) {
        slides.push({
          id: 'sharedTaste',
          type: 'topArtists',
          title: 'Your Shared Taste',
          subtitle: `${sharedArtists.length} artists you both love`,
          gradient: 'from-green-400 via-teal-500 to-blue-500',
          data: { sharedArtists: sharedArtists.length }
        });
      }
    }

    // Listening Time slide
    slides.push({
      id: 'listeningTime',
      type: 'listeningTime',
      title: 'Total Listening Time',
      subtitle: 'You\'ve been on a musical journey',
      gradient: 'from-orange-400 via-red-500 to-pink-500',
      data: { 
        totalTime: data.totalListeningTime,
        totalTracks: data.totalTracks,
        averagePerTrack: data.totalTracks > 0 ? data.totalListeningTime / data.totalTracks : 0
      }
    });

    // Outro slide
    slides.push({
      id: 'outro',
      type: 'outro',
      title: 'Thanks for Listening!',
      subtitle: 'Keep discovering amazing music',
      gradient: 'from-purple-500 via-pink-500 to-red-500',
      data: { generatedAt: data.generatedAt }
    });

    return slides;
  };

  const slides = wrappedData ? generateSlides(wrappedData) : [];

  // Fetch artist images
  const fetchArtistImages = async (artists: any[]) => {
    if (!currentUser?.user?.id || !currentUser?.jwt) return;
    
    const imagePromises = artists.map(async (artist) => {
      try {
        const response = await apiGet(`/users/${currentUser.user.id}/artist/${artist.id}`, currentUser.jwt);
        if (response.images && response.images.length > 0) {
          setArtistImages(prev => ({
            ...prev,
            [artist.id]: response.images[0].url
          }));
        }
      } catch (error) {
        console.error(`Failed to fetch image for artist ${artist.name}:`, error);
      }
    });
    
    await Promise.all(imagePromises);
  };

  const fetchWrappedData = async (range: string = 'all') => {
    if (!currentUser?.user?.id || !currentUser?.jwt) return;
    
    setIsLoading(true);
    try {
      const response = await apiGet<WrappedData>(`/users/${currentUser.user.id}/wrapped?range=${range}`, currentUser.jwt);
      setWrappedData(response);
      setCurrentSlide(0);
      
      // Fetch artist images
      if (response.topArtists && response.topArtists.length > 0) {
        fetchArtistImages(response.topArtists);
      }
    } catch (error) {
      console.error('Failed to fetch wrapped data:', error);
      toast.error('Failed to load your music wrapped');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchWrappedData(timeRange);
  }, [timeRange, currentUser?.user?.id, currentUser?.jwt]);

  const nextSlide = () => {
    setCurrentSlide(prev => (prev + 1) % slides.length);
  };

  const prevSlide = () => {
    setCurrentSlide(prev => (prev - 1 + slides.length) % slides.length);
  };

  const formatTime = (ms: number) => {
    const hours = Math.floor(ms / (1000 * 60 * 60));
    const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
    return `${hours}h ${minutes}m`;
  };

  const formatHour = (hour: number) => {
    if (hour === 0) return '12 AM';
    if (hour < 12) return `${hour} AM`;
    if (hour === 12) return '12 PM';
    return `${hour - 12} PM`;
  };

  const renderSlide = (slide: WrappedSlide) => {
    const baseClasses = "w-full h-full flex flex-col items-center justify-center text-center p-3 sm:p-6 overflow-y-auto";
    
    switch (slide.type) {
      case 'intro':
        return (
          <div className={`${baseClasses} relative`}>
            <motion.div
              initial={{ scale: 0.5, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ duration: 0.8, ease: "easeOut" }}
              className="relative z-10 space-y-6"
            >
              <Music className="w-16 h-16 sm:w-20 sm:h-20 lg:w-24 lg:h-24 mx-auto text-white/90" />
              <h1 className="text-3xl sm:text-5xl lg:text-6xl font-bold text-white mb-4">{slide.title}</h1>
              <p className="text-lg sm:text-xl lg:text-2xl text-white/80 mb-8">{slide.subtitle}</p>
              
              {slide.data?.hoursListened && (
                <div className="text-2xl sm:text-4xl lg:text-5xl font-bold text-white mb-4">
                  {slide.data.hoursListened} hours listened
                </div>
              )}
              
              {slide.data?.daysSinceStart && (
                <div className="text-lg text-white/70">
                  Since {slide.data.startDate} ({slide.data.daysSinceStart} days ago)
                </div>
              )}
              
              {slide.data?.totalTracks && (
                <div className="text-2xl text-white/90">
                  {slide.data.totalTracks} songs played
                </div>
              )}
            </motion.div>
          </div>
        );

      case 'topSongs':
        return (
          <div className={`${baseClasses} relative`}>
            <motion.div
              initial={{ y: 50, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              transition={{ duration: 0.6 }}
              className="w-full max-w-3xl relative z-10"
            >
              <h2 className="text-3xl sm:text-4xl lg:text-5xl font-bold text-white mb-2">{slide.title}</h2>
              <p className="text-lg sm:text-lg lg:text-xl text-white/80 mb-8">{slide.subtitle}</p>
              
              <div className="space-y-3">
                {slide.data?.map((song: any, index: number) => (
                  <motion.div
                    key={song.id}
                    initial={{ x: -100, opacity: 0 }}
                    animate={{ x: 0, opacity: 1 }}
                    transition={{ delay: index * 0.2, duration: 0.5 }}
                    className="flex items-center justify-between bg-white/10 backdrop-blur-md rounded-2xl p-4 border border-white/20"
                  >
                    <div className="flex items-center space-x-4">
                      <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center text-white font-bold text-lg">
                        {index + 1}
                      </div>
                      <img
                        src={song.album?.images?.[0]?.url || '/placeholder-album.png'}
                        alt={song.album?.name}
                        className="w-12 h-12 rounded-lg object-cover"
                      />
                      <div className="text-left">
                        <h3 className="text-lg font-semibold text-white">{song.name}</h3>
                        <p className="text-white/70 text-sm">{song.artists?.[0]?.name}</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="text-white font-bold">{song.playCount} plays</div>
                      <div className="text-white/70 text-sm">{formatDuration(song.duration_ms)}</div>
                    </div>
                  </motion.div>
                ))}
              </div>
            </motion.div>
          </div>
        );

      case 'topArtists':
        return (
          <div className={`${baseClasses} relative`}>
            <motion.div
              initial={{ y: 50, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              transition={{ duration: 0.6 }}
              className="w-full max-w-4xl relative z-10"
            >
              <h2 className="text-3xl sm:text-4xl lg:text-5xl font-bold text-white mb-2">{slide.title}</h2>
              <p className="text-lg sm:text-lg lg:text-xl text-white/80 mb-8">{slide.subtitle}</p>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {slide.data?.map((artist: any, index: number) => (
                  <motion.div
                    key={artist.id}
                    initial={{ scale: 0.8, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    transition={{ delay: index * 0.1, duration: 0.5 }}
                    className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20"
                  >
                    <div className="w-20 h-20 mx-auto mb-4 rounded-full overflow-hidden border-2 border-white/20">
                      {artistImages[artist.id] ? (
                        <img
                          src={artistImages[artist.id]}
                          alt={artist.name}
                          className="w-full h-full object-cover"
                        />
                      ) : (
                        <div className="w-full h-full bg-white/20 flex items-center justify-center text-white font-bold text-xl">
                          {index + 1}
                        </div>
                      )}
                    </div>
                    <h3 className="text-xl font-bold text-white mb-2">{artist.name}</h3>
                    <p className="text-white/70">{artist.playCount} plays</p>
                    <p className="text-white/60 text-sm">{formatTime(artist.totalDuration)}</p>
                  </motion.div>
                ))}
              </div>
            </motion.div>
          </div>
        );

      case 'listeningTime':
        return (
          <div className={`${baseClasses} relative`}>
            <motion.div
              initial={{ scale: 0.5, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ duration: 0.8, ease: "easeOut" }}
              className="space-y-6 relative z-10"
            >
              <Clock className="w-16 h-16 sm:w-20 sm:h-20 lg:w-24 lg:h-24 mx-auto text-white/90" />
              <h2 className="text-3xl sm:text-5xl lg:text-6xl font-bold text-white mb-4">{slide.title}</h2>
              <p className="text-lg sm:text-xl lg:text-2xl text-white/80 mb-8">{slide.subtitle}</p>
              
              <div className="text-4xl sm:text-6xl lg:text-7xl font-bold text-white mb-8">
                {formatTime(slide.data?.totalTime || slide.data?.duration || 0)}
              </div>
              
              <div className="grid grid-cols-2 gap-6 text-center">
                <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 border border-white/20">
                  <div className="text-3xl font-bold text-white">{slide.data?.totalTracks || 0}</div>
                  <div className="text-white/70">Total Songs</div>
                </div>
                <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 border border-white/20">
                  <div className="text-3xl font-bold text-white">
                    {formatDuration(slide.data?.averagePerTrack || 0)}
                  </div>
                  <div className="text-white/70">Avg per Song</div>
                </div>
              </div>
            </motion.div>
          </div>
        );

      case 'listeningPatterns':
        return (
          <div className={`${baseClasses} relative`}>
            <motion.div
              initial={{ y: 50, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              transition={{ duration: 0.6 }}
              className="w-full max-w-4xl relative z-10"
            >
              <h2 className="text-3xl sm:text-4xl lg:text-5xl font-bold text-white mb-2">{slide.title}</h2>
              <p className="text-lg sm:text-lg lg:text-xl text-white/80 mb-8">{slide.subtitle}</p>
              
              <div className={`grid gap-6 justify-items-center ${
                // Check if this is a single-item slide (Most Diverse Day)
                slide.data?.artistCount !== undefined && 
                !slide.data?.mostActiveHour && 
                !slide.data?.mostActiveDay && 
                !slide.data?.listeningStreak && 
                !slide.data?.lateNight && 
                !slide.data?.earlyBird && 
                !slide.data?.weekendWarrior && 
                !slide.data?.discoveryRate && 
                !slide.data?.listeningVelocity && 
                !slide.data?.averageSongLength
                  ? 'grid-cols-1 justify-center' 
                  : 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3'
              }`}>
                {slide.data?.mostActiveHour !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Clock className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {formatHour(slide.data.mostActiveHour)}
                    </div>
                    <div className="text-white/70">Most Active Hour</div>
                  </div>
                )}
                
                {slide.data?.mostActiveDay && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Calendar className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.mostActiveDay}
                    </div>
                    <div className="text-white/70">Most Active Day</div>
                  </div>
                )}
                
                {slide.data?.listeningStreak !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <TrendingUp className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.listeningStreak}
                    </div>
                    <div className="text-white/70">Day Streak</div>
                  </div>
                )}
                
                {slide.data?.lateNight !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Moon className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.lateNight}
                    </div>
                    <div className="text-white/70">Late Night Plays</div>
                  </div>
                )}
                
                {slide.data?.earlyBird !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Sun className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.earlyBird}
                    </div>
                    <div className="text-white/70">Early Bird Plays</div>
                  </div>
                )}
                
                {slide.data?.weekendWarrior !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Activity className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.weekendWarrior}
                    </div>
                    <div className="text-white/70">Weekend Plays</div>
                  </div>
                )}
                
                {/* Discovery data for Music Explorer slide */}
                {slide.data?.discoveryRate !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Star className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.discoveryRate}
                    </div>
                    <div className="text-white/70">Artists Discovered</div>
                  </div>
                )}
                
                {slide.data?.listeningVelocity !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Zap className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.listeningVelocity.toFixed(1)}
                    </div>
                    <div className="text-white/70">Songs per Day</div>
                  </div>
                )}
                
                {slide.data?.averageSongLength !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Music className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {formatDuration(slide.data.averageSongLength)}
                    </div>
                    <div className="text-white/70">Avg Song Length</div>
                  </div>
                )}
                
                {/* Most Diverse Day data */}
                {slide.data?.artistCount !== undefined && (
                  <div className="bg-white/10 backdrop-blur-md rounded-2xl p-6 text-center border border-white/20 w-full max-w-xs h-40 flex flex-col justify-center">
                    <Users className="w-12 h-12 mx-auto text-white/90 mb-4" />
                    <div className="text-2xl font-bold text-white mb-2">
                      {slide.data.artistCount}
                    </div>
                    <div className="text-white/70">Artists on {slide.data.date}</div>
                  </div>
                )}
              </div>
            </motion.div>
          </div>
        );

      case 'outro':
        return (
          <div className={`${baseClasses} relative`}>
            <motion.div
              initial={{ scale: 0.5, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ duration: 0.8, ease: "easeOut" }}
              className="space-y-6 relative z-10"
            >
              <Sparkles className="w-16 h-16 sm:w-20 sm:h-20 lg:w-24 lg:h-24 mx-auto text-white/90" />
              <h1 className="text-3xl sm:text-5xl lg:text-6xl font-bold text-white mb-4">{slide.title}</h1>
              <p className="text-lg sm:text-xl lg:text-2xl text-white/80 mb-8">{slide.subtitle}</p>
              <div className="text-lg text-white/60">
                Generated on {new Date(slide.data?.generatedAt || Date.now()).toLocaleDateString()}
              </div>
            </motion.div>
          </div>
        );

      default:
        return null;
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center relative">
        <DarkVeil hueShift={getThemeHueShift(theme)} />
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="glass-fluid rounded-3xl p-10 flex flex-col items-center space-y-6 relative z-20"
        >
          <div className="w-16 h-16 border-4 border-t-transparent rounded-full animate-spin" style={{ borderColor: `var(--theme-primary) var(--theme-primary) var(--theme-primary) transparent` }}></div>
          <p className="text-white font-medium text-lg">Generating your music wrapped...</p>
        </motion.div>
      </div>
    );
  }

  if (!wrappedData) {
    return (
      <div className="min-h-screen flex items-center justify-center relative">
        <DarkVeil hueShift={getThemeHueShift(theme)} />
        <div className="text-center relative z-20">
          <Music className="w-24 h-24 text-white/50 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-white mb-2">No Music Data</h2>
          <p className="text-white/70 mb-6">Start listening to music to generate your wrapped!</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen relative">
      <DarkVeil hueShift={getThemeHueShift(theme)} />
      
      <div className="relative z-20">
        {/* Header */}
        <div className="fixed top-0 left-0 right-0 z-50 p-4 sm:p-6 bg-black/30 backdrop-blur-md border-b border-white/10">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <select
                value={timeRange}
                onChange={(e) => setTimeRange(e.target.value)}
                className="bg-white/10 backdrop-blur-md text-white rounded-lg px-3 py-1 border border-white/20"
              >
                <option value="all" className="bg-gray-800">All Time</option>
                <option value="year" className="bg-gray-800">This Year</option>
                <option value="month" className="bg-gray-800">This Month</option>
                <option value="week" className="bg-gray-800">This Week</option>
              </select>
            </div>
          </div>
        </div>

        {/* Slide Container */}
        <div className="relative w-full min-h-screen flex items-center justify-center p-2 sm:p-4 pt-20 sm:pt-24">
          <div className="w-full max-w-2xl sm:max-w-4xl h-[60vh] sm:h-[80vh] relative">
            <AnimatePresence mode="wait">
              <motion.div
                key={currentSlide}
                initial={{ opacity: 0, scale: 0.9, y: 20 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.9, y: -20 }}
                transition={{ duration: 0.5, ease: "easeInOut" }}
                className="absolute inset-0 rounded-3xl overflow-hidden shadow-2xl overflow-y-auto"
                style={{
                  background: `linear-gradient(135deg, ${themeClasses.cssVars?.primary || '#1db954'}20 0%, ${themeClasses.cssVars?.secondary || '#1ed760'}15 100%)`,
                  backdropFilter: 'blur(25px) saturate(180%)',
                  WebkitBackdropFilter: 'blur(25px) saturate(180%)',
                  border: `1px solid ${themeClasses.cssVars?.primary || '#1db954'}40`,
                  boxShadow: `0 25px 50px rgba(0,0,0,0.4), 0 0 0 1px ${themeClasses.cssVars?.primary || '#1db954'}30, inset 0 1px 0 rgba(255,255,255,0.1)`
                }}
              >
                {renderSlide(slides[currentSlide])}
              </motion.div>
            </AnimatePresence>

            {/* Navigation */}
            {slides.length > 1 && (
              <>
                <button
                  onClick={prevSlide}
                  className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-white/10 backdrop-blur-md hover:bg-white/20 text-white p-3 rounded-full transition-colors border border-white/20"
                >
                  <ChevronLeft className="w-6 h-6" />
                </button>
                
                <button
                  onClick={nextSlide}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-white/10 backdrop-blur-md hover:bg-white/20 text-white p-3 rounded-full transition-colors border border-white/20"
                >
                  <ChevronRight className="w-6 h-6" />
                </button>
              </>
            )}

            {/* Slide Indicators */}
            <div className="absolute bottom-6 left-1/2 transform -translate-x-1/2 flex space-x-2">
              {slides.map((_, index) => (
                <button
                  key={index}
                  onClick={() => setCurrentSlide(index)}
                  className={`w-3 h-3 rounded-full transition-colors ${
                    index === currentSlide ? 'bg-white' : 'bg-white/30'
                  }`}
                />
              ))}
            </div>

            {/* Slide Counter */}
            <div className="absolute top-6 right-6 text-white/70 text-sm bg-white/10 backdrop-blur-md px-3 py-1 rounded-full border border-white/20">
              {currentSlide + 1} / {slides.length}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};