import { useState, useEffect } from 'react'
import { useLocalStorage } from '@/hooks/useLocalStorage'
import { Button } from '@/components/ui/button'
import { Progress } from '@/components/ui/progress'
import { Card } from '@/components/ui/card'
import { MdEmojiEvents, MdStar, MdVolumeUp, MdVolumeOff, MdArrowBack, MdStars, MdSettings, MdBarChart, MdKeyboardArrowUp, MdKeyboardArrowDown, MdFavorite, MdSportsEsports, MdPerson } from 'react-icons/md'
import { motion, AnimatePresence } from 'framer-motion'
import { MathExercise } from './MathExercise'
import { StickerCollection } from './BadgeCollection'
import { Settings } from './Settings'
import { ProgressAnalytics } from './ProgressAnalytics'
import { MathWizardMascot } from './MathWizardMascot'
import { MiniGameContainer } from './minigames/MiniGameContainer'
import { MiniGamesGallery } from './MiniGamesGallery'
import { ParentPortal } from './ParentPortal'
import { DailyChallenge } from './DailyChallenge'
import { useSound } from '@/hooks/useSound'
import { useStickers } from '@/hooks/useBadges'
import { useProgressTracking } from '@/hooks/useProgressTracking'
import { logSessionStart } from '@/lib/analytics'
import type { TimedAttempt } from '@/types/progress'

// Per-card accent colors cycling through the design palette.
// Gives each exercise card a unique visual identity so pre-readers
// can navigate by color ("the pink card", "the blue card").
const CARD_ACCENTS = [
  { border: 'border-primary/40', emoji: 'bg-primary/15', btn: 'bg-primary hover:bg-primary/90' },
  { border: 'border-secondary/40', emoji: 'bg-secondary/15', btn: 'bg-secondary hover:bg-secondary/90' },
  { border: 'border-accent/40', emoji: 'bg-accent/15', btn: 'bg-accent hover:bg-accent/90' },
]

interface DashboardProps {
  studentName: string
  grade: string
  onBack: () => void
  onPageChange?: (page: string) => void
}

export function Dashboard({ studentName, grade, onBack, onPageChange: _onPageChange }: DashboardProps) {
  const [currentExercise, setCurrentExercise] = useState<number | null>(null)
  const [showStickers, setShowStickers] = useState(false)
  const [showSettings, setShowSettings] = useState(false)
  const [showAnalytics, setShowAnalytics] = useState(false)
  const [showMascotHelper, setShowMascotHelper] = useState(false)
  const [mascotMessage, setMascotMessage] = useState('')
  const [isExerciseActivityExpanded, setIsExerciseActivityExpanded] = useState(false)
  const [showMiniGame, setShowMiniGame] = useState(false)
  const [showMiniGamesGallery, setShowMiniGamesGallery] = useState(false)
  const [showParentPortal, setShowParentPortal] = useState(false)
  const [completedExercises, setCompletedExercises] = useLocalStorage<number[]>(`progress-${grade}-${studentName.toLowerCase()}`, [])
  const [isMusicOnStr, setIsMusicOnStr] = useLocalStorage('music-setting', 'true')
  const [settingsStr] = useLocalStorage(`settings-${grade}-${studentName.toLowerCase()}`, JSON.stringify({ hideVisualAid: false, disableSubtractionHints: false, autoStartMiniGames: true }))
  
  // Parse string values to proper types
  const isMusicOn = isMusicOnStr === 'true'
  const setIsMusicOn = (value: boolean) => setIsMusicOnStr(value ? 'true' : 'false')
  
  // Safely parse settings with error handling for corrupted data
  const defaultSettings = { hideVisualAid: false, disableSubtractionHints: false, autoStartMiniGames: true }
  let settings = defaultSettings
  try {
    if (settingsStr && settingsStr !== '[object Object]' && settingsStr !== 'undefined' && settingsStr !== 'null') {
      settings = JSON.parse(settingsStr) as { hideVisualAid: boolean; disableSubtractionHints: boolean; autoStartMiniGames: boolean }
    }
  } catch (error) {
    console.warn('Error parsing settings from localStorage, using defaults:', error)
    settings = defaultSettings
  }
  
  const { playButtonClickSound, playCelebrationSound, setSoundEnabled, setGrade } = useSound(grade as 'kindergarten' | 'grade1' | 'grade2')
  
  // Badge system
  const { 
    recordExerciseCompletion, 
    getEarnedStickers, 
    getAvailableStickers, 
    getStickerProgress,
    getStreakData
  } = useStickers(studentName, grade)

  // Progress tracking system
  const { 
    progress: detailedProgress, 
    recordExerciseAttempt, 
    getExerciseStats
  } = useProgressTracking(studentName, grade)

  // Track session start for analytics
  useEffect(() => {
    logSessionStart(grade)
  }, [grade])

  // Show mascot helper occasionally
  useEffect(() => {
    const showHelper = () => {
      const messages = [
        `Great to see you back, ${studentName}! Ready for some math fun?`,
        `You're doing amazing, ${studentName}! Keep up the great work!`,
        `Hey ${studentName}, which math adventure will you pick today?`,
        `I'm here to help if you need me, ${studentName}!`
      ]
      
      const randomMessage = messages[Math.floor(Math.random() * messages.length)]
      setMascotMessage(randomMessage)
      setShowMascotHelper(true)
      
      // Auto-hide after 5 seconds
      setTimeout(() => setShowMascotHelper(false), 5000)
    }
    
    // Show helper when first loading and randomly afterwards
    const timer = setTimeout(showHelper, 1000)
    const interval = setInterval(showHelper, 30000) // Show every 30 seconds
    
    return () => {
      clearTimeout(timer)
      clearInterval(interval)
    }
  }, [studentName])

  // Update sound settings when music preference changes
  useEffect(() => {
    setSoundEnabled(isMusicOn)
  }, [isMusicOn, setSoundEnabled])

  // Update sound grade when grade changes
  useEffect(() => {
    setGrade(grade as 'kindergarten' | 'grade1' | 'grade2')
  }, [grade, setGrade])

  const gradeConfig = {
    kindergarten: {
      title: 'Kindergarten Adventures',
      exercises: [
        { id: 1, title: 'Counting Fun', emoji: '🔢', description: 'Count things and learn numbers!' },
        { id: 2, title: 'Simple Addition', emoji: '➕', description: 'Add numbers with pictures!' },
        { id: 3, title: 'Take Away', emoji: '➖', description: 'Take away with apples!' },
        { id: 4, title: 'Math Tricks', emoji: '🎩', description: 'Learn fun math shortcuts!' }
      ]
    },
    grade1: {
      title: 'Grade 1 Adventures',
      exercises: [
        { id: 1, title: 'Addition to 20', emoji: '🧮', description: 'Add numbers up to 20!' },
        { id: 2, title: 'Subtraction Fun', emoji: '🎯', description: 'Take away up to 20!' },
        { id: 3, title: 'Number Patterns', emoji: '🌈', description: 'Find the missing numbers!' },
        { id: 4, title: 'Math Tricks', emoji: '🎩', description: 'Smart shortcuts for big sums!' }
      ]
    },
    grade2: {
      title: 'Grade 2 Adventures',
      exercises: [
        { id: 1, title: 'Big Addition', emoji: '🚀', description: 'Add two-digit numbers!' },
        { id: 2, title: 'Smart Subtraction', emoji: '🎪', description: 'Subtract two-digit numbers!' },
        { id: 3, title: 'Times Tables', emoji: '✖️', description: 'Learn your times tables!' },
        { id: 4, title: 'Math Tricks', emoji: '🎩', description: 'Smart shortcuts for big sums!' },
        { id: 5, title: 'Division Fun', emoji: '➗', description: 'Share things out equally!' }
      ]
    }
  }

  const config = gradeConfig[grade as keyof typeof gradeConfig]
  const progressPercentage = ((completedExercises || []).length / config.exercises.length) * 100

  const handleExerciseComplete = (exerciseId: number, correctCount: number, totalCount: number, answers?: any[], actualExerciseId?: number, timedAttempt?: TimedAttempt) => {
    // Use actualExerciseId if provided (from Math Tricks), otherwise use exerciseId
    const trackingExerciseId = actualExerciseId || exerciseId
    
    // Get exercise name - for Math Tricks, provide specific names
    let exerciseName = config.exercises.find(ex => ex.id === exerciseId)?.title || 'Unknown Exercise'
    
    if (actualExerciseId && actualExerciseId >= 11) {
      // Map specific Math Tricks exercise names
      const trickNames = {
        11: grade === 'kindergarten' ? 'Doubles Adventure' : 
            grade === 'grade1' ? 'Near Doubles Challenge' : 
            'Compensation Strategy',
        12: grade === 'kindergarten' ? 'Making 10 Game' : 
            grade === 'grade1' ? 'Making 20 Game' : 
            'Split Method Mastery',
        13: grade === 'kindergarten' ? 'Add to 10 Trick' : 
            grade === 'grade1' ? 'Bridge Numbers' : 
            'Advanced Subtraction Tricks',
        14: 'Quick Subtraction' // Grade 1 only
      }
      exerciseName = trickNames[actualExerciseId as keyof typeof trickNames] || exerciseName
    }
    
    // Add timed mode suffix to exercise name if applicable
    if (timedAttempt && timedAttempt.mode !== 'standard') {
      const modeName = timedAttempt.mode === 'speed-round' ? 'Speed Round' : 'Beat the Clock'
      exerciseName = `${exerciseName} (${modeName})`
    }
    
    setCompletedExercises((current) => {
      const currentArray = current || []
      if (!currentArray.includes(exerciseId)) {
        return [...currentArray, exerciseId]
      }
      return currentArray
    })
    
    // Record sticker progress with the correct exercise ID for tracking
    // For timed modes, also record timed stats
    recordExerciseCompletion(grade, trackingExerciseId, correctCount, totalCount)
    
    // Record detailed progress tracking
    if (answers && answers.length > 0) {
      recordExerciseAttempt(trackingExerciseId, exerciseName, correctCount, totalCount, answers)
    }
    
    // Play celebration sound when exercise is completed
    if (isMusicOn) {
      setTimeout(() => playCelebrationSound(), 100)
    }
    
    setCurrentExercise(null)
    
    // Show mini-game reward after exercise completion
    // Only show for exercises with reasonable completion (at least 50% correct) and if auto-start is enabled
    // Skip mini-games for timed modes to allow quick restart
    const completionRate = correctCount / totalCount
    const isTimedMode = timedAttempt && timedAttempt.mode !== 'standard'
    if (completionRate >= 0.5 && settings?.autoStartMiniGames && !isTimedMode) {
      setTimeout(() => {
        setShowMiniGame(true)
      }, 1000) // Brief delay to show celebration first
    }
  }

  if (currentExercise !== null) {
    return (
      <MathExercise
        exerciseId={currentExercise}
        grade={grade}
        studentName={studentName}
        settings={settings || { hideVisualAid: false, disableSubtractionHints: false, autoStartMiniGames: true }}
        onComplete={(correctCount, totalCount, answers, actualExerciseId, timedAttempt) => handleExerciseComplete(currentExercise, correctCount, totalCount, answers, actualExerciseId, timedAttempt)}
        onBack={() => setCurrentExercise(null)}
      />
    )
  }

  if (showMiniGame) {
    return (
      <MiniGameContainer
        grade={grade as 'kindergarten' | 'grade1' | 'grade2'}
        studentName={studentName}
        onComplete={() => setShowMiniGame(false)}
        onBack={() => setShowMiniGame(false)}
        playButtonClickSound={playButtonClickSound}
      />
    )
  }

  if (showMiniGamesGallery) {
    return (
      <MiniGamesGallery
        studentName={studentName}
        grade={grade as 'kindergarten' | 'grade1' | 'grade2'}
        onBack={() => setShowMiniGamesGallery(false)}
        playButtonClickSound={playButtonClickSound}
      />
    )
  }

  if (showAnalytics) {
    return (
      <ProgressAnalytics
        studentName={studentName}
        grade={grade}
        onBack={() => setShowAnalytics(false)}
        playButtonClickSound={playButtonClickSound}
      />
    )
  }

  if (showSettings) {
    return (
      <Settings
        grade={grade}
        studentName={studentName}
        onBack={() => setShowSettings(false)}
        playButtonClickSound={playButtonClickSound}
      />
    )
  }

  if (showParentPortal) {
    return (
      <ParentPortal
        studentName={studentName}
        grade={grade}
        onBack={() => setShowParentPortal(false)}
        playButtonClickSound={playButtonClickSound}
      />
    )
  }

  if (showStickers) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-100 via-purple-50 to-pink-100">
        {/* Header */}
        <div className="bg-white/80 backdrop-blur-sm border-b border-primary/20 p-4">
          <div className="max-w-6xl mx-auto flex items-center justify-between">
            <Button
              onClick={() => {
                playButtonClickSound()
                setShowStickers(false)
              }}
              variant="outline"
              size="sm"
              aria-label="Go back"
              className="border-2 border-primary/20 hover:border-primary"
            >
              <MdArrowBack size={20} />
              Back
            </Button>
            
            <h1 className="heading-font text-2xl font-bold text-primary flex items-center gap-2">
              <MdStars size={28} className="text-accent" />
              Sticker Collection
            </h1>
            
            <div className="w-24" /> {/* Spacer for centering */}
          </div>
        </div>

        <div className="max-w-6xl mx-auto p-6">
          <StickerCollection
            earnedStickers={getEarnedStickers()}
            availableStickers={getAvailableStickers()}
            getStickerProgress={getStickerProgress}
            studentName={studentName}
          />
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-100 via-purple-50 to-pink-100">
      {/* Header */}
      <div className="bg-white/80 backdrop-blur-sm border-b border-primary/20 p-4">
        <div className="max-w-6xl mx-auto space-y-4">
          {/* Top Row: Back button, Student name, Volume control */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Button
                onClick={() => {
                  playButtonClickSound()
                  onBack()
                }}
                variant="outline"
                size="sm"
                className="border-2 border-primary/20 hover:border-primary"
              >
                <MdArrowBack size={20} />
              </Button>
              <div>
                <h1 className="heading-font font-bold text-primary text-4xl">
                  Hi, {studentName}! 👋
                </h1>
                <p className="text-muted-foreground">{config.title}</p>
              </div>
            </div>
            
            {/* Utility controls: parent/settings zone — de-emphasised for adults */}
            <div className="flex items-center gap-1">
              <Button
                onClick={() => {
                  playButtonClickSound()
                  setShowAnalytics(true)
                }}
                variant="ghost"
                size="sm"
                className="text-muted-foreground hover:text-foreground flex items-center gap-1.5"
                aria-label="My Progress"
              >
                <MdBarChart size={16} />
                <span className="hidden sm:inline text-xs">Progress</span>
              </Button>

              <Button
                onClick={() => {
                  playButtonClickSound()
                  setShowSettings(true)
                }}
                variant="ghost"
                size="sm"
                className="text-muted-foreground hover:text-foreground flex items-center gap-1.5"
                aria-label="Settings"
              >
                <MdSettings size={16} />
                <span className="hidden sm:inline text-xs">Settings</span>
              </Button>

              <Button
                onClick={() => {
                  playButtonClickSound()
                  setShowParentPortal(true)
                }}
                variant="ghost"
                size="sm"
                className="text-muted-foreground hover:text-foreground flex items-center gap-1.5"
                aria-label="Parent Portal"
              >
                <MdPerson size={16} />
                <span className="hidden sm:inline text-xs">Parent</span>
              </Button>

              <Button
                onClick={() => {
                  if (isMusicOn) {
                    playButtonClickSound()
                  }
                  setIsMusicOn(!isMusicOn)
                  if (!isMusicOn) {
                    setTimeout(() => playButtonClickSound(), 50)
                  }
                }}
                variant="outline"
                size="sm"
                aria-label={isMusicOn ? 'Turn sound off' : 'Turn sound on'}
                className="border-2 border-primary/20 hover:border-primary"
              >
                {isMusicOn ? <MdVolumeUp size={20} /> : <MdVolumeOff size={20} />}
              </Button>
            </div>
          </div>
          
          {/* Child action row: explore destinations — prominent, left-aligned */}
          <div className="flex items-center gap-3">
            <Button
              onClick={() => {
                playButtonClickSound()
                setShowMiniGamesGallery(true)
              }}
              variant="outline"
              size="sm"
              className="border-2 border-purple-500/30 hover:border-purple-500 flex items-center gap-2"
            >
              <MdSportsEsports size={20} className="text-purple-500" />
              <span>Mini Games</span>
            </Button>

            <Button
              onClick={() => {
                playButtonClickSound()
                setShowStickers(true)
              }}
              variant="outline"
              size="sm"
              className="border-2 border-accent/30 hover:border-accent flex items-center gap-2"
            >
              <MdStars size={22} className="text-accent" />
              <span>Stickers</span>
              <div className="bg-accent text-accent-foreground text-xs px-1.5 py-0.5 rounded-full">
                {getEarnedStickers().length}
              </div>
            </Button>

            <div className="ml-auto flex items-center gap-2 bg-white/50 rounded-full px-4 py-2" aria-label={`${(completedExercises || []).length} of ${config.exercises.length} done`}>
              <MdEmojiEvents size={22} className="text-accent" />
              <span className="font-medium text-sm">{(completedExercises || []).length} of {config.exercises.length} done</span>
            </div>
          </div>
        </div>
      </div>
      <div className="max-w-6xl mx-auto p-6">
        {/* Progress Section */}
        <motion.div
          initial={{ y: -20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          className="mb-8"
        >
          <Card className="p-6 bg-white/90 backdrop-blur-sm border-2 border-primary/20">
            <div className="flex items-center gap-4 mb-4">
              <MdStar size={32} className="text-accent" />
              <div className="flex-1">
                <h2 className="text-xl font-bold text-foreground mb-2">Your Progress</h2>
                <Progress value={progressPercentage} className="h-4" />
              </div>
              <div className="text-2xl font-bold text-primary">
                {Math.round(progressPercentage)}%
              </div>
            </div>
            
            {progressPercentage === 100 && (
              <motion.div
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                className="text-center p-4 bg-accent/10 rounded-lg border-2 border-accent/20"
              >
                <MdEmojiEvents size={24} className="text-accent" />
                <p className="text-lg font-bold text-foreground">
                  🎉 Amazing work, {studentName}! You completed all exercises! 🎉
                </p>
              </motion.div>
            )}

            {/* Recent stickers preview */}
            {getEarnedStickers().length > 0 && (
              <div className="mt-4 p-4 bg-secondary/10 rounded-lg border border-secondary/20">
                <h3 className="font-bold text-sm text-foreground mb-2 flex items-center gap-2">
                  <MdStars size={28} className="text-accent" />
                  Recent Stickers ({getEarnedStickers().length} total)
                </h3>
                <div className="flex gap-2 overflow-x-auto">
                  {getEarnedStickers().slice(-4).reverse().map(sticker => (
                    <div key={sticker.id} className="flex-shrink-0 text-center bg-white/50 rounded p-2 min-w-[60px]">
                      <div className="text-xl mb-1">{sticker.icon}</div>
                      <div className="text-xs font-medium text-muted-foreground truncate">
                        {sticker.name}
                      </div>
                    </div>
                  ))}
                  {getEarnedStickers().length > 4 && (
                    <div className="flex-shrink-0 flex items-center text-xs text-muted-foreground px-2">
                      +{getEarnedStickers().length - 4} more
                    </div>
                  )}
                </div>
              </div>
            )}
          </Card>
        </motion.div>

        {/* Daily Challenge & Streak Section */}
        <motion.div
          initial={{ y: -20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ delay: 0.05 }}
          className="mb-8"
        >
          <DailyChallenge
            studentName={studentName}
            streakData={getStreakData()}
            grade={grade as 'kindergarten' | 'grade1' | 'grade2'}
            onStartChallenge={() => {
              playButtonClickSound()
              // Start the first exercise for the daily challenge
              setCurrentExercise(1)
            }}
            playButtonClickSound={playButtonClickSound}
          />
        </motion.div>

        {/* Exercise Activity Summary */}
        <motion.div
          initial={{ y: -20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ delay: 0.1 }}
          className="mb-8"
        >
          <Card className="p-6 bg-white/90 backdrop-blur-sm border-2 border-secondary/20">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <MdBarChart size={20} className="text-primary" />
                <div>
                  <h2 className="text-xl font-bold text-foreground">Times Played</h2>
                  <p className="text-sm text-muted-foreground">
                    {detailedProgress?.exerciseStats?.reduce((sum, stat) => sum + stat.attemptCount, 0) || 0} plays •
                    Top score: {(detailedProgress?.exerciseStats?.length || 0) > 0
                      ? Math.round((detailedProgress?.exerciseStats?.reduce((sum, stat) => sum + stat.averageScore, 0) || 0) / (detailedProgress?.exerciseStats?.length || 1))
                      : 0}%
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Button
                  onClick={() => {
                    playButtonClickSound()
                    setShowAnalytics(true)
                  }}
                  variant="outline"
                  size="sm"
                  className="border-2 border-primary/20 hover:border-primary"
                >
                  View Details
                </Button>
                <Button
                  onClick={() => {
                    playButtonClickSound()
                    setIsExerciseActivityExpanded(!isExerciseActivityExpanded)
                  }}
                  variant="ghost"
                  size="sm"
                  className="p-2"
                >
                  {isExerciseActivityExpanded ? <MdKeyboardArrowUp size={20} /> : <MdKeyboardArrowDown size={20} />}
                </Button>
              </div>
            </div>
            
            <AnimatePresence>
              {isExerciseActivityExpanded && (
                <motion.div
                  initial={{ height: 0, opacity: 0 }}
                  animate={{ height: 'auto', opacity: 1 }}
                  exit={{ height: 0, opacity: 0 }}
                  transition={{ duration: 0.3 }}
                  className="overflow-hidden"
                >
                  <div className="grid gap-3">
                    {config.exercises.map(exercise => {
                      const stats = getExerciseStats(exercise.id)
                      const attemptCount = stats?.attemptCount || 0
                      const maxAttempts = Math.max(10, detailedProgress?.exerciseStats?.reduce((max, stat) => Math.max(max, stat.attemptCount), 10) || 10)
                      const progressPercentage = (attemptCount / maxAttempts) * 100
                      
                      return (
                        <div
                          key={exercise.id}
                          className="flex items-center gap-4 p-3 rounded-lg bg-gradient-to-r from-secondary/5 to-secondary/10 border border-secondary/20"
                        >
                          <div className="text-2xl">{exercise.emoji}</div>
                          <div className="flex-1">
                            <div className="flex items-center justify-between mb-1">
                              <h3 className="font-bold text-foreground text-sm">{exercise.title}</h3>
                              <span className="text-lg font-bold text-secondary">{attemptCount}</span>
                            </div>
                            <Progress 
                              value={progressPercentage} 
                              className="h-3"
                            />
                            <div className="flex justify-between text-xs text-muted-foreground mt-1">
                              <span>{attemptCount} attempts</span>
                              {stats && (
                                <span>Best: {stats.bestScore}% • Avg: {stats.averageScore}%</span>
                              )}
                            </div>
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </Card>
        </motion.div>

        {/* All-done celebration banner — shown when every exercise in the grade is complete */}
        {(completedExercises || []).length === config.exercises.length && config.exercises.length > 0 && (
          <motion.div
            initial={{ scale: 0.92, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
            className="mb-8 p-6 rounded-2xl bg-accent/15 border-2 border-accent/40 text-center"
          >
            <div className="text-5xl mb-3">🎉</div>
            <h2 className="heading-font text-2xl font-bold text-foreground mb-1">You finished everything!</h2>
            <p className="text-muted-foreground">Amazing work! Play again to beat your scores.</p>
          </motion.div>
        )}

        {/* Exercise Cards */}
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          <AnimatePresence>
            {config.exercises.map((exercise, index) => {
              const isCompleted = (completedExercises || []).includes(exercise.id)
              const accent = CARD_ACCENTS[index % CARD_ACCENTS.length]

              return (
                <motion.div
                  key={exercise.id}
                  initial={{ y: 50, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: index * 0.1 }}
                  whileHover={{ scale: 1.02, y: -5 }}
                  whileTap={{ scale: 0.98 }}
                >
                  <Card 
                    className={`p-6 cursor-pointer transition-all duration-200 ${
                      isCompleted 
                        ? 'bg-accent/20 border-4 border-accent shadow-lg' 
                        : `bg-white/90 border-2 ${accent.border} hover:shadow-lg`
                    } backdrop-blur-sm`}
                    onClick={() => {
                      playButtonClickSound()
                      setCurrentExercise(exercise.id)
                    }}
                  >
                    <div className="text-center">
                      <div className={`inline-flex items-center justify-center w-20 h-20 rounded-full ${accent.emoji} mb-4 text-5xl`}>
                        {exercise.emoji}
                      </div>
                      <h3 className="heading-font text-xl font-bold text-foreground mb-2">
                        {exercise.title}
                      </h3>
                      <p className="text-muted-foreground text-sm mb-4">
                        {exercise.description}
                      </p>
                      
                      <div className="flex items-center justify-center gap-2">
                        {isCompleted && (
                          <>
                            <MdFavorite size={20} className="text-accent" />
                            <span className="text-foreground font-medium">Completed!</span>
                          </>
                        )}
                        {!isCompleted && (
                          <Button 
                            className={accent.btn}
                            size="sm"
                          >
                            Start Adventure
                          </Button>
                        )}
                      </div>
                    </div>
                  </Card>
                </motion.div>
              )
            })}
          </AnimatePresence>
        </div>
      </div>
      
      {/* Floating Mascot Helper */}
      <AnimatePresence>
        {showMascotHelper && (
          <motion.div
            initial={{ scale: 0, opacity: 0, y: 50 }}
            animate={{ scale: 1, opacity: 1, y: 0 }}
            exit={{ scale: 0, opacity: 0, y: 50 }}
            className="fixed bottom-6 right-6 z-50"
          >
            <div 
              className="relative cursor-pointer"
              onClick={() => setShowMascotHelper(false)}
            >
              <MathWizardMascot
                message={mascotMessage}
                expression="excited"
                isAnimating={true}
                size="medium"
              />
              {/* Close button */}
              <Button
                size="sm"
                variant="ghost"
                className="absolute -top-2 -right-2 h-6 w-6 p-0 bg-white/80 hover:bg-white rounded-full shadow-lg border border-primary/20"
                onClick={(e) => {
                  e.stopPropagation()
                  setShowMascotHelper(false)
                }}
              >
                ×
              </Button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}