'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  GraduationCap,
  Clock,
  Trophy,
  BookOpen,
  ChevronRight,
  CheckCircle2,
  XCircle,
  ArrowLeft,
  RotateCcw,
  Eye,
  Star,
  Medal,
  Calendar,
  Timer,
  Zap,
  Brain,
  Globe,
  Microscope,
  Landmark,
  Calculator,
  Monitor,
  Heart,
  Flag,
  Share2,
  Sparkles,
  Target,
  ChevronLeft,
} from 'lucide-react';

// ─── Types ───────────────────────────────────────────────────────────────────

type ViewMode = 'main' | 'wizard' | 'quiz' | 'result' | 'loading';
type WizardStep = 1 | 2 | 3 | 4;

interface QuizQuestion {
  id: string;
  question: string;
  optionA: string;
  optionB: string;
  optionC: string;
  optionD: string;
  correctAnswer: string;
  category: string;
  topic: string;
  difficulty: string;
  explanation?: string;
  selectedAnswer?: string;
}

interface ClassOption {
  id: string;
  labelKey: string;
  icon: React.ElementType;
  gradient: string;
}

interface TopicOption {
  id: string;
  labelKey: string;
  icon: React.ElementType;
}

interface ChapterOption {
  id: string;
  labelKey: string;
}

interface QuestionCountOption {
  count: number;
  timeMinutes: number;
}

// ─── Constants ───────────────────────────────────────────────────────────────

const classOptions: ClassOption[] = [
  { id: 'class6-8', labelKey: 'edu.class6_10', icon: BookOpen, gradient: 'from-orange-400 to-orange-600' },
  { id: 'class9-10', labelKey: 'edu.class9_10', icon: BookOpen, gradient: 'from-orange-400 to-amber-600' },
  { id: 'ssc', labelKey: 'edu.ssc', icon: GraduationCap, gradient: 'from-orange-500 to-amber-600' },
  { id: 'hsc', labelKey: 'edu.hsc', icon: Microscope, gradient: 'from-orange-500 to-amber-500' },
  { id: 'admission', labelKey: 'edu.admission', icon: Landmark, gradient: 'from-amber-400 to-orange-600' },
  { id: 'gk', labelKey: 'edu.gk', icon: Globe, gradient: 'from-emerald-400 to-emerald-600' },
];

const topicsByClass: Record<string, TopicOption[]> = {
  'class6-8': [
    { id: 'math', labelKey: 'edu.math', icon: Calculator },
    { id: 'science', labelKey: 'edu.science', icon: Microscope },
    { id: 'bangla', labelKey: 'edu.bangla', icon: BookOpen },
    { id: 'english', labelKey: 'edu.english', icon: Globe },
  ],
  'class9-10': [
    { id: 'math', labelKey: 'edu.math', icon: Calculator },
    { id: 'physics', labelKey: 'edu.physics', icon: Zap },
    { id: 'chemistry', labelKey: 'edu.chemistry', icon: Microscope },
    { id: 'biology', labelKey: 'edu.biology', icon: Heart },
    { id: 'bangla', labelKey: 'edu.bangla', icon: BookOpen },
    { id: 'english', labelKey: 'edu.english', icon: Globe },
  ],
  'ssc': [
    { id: 'math', labelKey: 'edu.math', icon: Calculator },
    { id: 'physics', labelKey: 'edu.physics', icon: Zap },
    { id: 'chemistry', labelKey: 'edu.chemistry', icon: Microscope },
    { id: 'biology', labelKey: 'edu.biology', icon: Heart },
    { id: 'bangla', labelKey: 'edu.bangla', icon: BookOpen },
    { id: 'english', labelKey: 'edu.english', icon: Globe },
    { id: 'ict', labelKey: 'edu.ict', icon: Monitor },
  ],
  'hsc': [
    { id: 'math', labelKey: 'edu.higherMath', icon: Calculator },
    { id: 'physics', labelKey: 'edu.physics', icon: Zap },
    { id: 'chemistry', labelKey: 'edu.chemistry', icon: Microscope },
    { id: 'biology', labelKey: 'edu.biology', icon: Heart },
    { id: 'bangla', labelKey: 'edu.bangla', icon: BookOpen },
    { id: 'english', labelKey: 'edu.english', icon: Globe },
    { id: 'ict', labelKey: 'edu.ict', icon: Monitor },
  ],
  'admission': [
    { id: 'math', labelKey: 'edu.math', icon: Calculator },
    { id: 'physics', labelKey: 'edu.physics', icon: Zap },
    { id: 'chemistry', labelKey: 'edu.chemistry', icon: Microscope },
    { id: 'biology', labelKey: 'edu.biology', icon: Heart },
    { id: 'gk', labelKey: 'edu.gk', icon: Globe },
    { id: 'english', labelKey: 'edu.english', icon: Globe },
  ],
  'gk': [
    { id: 'bangladesh', labelKey: 'edu.bangladesh', icon: Flag },
    { id: 'international', labelKey: 'edu.international', icon: Globe },
    { id: 'science', labelKey: 'edu.science', icon: Microscope },
    { id: 'sports', labelKey: 'edu.sports', icon: Trophy },
    { id: 'history', labelKey: 'edu.historyTopic', icon: Landmark },
  ],
};

const chaptersByTopic: Record<string, ChapterOption[]> = {
  'math': [
    { id: 'algebra', labelKey: 'edu.algebra' },
    { id: 'geometry', labelKey: 'edu.geometry' },
    { id: 'trigonometry', labelKey: 'edu.trigonometry' },
    { id: 'statistics', labelKey: 'edu.statistics' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'physics': [
    { id: 'mechanics', labelKey: 'edu.mechanics' },
    { id: 'thermodynamics', labelKey: 'edu.thermodynamics' },
    { id: 'optics', labelKey: 'edu.optics' },
    { id: 'electricity', labelKey: 'edu.electricity' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'chemistry': [
    { id: 'organic', labelKey: 'edu.organic' },
    { id: 'inorganic', labelKey: 'edu.inorganic' },
    { id: 'physical', labelKey: 'edu.physical' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'biology': [
    { id: 'botany', labelKey: 'edu.botany' },
    { id: 'zoology', labelKey: 'edu.zoology' },
    { id: 'genetics', labelKey: 'edu.genetics' },
    { id: 'ecology', labelKey: 'edu.ecology' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'bangla': [
    { id: 'grammar', labelKey: 'edu.grammar' },
    { id: 'literature', labelKey: 'edu.literature' },
    { id: 'poetry', labelKey: 'edu.poetry' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'english': [
    { id: 'grammar', labelKey: 'edu.grammar' },
    { id: 'vocabulary', labelKey: 'edu.vocabulary' },
    { id: 'comprehension', labelKey: 'edu.comprehension' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'ict': [
    { id: 'programming', labelKey: 'edu.programming' },
    { id: 'networking', labelKey: 'edu.networking' },
    { id: 'database', labelKey: 'edu.database' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'bangladesh': [
    { id: 'geography', labelKey: 'edu.geography' },
    { id: 'history', labelKey: 'edu.historyTopic' },
    { id: 'culture', labelKey: 'edu.culture' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'international': [
    { id: 'world_history', labelKey: 'edu.worldHistory' },
    { id: 'geography', labelKey: 'edu.geography' },
    { id: 'organizations', labelKey: 'edu.organizations' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'science': [
    { id: 'discoveries', labelKey: 'edu.discoveries' },
    { id: 'technology', labelKey: 'edu.technology' },
    { id: 'space', labelKey: 'edu.space' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'sports': [
    { id: 'cricket', labelKey: 'edu.cricket' },
    { id: 'football', labelKey: 'edu.football' },
    { id: 'olympics', labelKey: 'edu.olympics' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'history': [
    { id: 'ancient', labelKey: 'edu.ancient' },
    { id: 'medieval', labelKey: 'edu.medieval' },
    { id: 'modern', labelKey: 'edu.modern' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
  'gk': [
    { id: 'current_affairs', labelKey: 'edu.currentAffairs' },
    { id: 'world', labelKey: 'edu.world' },
    { id: 'science_gk', labelKey: 'edu.science' },
    { id: 'all', labelKey: 'edu.allChapters' },
  ],
};

const questionCountOptions: QuestionCountOption[] = [
  { count: 20, timeMinutes: 10 },
  { count: 30, timeMinutes: 15 },
  { count: 40, timeMinutes: 20 },
];

const optionLabels: ('A' | 'B' | 'C' | 'D')[] = ['A', 'B', 'C', 'D'];

// Map class IDs to API category values
const classToCategoryMap: Record<string, string> = {
  'class6-8': 'class6-10',
  'class9-10': 'class6-10',
  'ssc': 'ssc',
  'hsc': 'hsc',
  'admission': 'admission',
  'gk': 'gk',
};

// Map UI topic IDs to topic names for API filtering
const topicToNameMap: Record<string, string> = {
  'math': 'Mathematics',
  'physics': 'Physics',
  'chemistry': 'Chemistry',
  'biology': 'Biology',
  'bangla': 'Bangla',
  'english': 'English',
  'ict': 'ICT',
  'gk': 'General Knowledge',
  'science': 'Science',
  'bangladesh': 'Bangladesh',
  'international': 'International',
  'sports': 'Sports',
  'history': 'History',
};

// ─── Helper Functions ────────────────────────────────────────────────────────

function getOptionLabelKey(option: string): string {
  const map: Record<string, string> = {
    A: 'edu.optionA',
    B: 'edu.optionB',
    C: 'edu.optionC',
    D: 'edu.optionD',
  };
  return map[option] || option;
}

function formatTime(seconds: number): string {
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${m}:${s.toString().padStart(2, '0')}`;
}

function shuffleArray<T>(array: T[]): T[] {
  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

async function fetchQuestionsFromAPI(
  classId: string,
  topicId: string,
  _chapterId: string,
  questionCount: number
): Promise<QuizQuestion[]> {
  const category = classToCategoryMap[classId] || classId;
  const topicName = topicToNameMap[topicId] || topicId;

  const params = new URLSearchParams({
    category,
    topic: topicName,
    limit: String(questionCount),
    includeAnswers: 'true',
  });

  const response = await fetch(`/api/mcq?${params.toString()}`);
  if (!response.ok) {
    throw new Error('Failed to fetch questions');
  }

  const data = await response.json();
  const apiQuestions = data.questions || [];

  // Map API response to QuizQuestion interface
  const mapped: QuizQuestion[] = shuffleArray(apiQuestions).map(
    (q: Record<string, unknown>) => ({
      id: String(q.id),
      question: String(q.question || ''),
      optionA: String(q.optionA || ''),
      optionB: String(q.optionB || ''),
      optionC: String(q.optionC || ''),
      optionD: String(q.optionD || ''),
      correctAnswer: String(q.correctAnswer || 'A'),
      category: String(q.category || category),
      topic: String(q.topic || topicName),
      difficulty: String(q.difficulty || 'medium'),
      explanation: q.explanation ? String(q.explanation) : undefined,
      selectedAnswer: undefined,
    })
  );

  return mapped;
}

function getPerformanceMessage(percentage: number, language: 'en' | 'bn'): string {
  if (percentage >= 90) return t('edu.perfectScore', language);
  if (percentage >= 80) return t('edu.greatJob', language);
  if (percentage >= 60) return t('edu.goodWork', language);
  if (percentage >= 40) return t('edu.keepPracticing', language);
  return t('edu.needsPractice', language);
}

// ─── Component ───────────────────────────────────────────────────────────────

export default function EducationModule() {
  const { language, setCurrentSection } = useAppStore();

  // View state
  const [view, setView] = useState<ViewMode>('main');
  const [activeTab, setActiveTab] = useState('quiz');

  // Wizard state
  const [wizardStep, setWizardStep] = useState<WizardStep>(1);
  const [selectedClass, setSelectedClass] = useState<string | null>(null);
  const [selectedTopic, setSelectedTopic] = useState<string | null>(null);
  const [selectedChapter, setSelectedChapter] = useState<string | null>(null);
  const [selectedQuestionCount, setSelectedQuestionCount] = useState<number | null>(null);

  // Quiz state
  const [questions, setQuestions] = useState<QuizQuestion[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<string | null>(null);
  const [isAnswered, setIsAnswered] = useState(false);
  const [score, setScore] = useState(0);
  const [timeLeft, setTimeLeft] = useState(0);
  const [totalTimerSeconds, setTotalTimerSeconds] = useState(0);
  const [quizStartTime, setQuizStartTime] = useState(0);
  const [timeTaken, setTimeTaken] = useState(0);

  // Result state
  const [showAnswers, setShowAnswers] = useState(false);

  // Loading & error states
  const [isLoading, setIsLoading] = useState(false);
  const [fetchError, setFetchError] = useState<string | null>(null);

  // ─── Handlers ────────────────────────────────────────────────────────────

  const handleSubmitQuiz = useCallback(() => {
    const elapsed = Math.floor((Date.now() - quizStartTime) / 1000);
    setTimeTaken(elapsed);
    setView('result');
  }, [quizStartTime]);

  // ─── Timer ───────────────────────────────────────────────────────────────

  useEffect(() => {
    if (view !== 'quiz' || timeLeft <= 0) return;

    const interval = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          clearInterval(interval);
          handleSubmitQuiz();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(interval);
  }, [view, timeLeft <= 0, handleSubmitQuiz]);

  const startQuiz = useCallback(async () => {
    if (!selectedClass || !selectedQuestionCount) return;

    const timerSeconds = questionCountOptions.find(o => o.count === selectedQuestionCount)?.timeMinutes || 10;
    const totalSec = timerSeconds * 60;

    setIsLoading(true);
    setFetchError(null);
    setView('loading');

    try {
      const fetched = await fetchQuestionsFromAPI(
        selectedClass,
        selectedTopic || 'all',
        selectedChapter || 'all',
        selectedQuestionCount
      );

      if (fetched.length === 0) {
        setFetchError('No questions available for this selection. Please try a different topic or class.');
        setIsLoading(false);
        setView('quiz'); // show error in quiz view
        return;
      }

      setQuestions(fetched);
      setCurrentQuestionIndex(0);
      setSelectedAnswer(null);
      setIsAnswered(false);
      setScore(0);
      setTimeLeft(totalSec);
      setTotalTimerSeconds(totalSec);
      setQuizStartTime(Date.now());
      setTimeTaken(0);
      setShowAnswers(false);
      setIsLoading(false);
      setView('quiz');
    } catch {
      setFetchError('Failed to load questions. Please try again.');
      setIsLoading(false);
      setView('quiz'); // show error in quiz view
    }
  }, [selectedClass, selectedTopic, selectedChapter, selectedQuestionCount]);

  const handleSelectAnswer = (answer: string) => {
    if (isAnswered) return;
    setSelectedAnswer(answer);
    setIsAnswered(true);

    const currentQuestion = questions[currentQuestionIndex];
    const isCorrect = answer === currentQuestion.correctAnswer;

    if (isCorrect) {
      setScore((prev) => prev + 1);
    }

    setQuestions((prev) =>
      prev.map((q, i) =>
        i === currentQuestionIndex ? { ...q, selectedAnswer: answer } : q
      )
    );
  };

  const handleNextQuestion = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex((prev) => prev + 1);
      setSelectedAnswer(null);
      setIsAnswered(false);
    }
  };

  const handleJumpToQuestion = (index: number) => {
    setCurrentQuestionIndex(index);
    const q = questions[index];
    if (q.selectedAnswer) {
      setSelectedAnswer(q.selectedAnswer);
      setIsAnswered(true);
    } else {
      setSelectedAnswer(null);
      setIsAnswered(false);
    }
  };

  const handleTryAgain = () => {
    // Re-shuffle questions by starting a new quiz with same selections
    startQuiz();
  };

  const handleBackToHome = () => {
    setView('main');
    setWizardStep(1);
    setSelectedClass(null);
    setSelectedTopic(null);
    setSelectedChapter(null);
    setSelectedQuestionCount(null);
    setQuestions([]);
    setCurrentQuestionIndex(0);
    setSelectedAnswer(null);
    setIsAnswered(false);
    setScore(0);
    setShowAnswers(false);
    setIsLoading(false);
    setFetchError(null);
  };

  const openWizard = () => {
    setWizardStep(1);
    setSelectedClass(null);
    setSelectedTopic(null);
    setSelectedChapter(null);
    setSelectedQuestionCount(null);
    setView('wizard');
  };

  const handleWizardNext = () => {
    if (wizardStep < 4) {
      setWizardStep((prev) => (prev + 1) as WizardStep);
    }
  };

  const handleWizardBack = () => {
    if (wizardStep > 1) {
      setWizardStep((prev) => (prev - 1) as WizardStep);
    } else {
      setView('main');
    }
  };

  // ─── Computed values ─────────────────────────────────────────────────────

  const currentQuestion = questions[currentQuestionIndex];
  const questionCount = questions.length || selectedQuestionCount || 20;
  const percentage = questions.length > 0 ? Math.round((score / questions.length) * 100) : 0;
  const isLastQuestion = currentQuestionIndex === questions.length - 1;
  const progressValue = ((currentQuestionIndex + 1) / questionCount) * 100;
  const timerPercentage = totalTimerSeconds > 0 ? (timeLeft / totalTimerSeconds) * 100 : 0;
  const answeredCount = questions.filter(q => q.selectedAnswer).length;
  const correctCount = questions.filter(q => q.selectedAnswer === q.correctAnswer).length;
  const wrongCount = answeredCount - correctCount;
  const avgTimePerQ = timeTaken > 0 && answeredCount > 0 ? (timeTaken / answeredCount).toFixed(1) : '0';

  // ─── Render: Loading View ────────────────────────────────────────────────

  if (view === 'loading' || isLoading) {
    return (
      <div className="flex min-h-[calc(100vh-8rem)] flex-col items-center justify-center px-4">
        <div className="flex flex-col items-center gap-4">
          <div className="relative">
            <div className="h-16 w-16 rounded-full border-4 border-primary/20 border-t-primary animate-spin" />
            <Brain className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-6 w-6 text-primary" />
          </div>
          <div className="text-center">
            <p className="text-lg font-semibold text-foreground">{t('edu.loadingQuestions', language) || 'Loading Questions...'}</p>
            <p className="text-sm text-muted-foreground mt-1">{t('edu.pleaseWait', language) || 'Please wait while we prepare your quiz'}</p>
          </div>
        </div>
      </div>
    );
  }

  // ─── Render: Error / No Questions View ──────────────────────────────────

  if ((view === 'quiz') && fetchError && questions.length === 0) {
    return (
      <div className="flex min-h-[calc(100vh-8rem)] flex-col items-center justify-center px-4">
        <div className="flex flex-col items-center gap-4 max-w-sm text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/30">
            <XCircle className="h-8 w-8 text-red-500" />
          </div>
          <div>
            <p className="text-lg font-semibold text-foreground">
              {fetchError.includes('No questions') ? (t('edu.noQuestions', language) || 'No Questions Available') : (t('edu.loadError', language) || 'Failed to Load Questions')}
            </p>
            <p className="text-sm text-muted-foreground mt-1">{fetchError}</p>
          </div>
          <div className="flex gap-3 w-full">
            <Button
              onClick={() => startQuiz()}
              className="flex-1 bg-gradient-to-r from-orange-600 to-orange-500 gap-2 h-11 text-white"
            >
              <RotateCcw className="h-4 w-4" />
              {t('edu.tryAgain', language)}
            </Button>
            <Button
              onClick={handleBackToHome}
              variant="outline"
              className="flex-1 gap-2 h-11"
            >
              <ArrowLeft className="h-4 w-4" />
              {t('edu.backToHome', language)}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  // ─── Render: Quiz View ───────────────────────────────────────────────────

  if (view === 'quiz' && currentQuestion) {
    return (
      <div className="flex min-h-[calc(100vh-8rem)] flex-col bg-gradient-to-b from-slate-50 to-white dark:from-slate-950/20 dark:to-background">
        {/* Quiz Header */}
        <div className="sticky top-0 z-10 border-b bg-background/95 backdrop-blur-sm">
          <div className="flex items-center justify-between px-4 py-3">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleBackToHome}
              className="gap-1 text-muted-foreground"
            >
              <ArrowLeft className="h-4 w-4" />
              {t('edu.back', language)}
            </Button>
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                <CheckCircle2 className="h-3.5 w-3.5 text-green-500" />
                <span className="text-green-600 dark:text-green-400 font-medium">{correctCount}</span>
                <XCircle className="h-3.5 w-3.5 text-red-500 ml-1" />
                <span className="text-red-600 dark:text-red-400 font-medium">{wrongCount}</span>
              </div>
              <Badge
                variant={timeLeft <= 60 ? 'destructive' : timeLeft <= 180 ? 'secondary' : 'outline'}
                className={`gap-1 font-mono text-sm px-3 py-1 ${
                  timeLeft <= 60 ? 'animate-pulse' : timeLeft <= 180 ? 'border-amber-400 text-amber-600' : 'border-primary/30 text-primary'
                }`}
              >
                <Clock className="h-3.5 w-3.5" />
                {formatTime(timeLeft)}
              </Badge>
            </div>
          </div>

          {/* Timer bar */}
          <div className="h-1.5 w-full bg-muted">
            <div
              className={`h-full transition-all duration-1000 rounded-r-full ${
                timeLeft <= 60
                  ? 'bg-gradient-to-r from-red-500 to-red-400'
                  : timeLeft <= 180
                  ? 'bg-gradient-to-r from-amber-500 to-amber-400'
                  : 'bg-gradient-to-r from-primary to-primary/90'
              }`}
              style={{ width: `${timerPercentage}%` }}
            />
          </div>

          {/* Progress */}
          <div className="px-4 py-2">
            <div className="flex items-center justify-between text-sm">
              <span className="font-medium text-foreground">
                {t('edu.questionOf', language)
                  .replace('{current}', String(currentQuestionIndex + 1))
                  .replace('{total}', String(questionCount))}
              </span>
              <span className="text-muted-foreground">
                {t('edu.score', language)}: {score}/{answeredCount}
              </span>
            </div>
            <Progress value={progressValue} className="mt-1.5 h-2" />
          </div>
        </div>

        {/* Question Content */}
        <div className="flex flex-1 flex-col px-4 py-5">
          {/* Topic Badge */}
          <div className="mb-4 flex items-center gap-2">
            <Badge variant="outline" className="gap-1 border-primary/30 text-primary">
              <Brain className="h-3 w-3" />
              {currentQuestion.topic}
            </Badge>
            <Badge
              variant="secondary"
              className={
                currentQuestion.difficulty === 'easy'
                  ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
                  : currentQuestion.difficulty === 'medium'
                  ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
                  : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
              }
            >
              {currentQuestion.difficulty}
            </Badge>
          </div>

          {/* Question Card */}
          <Card className="mb-5 shadow-md border-0 bg-gradient-to-br from-card to-card/80">
            <CardContent className="p-5">
              <h2 className="text-lg font-semibold leading-relaxed text-foreground sm:text-xl">
                {currentQuestion.question}
              </h2>
            </CardContent>
          </Card>

          {/* Options */}
          <div className="space-y-3">
            {optionLabels.map((option) => {
              const optionText =
                option === 'A'
                  ? currentQuestion.optionA
                  : option === 'B'
                  ? currentQuestion.optionB
                  : option === 'C'
                  ? currentQuestion.optionC
                  : currentQuestion.optionD;

              const isSelected = selectedAnswer === option;
              const isCorrect = currentQuestion.correctAnswer === option;

              let optionStyle =
                'border-border bg-card hover:border-primary/40 hover:bg-primary/5 hover:shadow-sm cursor-pointer';

              if (isAnswered) {
                if (isCorrect) {
                  optionStyle =
                    'border-green-500 bg-green-50 dark:bg-green-900/20 shadow-sm ring-2 ring-green-500/30';
                } else if (isSelected && !isCorrect) {
                  optionStyle =
                    'border-red-500 bg-red-50 dark:bg-red-900/20 shadow-sm ring-2 ring-red-500/30';
                } else {
                  optionStyle =
                    'border-border bg-card opacity-50';
                }
              } else if (isSelected) {
                optionStyle =
                  'border-primary bg-primary/10 shadow-sm ring-2 ring-primary/30';
              }

              return (
                <button
                  key={option}
                  onClick={() => handleSelectAnswer(option)}
                  disabled={isAnswered}
                  className={`flex w-full items-center gap-3 rounded-xl border-2 p-4 text-left transition-all duration-200 ${optionStyle} ${
                    !isAnswered ? 'active:scale-[0.98] hover:-translate-y-0.5' : ''
                  }`}
                >
                  <span
                    className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-sm font-bold transition-colors ${
                      isAnswered && isCorrect
                        ? 'bg-green-500 text-white'
                        : isAnswered && isSelected && !isCorrect
                        ? 'bg-red-500 text-white'
                        : isSelected
                        ? 'bg-primary text-primary-foreground'
                        : 'bg-muted text-muted-foreground'
                    }`}
                  >
                    {t(getOptionLabelKey(option), language)}
                  </span>
                  <span className="flex-1 text-sm font-medium text-foreground sm:text-base">
                    {optionText}
                  </span>
                  {isAnswered && isCorrect && (
                    <CheckCircle2 className="h-5 w-5 shrink-0 text-green-500" />
                  )}
                  {isAnswered && isSelected && !isCorrect && (
                    <XCircle className="h-5 w-5 shrink-0 text-red-500" />
                  )}
                </button>
              );
            })}
          </div>

          {/* Explanation */}
          {isAnswered && currentQuestion.explanation && (
            <div className="mt-4 rounded-xl bg-gradient-to-r from-primary/5 to-primary/5 border border-primary/20 p-4">
              <p className="text-xs font-semibold text-primary mb-1 flex items-center gap-1">
                <Sparkles className="h-3.5 w-3.5" />
                {t('edu.explanation', language)}
              </p>
              <p className="text-sm text-muted-foreground">
                {currentQuestion.explanation}
              </p>
            </div>
          )}

          {/* Action Buttons */}
          <div className="mt-5 flex gap-3">
            {isAnswered && !isLastQuestion && (
              <Button
                onClick={handleNextQuestion}
                className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold h-11"
                size="lg"
              >
                {t('edu.next', language)}
                <ChevronRight className="h-4 w-4" />
              </Button>
            )}
            {isAnswered && isLastQuestion && (
              <Button
                onClick={handleSubmitQuiz}
                className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold h-11"
                size="lg"
              >
                {t('edu.submit', language)}
              </Button>
            )}
            {!isAnswered && !isLastQuestion && (
              <Button
                variant="ghost"
                onClick={handleNextQuestion}
                className="text-muted-foreground"
              >
                {t('edu.skipQuestion', language)}
                <ChevronRight className="h-4 w-4" />
              </Button>
            )}
          </div>

          {/* Question Navigation Dots */}
          <div className="mt-5">
            <p className="text-xs text-muted-foreground mb-2">{t('edu.questionNav', language)}</p>
            <div className="flex flex-wrap gap-1.5 max-h-24 overflow-y-auto custom-scrollbar">
              {questions.map((q, idx) => {
                const isCurrent = idx === currentQuestionIndex;
                const isAnsweredQ = !!q.selectedAnswer;
                const isCorrectQ = q.selectedAnswer === q.correctAnswer;
                const isWrongQ = q.selectedAnswer && q.selectedAnswer !== q.correctAnswer;

                return (
                  <button
                    key={idx}
                    onClick={() => handleJumpToQuestion(idx)}
                    className={`flex h-7 w-7 items-center justify-center rounded-md text-xs font-medium transition-all ${
                      isCurrent
                        ? 'ring-2 ring-primary bg-primary text-primary-foreground scale-110'
                        : isCorrectQ
                        ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
                        : isWrongQ
                        ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
                        : isAnsweredQ
                        ? 'bg-muted text-muted-foreground'
                        : 'bg-muted/50 text-muted-foreground hover:bg-muted'
                    }`}
                  >
                    {idx + 1}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ─── Render: Result View ─────────────────────────────────────────────────

  if (view === 'result') {
    const performanceMessage = getPerformanceMessage(percentage, language);
    const isExcellent = percentage >= 80;

    // Celebration emojis based on score
    const celebrationEmojis = percentage >= 90 ? ['🏆', '🌟', '🎯', '✨', '🎉'] :
      percentage >= 70 ? ['🎉', '👏', '🌟', '✨'] :
      percentage >= 50 ? ['👍', '💪', '📚'] :
      ['💪', '📚', '🔄'];

    return (
      <div className="flex min-h-[calc(100vh-8rem)] flex-col">
        {/* Celebration Header */}
        <div
          className={`relative overflow-hidden px-6 py-10 text-center ${
            isExcellent
              ? 'bg-gradient-to-br from-orange-600 via-orange-500 to-amber-400'
              : percentage >= 50
              ? 'bg-gradient-to-br from-orange-500 to-amber-500'
              : 'bg-gradient-to-br from-slate-500 to-slate-600'
          }`}
        >
          {/* Floating celebration elements */}
          {celebrationEmojis.map((emoji, i) => (
            <span
              key={i}
              className="absolute text-2xl opacity-20 animate-bounce"
              style={{
                left: `${15 + i * 18}%`,
                top: `${10 + (i % 3) * 25}%`,
                animationDelay: `${i * 0.3}s`,
                animationDuration: `${2 + i * 0.5}s`,
              }}
            >
              {emoji}
            </span>
          ))}

          {/* Decorative circles */}
          <div className="absolute -top-8 -left-8 h-32 w-32 rounded-full bg-white/10" />
          <div className="absolute -bottom-6 -right-6 h-24 w-24 rounded-full bg-white/10" />
          <div className="absolute top-4 right-12 h-16 w-16 rounded-full bg-white/5" />

          {/* Trophy icon */}
          <div className="relative mx-auto mb-4 flex h-20 w-20 items-center justify-center">
            <div className="absolute inset-0 animate-ping rounded-full bg-white/20" />
            <div className="relative flex h-16 w-16 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm">
              <Trophy className="h-8 w-8 text-white" />
            </div>
          </div>

          <h2 className="text-2xl font-bold text-white sm:text-3xl">
            {t('edu.result', language)}
          </h2>

          <div className="mt-3">
            <span className="text-5xl font-black text-white sm:text-6xl">
              {score}
            </span>
            <span className="text-xl text-white/80">/{questionCount}</span>
          </div>

          <p className="mt-2 text-lg font-semibold text-white">
            {percentage}% {t('edu.correct', language)}
          </p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-3 gap-3 px-4 -mt-6 relative z-10">
          <Card className="border shadow-lg">
            <CardContent className="flex flex-col items-center py-4">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-orange-100 dark:bg-orange-900/30">
                <Zap className="h-5 w-5 text-orange-600 dark:text-orange-400" />
              </div>
              <span className="mt-2 text-xl font-bold text-foreground">{percentage}%</span>
              <span className="text-xs text-muted-foreground">{t('edu.accuracy', language)}</span>
            </CardContent>
          </Card>

          <Card className="border shadow-lg">
            <CardContent className="flex flex-col items-center py-4">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30">
                <Clock className="h-5 w-5 text-amber-600 dark:text-amber-400" />
              </div>
              <span className="mt-2 text-xl font-bold text-foreground">
                {Math.floor(timeTaken / 60)}:{(timeTaken % 60).toString().padStart(2, '0')}
              </span>
              <span className="text-xs text-muted-foreground">{t('edu.timeTaken', language)}</span>
            </CardContent>
          </Card>

          <Card className="border shadow-lg">
            <CardContent className="flex flex-col items-center py-4">
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30">
                <Target className="h-5 w-5 text-amber-600 dark:text-amber-400" />
              </div>
              <span className="mt-2 text-xl font-bold text-foreground">{avgTimePerQ}s</span>
              <span className="text-xs text-muted-foreground">{t('edu.avgTimePerQ', language)}</span>
            </CardContent>
          </Card>
        </div>

        {/* Performance Analysis */}
        <div className="px-4 pt-5">
          <Card
            className={`border-2 overflow-hidden ${
              isExcellent
                ? 'border-orange-300 bg-gradient-to-r from-orange-50 to-amber-50 dark:border-orange-800 dark:from-orange-900/10 dark:to-amber-900/10'
                : percentage >= 50
                ? 'border-amber-300 bg-amber-50 dark:border-amber-800 dark:bg-amber-900/10'
                : 'border-slate-300 bg-slate-50 dark:border-slate-700 dark:bg-slate-900/10'
            }`}
          >
            <CardContent className="py-5">
              <p className="text-lg font-semibold text-foreground text-center mb-3">
                {performanceMessage}
              </p>
              <Progress value={percentage} className="h-3" />
              <div className="mt-3 grid grid-cols-2 gap-2 text-center">
                <div className="rounded-lg bg-green-100/50 dark:bg-green-900/20 p-2">
                  <p className="text-sm font-bold text-green-700 dark:text-green-400">{correctCount} {t('edu.correct', language)}</p>
                </div>
                <div className="rounded-lg bg-red-100/50 dark:bg-red-900/20 p-2">
                  <p className="text-sm font-bold text-red-700 dark:text-red-400">{wrongCount} {t('edu.wrong', language)}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Action Buttons */}
        <div className="mt-auto px-4 py-6 space-y-3">
          <Button
            onClick={() => setShowAnswers(true)}
            variant="outline"
            className="w-full gap-2 h-11"
          >
            <Eye className="h-4 w-4" />
            {t('edu.viewAnswers', language)}
          </Button>

          <div className="grid grid-cols-2 gap-3">
            <Button
              onClick={handleTryAgain}
              variant="outline"
              className="gap-2 h-11"
            >
              <RotateCcw className="h-4 w-4" />
              {t('edu.tryAgain', language)}
            </Button>

            <Button
              onClick={handleBackToHome}
              className="bg-gradient-to-r from-orange-600 to-orange-500 gap-2 h-11 text-white"
            >
              <ArrowLeft className="h-4 w-4" />
              {t('edu.backToHome', language)}
            </Button>
          </div>

          <Button
            variant="ghost"
            className="w-full gap-2 h-10 text-muted-foreground"
            onClick={() => {
              if (navigator.share) {
                navigator.share({
                  title: 'Needyfy MCQ Score',
                  text: `I scored ${score}/${questionCount} (${percentage}%) on my MCQ test! ${performanceMessage}`,
                }).catch(() => {});
              }
            }}
          >
            <Share2 className="h-4 w-4" />
            {t('edu.shareScore', language)}
          </Button>
        </div>

        {/* View Answers Dialog */}
        <Dialog open={showAnswers} onOpenChange={setShowAnswers}>
          <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <BookOpen className="h-5 w-5 text-primary" />
                {t('edu.reviewAnswers', language)}
              </DialogTitle>
            </DialogHeader>
            <div className="space-y-4 pr-1">
              {questions.map((q, idx) => {
                const isUserCorrect = q.selectedAnswer === q.correctAnswer;
                return (
                  <Card
                    key={`${q.id}-${idx}`}
                    className={`border ${
                      isUserCorrect
                        ? 'border-green-300 dark:border-green-800'
                        : 'border-red-300 dark:border-red-800'
                    }`}
                  >
                    <CardContent className="py-4">
                      <div className="flex items-start gap-2">
                        <span
                          className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-bold ${
                            isUserCorrect
                              ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
                              : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
                          }`}
                        >
                          {idx + 1}
                        </span>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-foreground">
                            {q.question}
                          </p>
                          <div className="mt-2 space-y-1 text-xs">
                            {q.selectedAnswer && (
                              <p className={
                                isUserCorrect
                                  ? 'text-green-600 dark:text-green-400'
                                  : 'text-red-600 dark:text-red-400'
                              }>
                                {t('edu.yourAnswer', language)}: {t(getOptionLabelKey(q.selectedAnswer), language)} —{' '}
                                {q.selectedAnswer === 'A'
                                  ? q.optionA
                                  : q.selectedAnswer === 'B'
                                  ? q.optionB
                                  : q.selectedAnswer === 'C'
                                  ? q.optionC
                                  : q.optionD}
                              </p>
                            )}
                            {!q.selectedAnswer && (
                              <p className="text-muted-foreground italic">
                                {t('edu.yourAnswer', language)}: —
                              </p>
                            )}
                            {!isUserCorrect && (
                              <p className="text-green-600 dark:text-green-400 font-medium">
                                {t('edu.correctAnswer', language)}: {t(getOptionLabelKey(q.correctAnswer), language)} —{' '}
                                {q.correctAnswer === 'A'
                                  ? q.optionA
                                  : q.correctAnswer === 'B'
                                  ? q.optionB
                                  : q.correctAnswer === 'C'
                                  ? q.optionC
                                  : q.optionD}
                              </p>
                            )}
                            {q.explanation && (
                              <p className="text-muted-foreground mt-1">
                                💡 {q.explanation}
                              </p>
                            )}
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </DialogContent>
        </Dialog>
      </div>
    );
  }

  // ─── Render: Wizard View ─────────────────────────────────────────────────

  if (view === 'wizard') {
    const stepLabels = [
      t('edu.stepClass', language),
      t('edu.stepTopic', language),
      t('edu.stepChapter', language),
      t('edu.stepCount', language),
    ];

    return (
      <div className="flex min-h-[calc(100vh-8rem)] flex-col">
        {/* Wizard Header */}
        <div className="bg-gradient-to-r from-orange-600 via-orange-500 to-amber-400 px-4 pb-6 pt-4">
          <div className="flex items-center gap-3 mb-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleWizardBack}
              className="text-white/80 hover:text-white hover:bg-white/10 gap-1"
            >
              <ChevronLeft className="h-4 w-4" />
              {t('edu.back', language)}
            </Button>
          </div>

          {/* Stepper */}
          <div className="flex items-center justify-between">
            {stepLabels.map((label, idx) => {
              const stepNum = (idx + 1) as WizardStep;
              const isActive = wizardStep === stepNum;
              const isComplete = wizardStep > stepNum;

              return (
                <div key={idx} className="flex items-center">
                  <div className="flex flex-col items-center">
                    <div
                      className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold transition-all ${
                        isActive
                          ? 'bg-white text-orange-600 ring-2 ring-white/50 scale-110'
                          : isComplete
                          ? 'bg-white/30 text-white'
                          : 'bg-white/10 text-white/50'
                      }`}
                    >
                      {isComplete ? <CheckCircle2 className="h-4 w-4" /> : stepNum}
                    </div>
                    <span className={`text-[10px] mt-1 ${
                      isActive ? 'text-white font-medium' : 'text-white/50'
                    }`}>
                      {label}
                    </span>
                  </div>
                  {idx < 3 && (
                    <div className={`h-0.5 w-8 mx-1 mb-4 ${
                      wizardStep > stepNum ? 'bg-white/50' : 'bg-white/15'
                    }`} />
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Wizard Content */}
        <div className="flex-1 px-4 py-5">
          {/* Step 1: Select Class */}
          {wizardStep === 1 && (
            <div>
              <h2 className="text-lg font-bold text-foreground mb-1">
                {t('edu.selectClass', language)}
              </h2>
              <p className="text-sm text-muted-foreground mb-4">
                {t('edu.step', language).replace('{current}', '1').replace('{total}', '4')}
              </p>
              <div className="grid grid-cols-2 gap-3">
                {classOptions.map((cls) => {
                  const Icon = cls.icon;
                  const isSelected = selectedClass === cls.id;
                  return (
                    <button
                      key={cls.id}
                      onClick={() => {
                        setSelectedClass(cls.id);
                        setSelectedTopic(null);
                        setSelectedChapter(null);
                      }}
                      className={`relative flex flex-col items-center gap-2 rounded-2xl p-4 border-2 transition-all duration-200 ${
                        isSelected
                          ? 'border-orange-500 bg-orange-50 shadow-lg shadow-orange-200/50 ring-2 ring-orange-300 dark:bg-orange-900/20 dark:shadow-orange-900/30 dark:ring-orange-700'
                          : 'border-border bg-card hover:border-primary/30 hover:shadow-md hover:-translate-y-0.5'
                      }`}
                    >
                      <div className={`flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br ${cls.gradient} shadow-md`}>
                        <Icon className="h-6 w-6 text-white" />
                      </div>
                      <span className={`text-sm font-semibold ${isSelected ? 'text-orange-700 dark:text-orange-300' : 'text-foreground'}`}>
                        {t(cls.labelKey, language)}
                      </span>
                      {isSelected && (
                        <div className="absolute -top-1.5 -right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-orange-500 text-white">
                          <CheckCircle2 className="h-3.5 w-3.5" />
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Step 2: Select Topic */}
          {wizardStep === 2 && selectedClass && (
            <div>
              <h2 className="text-lg font-bold text-foreground mb-1">
                {t('edu.selectTopic', language)}
              </h2>
              <p className="text-sm text-muted-foreground mb-4">
                {t('edu.step', language).replace('{current}', '2').replace('{total}', '4')}
              </p>
              <div className="grid grid-cols-2 gap-3">
                {(topicsByClass[selectedClass] || []).map((topic) => {
                  const Icon = topic.icon;
                  const isSelected = selectedTopic === topic.id;
                  return (
                    <button
                      key={topic.id}
                      onClick={() => {
                        setSelectedTopic(topic.id);
                        setSelectedChapter(null);
                      }}
                      className={`relative flex flex-col items-center gap-2 rounded-2xl p-4 border-2 transition-all duration-200 ${
                        isSelected
                          ? 'border-orange-500 bg-orange-50 shadow-lg shadow-orange-200/50 ring-2 ring-orange-300 dark:bg-orange-900/20 dark:shadow-orange-900/30 dark:ring-orange-700'
                          : 'border-border bg-card hover:border-primary/30 hover:shadow-md hover:-translate-y-0.5'
                      }`}
                    >
                      <div className={`flex h-12 w-12 items-center justify-center rounded-xl ${
                        isSelected ? 'bg-gradient-to-br from-orange-500 to-amber-500' : 'bg-gradient-to-br from-primary/80 to-primary'
                      } shadow-md`}>
                        <Icon className="h-6 w-6 text-white" />
                      </div>
                      <span className={`text-sm font-semibold ${isSelected ? 'text-orange-700 dark:text-orange-300' : 'text-foreground'}`}>
                        {t(topic.labelKey, language)}
                      </span>
                      {isSelected && (
                        <div className="absolute -top-1.5 -right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-orange-500 text-white">
                          <CheckCircle2 className="h-3.5 w-3.5" />
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Step 3: Select Chapter */}
          {wizardStep === 3 && selectedTopic && (
            <div>
              <h2 className="text-lg font-bold text-foreground mb-1">
                {t('edu.selectChapter', language)}
              </h2>
              <p className="text-sm text-muted-foreground mb-4">
                {t('edu.step', language).replace('{current}', '3').replace('{total}', '4')}
              </p>
              <div className="space-y-2">
                {(chaptersByTopic[selectedTopic] || []).map((chapter) => {
                  const isSelected = selectedChapter === chapter.id;
                  return (
                    <button
                      key={chapter.id}
                      onClick={() => setSelectedChapter(chapter.id)}
                      className={`flex w-full items-center gap-3 rounded-xl p-3.5 border-2 transition-all duration-200 ${
                        isSelected
                          ? 'border-orange-500 bg-orange-50 shadow-md shadow-orange-200/50 ring-2 ring-orange-300 dark:bg-orange-900/20 dark:shadow-orange-900/30 dark:ring-orange-700'
                          : 'border-border bg-card hover:border-primary/30 hover:shadow-sm'
                      }`}
                    >
                      <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${
                        isSelected
                          ? 'bg-gradient-to-br from-orange-500 to-amber-500 text-white'
                          : 'bg-muted text-muted-foreground'
                      }`}>
                        <BookOpen className="h-4 w-4" />
                      </div>
                      <span className={`text-sm font-semibold flex-1 text-left ${isSelected ? 'text-orange-700 dark:text-orange-300' : 'text-foreground'}`}>
                        {t(chapter.labelKey, language)}
                      </span>
                      {isSelected && (
                        <CheckCircle2 className="h-5 w-5 text-orange-500" />
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Step 4: Select Question Count */}
          {wizardStep === 4 && (
            <div>
              <h2 className="text-lg font-bold text-foreground mb-1">
                {t('edu.selectCount', language)}
              </h2>
              <p className="text-sm text-muted-foreground mb-4">
                {t('edu.step', language).replace('{current}', '4').replace('{total}', '4')}
              </p>
              <div className="grid grid-cols-3 gap-3">
                {questionCountOptions.map((option) => {
                  const isSelected = selectedQuestionCount === option.count;
                  return (
                    <button
                      key={option.count}
                      onClick={() => setSelectedQuestionCount(option.count)}
                      className={`relative flex flex-col items-center gap-2 rounded-2xl p-5 border-2 transition-all duration-200 ${
                        isSelected
                          ? 'border-orange-500 bg-orange-50 shadow-lg shadow-orange-200/50 ring-2 ring-orange-300 dark:bg-orange-900/20 dark:shadow-orange-900/30 dark:ring-orange-700 scale-105'
                          : 'border-border bg-card hover:border-primary/30 hover:shadow-md hover:-translate-y-0.5'
                      }`}
                    >
                      <div className={`flex h-14 w-14 items-center justify-center rounded-xl ${
                        isSelected ? 'bg-gradient-to-br from-orange-500 to-amber-500' : 'bg-gradient-to-br from-primary/80 to-primary'
                      } shadow-md`}>
                        <Clock className="h-7 w-7 text-white" />
                      </div>
                      <span className={`text-2xl font-black ${isSelected ? 'text-orange-700 dark:text-orange-300' : 'text-foreground'}`}>
                        {option.count}
                      </span>
                      <span className={`text-xs font-medium ${isSelected ? 'text-orange-600 dark:text-orange-400' : 'text-muted-foreground'}`}>
                        {option.timeMinutes} {t('edu.minutes', language)}
                      </span>
                      {isSelected && (
                        <div className="absolute -top-1.5 -right-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-orange-500 text-white">
                          <CheckCircle2 className="h-3.5 w-3.5" />
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>

              {/* Summary Card */}
              {selectedClass && selectedTopic && selectedChapter && selectedQuestionCount && (
                <Card className="mt-5 border-2 border-orange-200 bg-gradient-to-r from-orange-50 to-amber-50 dark:border-orange-800 dark:from-orange-900/20 dark:to-amber-900/20 shadow-lg">
                  <CardContent className="py-4">
                    <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-1.5">
                      <Sparkles className="h-4 w-4 text-orange-500" />
                      {t('edu.startTest', language)}
                    </h3>
                    <div className="grid grid-cols-2 gap-2 text-xs">
                      <div className="rounded-lg bg-white/60 dark:bg-white/5 p-2">
                        <span className="text-muted-foreground">{t('edu.stepClass', language)}:</span>
                        <p className="font-semibold text-foreground">{t(classOptions.find(c => c.id === selectedClass)?.labelKey || '', language)}</p>
                      </div>
                      <div className="rounded-lg bg-white/60 dark:bg-white/5 p-2">
                        <span className="text-muted-foreground">{t('edu.stepTopic', language)}:</span>
                        <p className="font-semibold text-foreground">{t(topicsByClass[selectedClass]?.find(tp => tp.id === selectedTopic)?.labelKey || '', language)}</p>
                      </div>
                      <div className="rounded-lg bg-white/60 dark:bg-white/5 p-2">
                        <span className="text-muted-foreground">{t('edu.stepChapter', language)}:</span>
                        <p className="font-semibold text-foreground">{t(chaptersByTopic[selectedTopic]?.find(ch => ch.id === selectedChapter)?.labelKey || '', language)}</p>
                      </div>
                      <div className="rounded-lg bg-white/60 dark:bg-white/5 p-2">
                        <span className="text-muted-foreground">{t('edu.questions', language)}:</span>
                        <p className="font-semibold text-foreground">{selectedQuestionCount} · {questionCountOptions.find(o => o.count === selectedQuestionCount)?.timeMinutes} {t('edu.minutes', language)}</p>
                      </div>
                    </div>
                    <Button
                      onClick={startQuiz}
                      className="w-full mt-4 bg-gradient-to-r from-orange-600 to-orange-500 font-bold h-12 text-white shadow-lg shadow-orange-300/30 dark:shadow-orange-900/30 text-base"
                      size="lg"
                    >
                      <Zap className="h-5 w-5 mr-2" />
                      {t('edu.startTest', language)}
                    </Button>
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </div>

        {/* Wizard Bottom Navigation */}
        <div className="border-t px-4 py-3 bg-background">
          <div className="flex gap-3">
            {wizardStep > 1 && (
              <Button
                variant="outline"
                onClick={handleWizardBack}
                className="flex-1 gap-1 h-11"
              >
                <ChevronLeft className="h-4 w-4" />
                {t('edu.back', language)}
              </Button>
            )}
            {wizardStep < 4 && (
              <Button
                onClick={handleWizardNext}
                disabled={
                  (wizardStep === 1 && !selectedClass) ||
                  (wizardStep === 2 && !selectedTopic) ||
                  (wizardStep === 3 && !selectedChapter)
                }
                className="flex-1 bg-gradient-to-r from-orange-600 to-orange-500 gap-1 h-11 text-white"
              >
                {t('edu.next', language)}
                <ChevronRight className="h-4 w-4" />
              </Button>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ─── Render: Main View ───────────────────────────────────────────────────

  return (
    <div className="flex min-h-[calc(100vh-8rem)] flex-col">
      {/* Header with gradient */}
      <div className="relative bg-gradient-to-r from-orange-600 via-orange-500 to-amber-400 px-4 pb-10 pt-6 overflow-hidden">
        {/* Animated decorative elements */}
        <div className="absolute top-4 left-8 h-20 w-20 rounded-full bg-white/10 animate-pulse" />
        <div className="absolute top-12 right-16 h-12 w-12 rounded-full bg-white/5 animate-bounce" style={{ animationDuration: '3s' }} />
        <div className="absolute bottom-2 left-1/3 h-8 w-8 rounded-full bg-white/10 animate-ping" style={{ animationDuration: '4s' }} />
        <div className="absolute -bottom-4 right-8 h-28 w-28 rounded-full bg-white/5" />

        <div className="relative z-10">
          <div className="flex items-center gap-3 mb-3">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setCurrentSection('home')}
              className="shrink-0 h-9 w-9 rounded-xl bg-white/20 backdrop-blur-sm text-white hover:bg-white/30"
            >
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-white/20 backdrop-blur-sm">
              <GraduationCap className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-white sm:text-2xl">
                {t('edu.title', language)}
              </h1>
              <p className="text-sm text-white/70">
                {t('edu.practicePerfect', language)}
              </p>
            </div>
          </div>

          {/* Stats Row */}
          <div className="grid grid-cols-3 gap-2 mt-3">
            <div className="rounded-xl bg-white/10 backdrop-blur-sm px-3 py-2 text-center">
              <p className="text-lg font-bold text-white">1,050</p>
              <p className="text-[10px] text-white/70">{t('edu.totalQuestions', language)}</p>
            </div>
            <div className="rounded-xl bg-white/10 backdrop-blur-sm px-3 py-2 text-center">
              <p className="text-lg font-bold text-white">12</p>
              <p className="text-[10px] text-white/70">{t('edu.testsTaken', language)}</p>
            </div>
            <div className="rounded-xl bg-white/10 backdrop-blur-sm px-3 py-2 text-center">
              <p className="text-lg font-bold text-white">76%</p>
              <p className="text-[10px] text-white/70">{t('edu.avgScore', language)}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Quick Start Button */}
      <div className="-mt-5 px-4 relative z-10">
        <button
          onClick={openWizard}
          className="w-full rounded-2xl bg-gradient-to-r from-orange-600 to-orange-500 p-4 shadow-xl shadow-orange-300/30 dark:shadow-orange-900/30 text-white flex items-center justify-between hover:shadow-2xl transition-all active:scale-[0.98]"
        >
          <div className="flex items-center gap-3">
            <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-white/20 backdrop-blur-sm">
              <Zap className="h-5 w-5 text-white" />
            </div>
            <div className="text-left">
              <p className="font-bold text-base">{t('edu.startExam', language)}</p>
              <p className="text-xs text-white/80">{t('edu.selectCategory', language)}</p>
            </div>
          </div>
          <ChevronRight className="h-5 w-5 text-white/60" />
        </button>
      </div>

      {/* Class Quick Access */}
      <div className="px-4 pt-5">
        <h3 className="text-sm font-semibold text-muted-foreground mb-3">
          {t('edu.selectClass', language)}
        </h3>
        <div className="flex gap-3 overflow-x-auto pb-2 scrollbar-hide">
          {classOptions.map((cls) => {
            const Icon = cls.icon;
            return (
              <button
                key={cls.id}
                onClick={() => {
                  setSelectedClass(cls.id);
                  setSelectedTopic(null);
                  setSelectedChapter(null);
                  setSelectedQuestionCount(null);
                  setWizardStep(2);
                  setView('wizard');
                }}
                className="shrink-0 flex flex-col items-center gap-1.5 rounded-2xl border-2 border-transparent bg-card p-3 w-20 shadow-sm hover:shadow-md hover:border-primary/20 transition-all active:scale-95"
              >
                <div className={`flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br ${cls.gradient} shadow-sm`}>
                  <Icon className="h-5 w-5 text-white" />
                </div>
                <span className="text-[11px] font-semibold text-foreground text-center leading-tight">
                  {t(cls.labelKey, language)}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Tabs: Quiz / Leaderboard / History */}
      <div className="flex-1 px-4 pt-4">
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="w-full grid grid-cols-3">
            <TabsTrigger value="quiz" className="gap-1 text-xs sm:text-sm">
              <Zap className="h-3.5 w-3.5" />
              {t('edu.quiz', language)}
            </TabsTrigger>
            <TabsTrigger value="leaderboard" className="gap-1 text-xs sm:text-sm">
              <Trophy className="h-3.5 w-3.5" />
              {t('edu.leaderboard', language)}
            </TabsTrigger>
            <TabsTrigger value="history" className="gap-1 text-xs sm:text-sm">
              <Clock className="h-3.5 w-3.5" />
              {t('edu.history', language)}
            </TabsTrigger>
          </TabsList>

          {/* Quiz Tab - Class Cards */}
          <TabsContent value="quiz" className="mt-4">
            <div className="grid gap-3 sm:grid-cols-2">
              {classOptions.map((cls) => {
                const Icon = cls.icon;
                const topicCount = topicsByClass[cls.id]?.length || 0;
                return (
                  <Card
                    key={cls.id}
                    className="cursor-pointer transition-all hover:shadow-lg hover:border-primary/30 active:scale-[0.98] overflow-hidden group"
                    onClick={() => {
                      setSelectedClass(cls.id);
                      setSelectedTopic(null);
                      setSelectedChapter(null);
                      setSelectedQuestionCount(null);
                      setWizardStep(2);
                      setView('wizard');
                    }}
                  >
                    <CardContent className="flex items-center gap-3 py-4">
                      <div
                        className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br ${cls.gradient} shadow-sm group-hover:shadow-md transition-shadow`}
                      >
                        <Icon className="h-6 w-6 text-white" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="font-semibold text-foreground">
                          {t(cls.labelKey, language)}
                        </h3>
                        <p className="text-xs text-muted-foreground">
                          {topicCount} {t('edu.questions', language).toLowerCase()}
                        </p>
                      </div>
                      <ChevronRight className="h-5 w-5 shrink-0 text-muted-foreground group-hover:text-primary transition-colors" />
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </TabsContent>

          {/* Leaderboard Tab */}
          <TabsContent value="leaderboard" className="mt-4">
            {/* Top 3 Podium */}
            <div className="mb-6 flex items-end justify-center gap-3 pt-4">
              {/* 2nd Place */}
              <div className="flex flex-col items-center">
                <div className="flex h-12 w-12 items-center justify-center rounded-full bg-gradient-to-br from-gray-300 to-gray-400 text-white font-bold text-lg shadow-md">
                  2
                </div>
                <div className="mt-2 rounded-t-lg bg-gray-200 dark:bg-gray-800 px-4 py-1">
                  <Medal className="h-4 w-4 text-gray-500" />
                </div>
                <div className="w-20 rounded-b-lg bg-gray-100 dark:bg-gray-900 py-2 text-center">
                  <p className="text-xs font-semibold text-foreground truncate px-1">
                    —
                  </p>
                  <p className="text-[10px] text-muted-foreground">
                    — {t('edu.points', language)}
                  </p>
                </div>
                <div className="h-16 w-20 bg-gray-200 dark:bg-gray-800" />
              </div>

              {/* 1st Place */}
              <div className="flex flex-col items-center">
                <div className="relative">
                  <Star className="absolute -top-3 left-1/2 -translate-x-1/2 h-5 w-5 text-amber-400 fill-amber-400" />
                  <div className="flex h-14 w-14 items-center justify-center rounded-full bg-gradient-to-br from-amber-400 to-yellow-500 text-white font-bold text-xl shadow-lg">
                    1
                  </div>
                </div>
                <div className="mt-2 rounded-t-lg bg-amber-200 dark:bg-amber-900/40 px-5 py-1">
                  <Trophy className="h-5 w-5 text-amber-600 dark:text-amber-400" />
                </div>
                <div className="w-24 rounded-b-lg bg-amber-50 dark:bg-amber-900/20 py-2 text-center">
                  <p className="text-xs font-semibold text-foreground truncate px-1">
                    —
                  </p>
                  <p className="text-[10px] text-muted-foreground">
                    — {t('edu.points', language)}
                  </p>
                </div>
                <div className="h-24 w-24 bg-amber-200 dark:bg-amber-900/30" />
              </div>

              {/* 3rd Place */}
              <div className="flex flex-col items-center">
                <div className="flex h-12 w-12 items-center justify-center rounded-full bg-gradient-to-br from-amber-600 to-amber-700 text-white font-bold text-lg shadow-md">
                  3
                </div>
                <div className="mt-2 rounded-t-lg bg-amber-100 dark:bg-amber-900/30 px-4 py-1">
                  <Medal className="h-4 w-4 text-amber-700 dark:text-amber-400" />
                </div>
                <div className="w-20 rounded-b-lg bg-amber-50 dark:bg-amber-900/10 py-2 text-center">
                  <p className="text-xs font-semibold text-foreground truncate px-1">
                    —
                  </p>
                  <p className="text-[10px] text-muted-foreground">
                    — {t('edu.points', language)}
                  </p>
                </div>
                <div className="h-10 w-20 bg-amber-100 dark:bg-amber-900/20" />
              </div>
            </div>

            {/* Leaderboard Coming Soon */}
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="flex items-center gap-2 text-base">
                  <Trophy className="h-4 w-4 text-primary" />
                  {t('edu.leaderboard', language)}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-col items-center justify-center py-8 text-center">
                  <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted mb-3">
                    <Trophy className="h-6 w-6 text-muted-foreground" />
                  </div>
                  <p className="text-sm font-medium text-muted-foreground">Coming Soon</p>
                  <p className="text-xs text-muted-foreground mt-1">Leaderboard will be available after more quizzes are completed</p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* History Tab */}
          <TabsContent value="history" className="mt-4">
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted mb-4">
                <GraduationCap className="h-8 w-8 text-muted-foreground" />
              </div>
              <p className="text-sm font-medium text-muted-foreground">
                {t('edu.noHistory', language)}
              </p>
              <p className="text-xs text-muted-foreground mt-1">
                {t('edu.startFirst', language)}
              </p>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
