import React from 'react';
import { ErrorAnalyzerView } from './components/ErrorAnalyzerView';
import { VivaSimulator } from './components/VivaSimulator';
import { calculateLEI } from './lib/lei';
import { analyzeError, type ErrorAnalysis } from './lib/errorAnalyzer';
import { motion, AnimatePresence } from 'framer-motion';
import { generateProjectDoc } from './lib/docGenerator';
import { detectPlagiarism } from './lib/plagiarismDetector';
import { analyzeDocumentation } from './lib/vivaSimulator';
import logo from './assets/logo.png';
import { 
  CheckCircle2, Trophy, ArrowRight, Star, BookOpen, Code2, Award, 
  Download, User, LogOut, Rocket, Flame, Target, Brain, Laptop, 
  Crown, Lock, Info, X, FileText, Upload, Play, LayoutDashboard, Users, Clock, AlertTriangle, MessageSquare
} from 'lucide-react';
import { 
  LEVELS, TRACKS, QUESTION_BANK, PROJECTS, BADGES,
  type LevelId, type TrackId, type Question, type UserProgress, type Project, type Badge, type User as UserType, type EffortLevel, type VivaSession
} from './types';
import { cn } from './lib/utils';
import confetti from 'canvas-confetti';
//import { GoogleGenAI } from "@google/genai";
import { generateCertificate } from './lib/certificate';
import { TeacherDashboard } from './components/TeacherDashboard';
import { Leaderboard } from './components/Leaderboard';

const ICON_MAP: Record<string, any> = {
  Rocket, Flame, Target, Brain, Trophy, Laptop, Crown, Star
};

const parseGrade = (input: string): number | null => {
  const match = input.match(/\d+/);
  return match ? parseInt(match[0], 10) : null;
};

export default function App() {
  const [progress, setProgress] = React.useState<UserProgress>(() => {
    const saved = localStorage.getItem('rs_learning_progress');
    if (saved) {
      const parsed = JSON.parse(saved);
      // Migrate old data if necessary
      return {
        xp: parsed.xp || 0,
        completedTracks: parsed.completedTracks || {},
        completedProjects: parsed.completedProjects || [],
        badges: parsed.badges || [],
        streak: parsed.streak || 0,
        lastActivityDate: parsed.lastActivityDate || null,
        questionsSolved: parsed.questionsSolved || 0,
        name: parsed.name || '',
        grade: parsed.grade || '',
        rollNumber: parsed.rollNumber || '',
        language: parsed.language || undefined,
        timeSpent: parsed.timeSpent || 0,
        totalAttempts: parsed.totalAttempts || 0,
        hintsUsed: parsed.hintsUsed || 0,
        retries: parsed.retries || 0,
        effortLevel: parsed.effortLevel || 'Beginner',
        lastLoginDate: parsed.lastLoginDate || new Date().toISOString(),
        activityLog: parsed.activityLog || [],
        answeredQuestionIds: parsed.answeredQuestionIds || [],
        schoolName: parsed.schoolName || localStorage.getItem('rs_school_name') || '',
        principalName: parsed.principalName || localStorage.getItem('rs_principal_name') || '',
        assignedProject: parsed.assignedProject || undefined,
        projectStatus: parsed.projectStatus || 'not-started'
      };
    }
    return {
      xp: 0,
      completedTracks: {},
      completedProjects: [],
      badges: [],
      streak: 0,
      lastActivityDate: null,
      questionsSolved: 0,
      name: '',
      grade: '',
      rollNumber: '',
      language: undefined,
      timeSpent: 0,
      totalAttempts: 0,
      hintsUsed: 0,
      effortLevel: 'Beginner',
      lastLoginDate: new Date().toISOString(),
      activityLog: [],
      answeredQuestionIds: [],
      schoolName: localStorage.getItem('rs_school_name') || '',
      principalName: localStorage.getItem('rs_principal_name') || '',
      projectStatus: 'not-started'
    };
  });

  const [view, setView] = React.useState<'onboarding' | 'dashboard' | 'challenge' | 'project' | 'project-intro' | 'badges' | 'coding' | 'submission' | 'project-submission' | 'teacher' | 'leaderboard' | 'login'>('onboarding');
  const [user, setUser] = React.useState<UserType | null>(() => {
    const saved = localStorage.getItem('rs_learning_user');
    return saved ? JSON.parse(saved) : null;
  });
  const [loginForm, setLoginForm] = React.useState({ username: '', password: '' });
  const [loginError, setLoginError] = React.useState('');
  const [activeLevel, setActiveLevel] = React.useState<LevelId>(1);
  const [activeTrack, setActiveTrack] = React.useState<TrackId>('basics');
  const [activeProject, setActiveProject] = React.useState<Project | null>(null);
  const [newBadge, setNewBadge] = React.useState<Badge | null>(null);
  const [showLanguageSelector, setShowLanguageSelector] = React.useState(false);
  const [isGeneratingProject, setIsGeneratingProject] = React.useState(false);
  const [docContent, setDocContent] = React.useState({
    objective: '',
    conceptsUsed: '',
    howItWorks: '',
    whatILearned: ''
  });

  // Challenge State
  const [currentQuestionIndex, setCurrentQuestionIndex] = React.useState(0);
  const [selectedOption, setSelectedOption] = React.useState<number | null>(null);
  const [isAnswered, setIsAnswered] = React.useState(false);
  const [showHint, setShowHint] = React.useState(false);
  const [wrongAttempts, setWrongAttempts] = React.useState(0);
  const [questions, setQuestions] = React.useState<Question[]>([]);

  // Coding State
  const [code, setCode] = React.useState('');
  const [evaluationResult, setEvaluationResult] = React.useState<{ success: boolean; message: string } | null>(null);
  const [errorAnalysis, setErrorAnalysis] = React.useState<ErrorAnalysis | null>(null);
  const [currentHintLevel, setCurrentHintLevel] = React.useState(0); // 0: none, 1: small, 2: guidance, 3: full
  const [isEvaluating, setIsEvaluating] = React.useState(false);
  const [isSubmitting, setIsSubmitting] = React.useState(false);

  // Submission State
  const [docText, setDocText] = React.useState('');
  const [trackStartTime, setTrackStartTime] = React.useState<number | null>(null);
  const [trackAttempts, setTrackAttempts] = React.useState(0);
  const [trackHintsUsed, setTrackHintsUsed] = React.useState(0);
  const [trackRetries, setTrackRetries] = React.useState(0);
  const [showViva, setShowViva] = React.useState(false);
  const [vivaRequestedSubmissions, setVivaRequestedSubmissions] = React.useState<any[]>([]);

  React.useEffect(() => {
    const checkVivaRequests = async () => {
      if (!progress.rollNumber) return;
      try {
        const res = await fetch('/api/submissions');
        if (res.ok) {
          const allSubmissions = await res.json();
          const requested = allSubmissions.filter((s: any) => s.rollNumber === progress.rollNumber && s.vivaRequested);
          setVivaRequestedSubmissions(requested);
        }
      } catch (err) {
        console.error("Failed to check viva requests:", err);
      }
    };
    
    if (view === 'dashboard') {
      checkVivaRequests();
    }
  }, [view, progress.rollNumber]);

  React.useEffect(() => {
    if (user?.role === 'teacher' && view === 'teacher') {
      // Teacher panel logic
    } else if (user?.role !== 'teacher' && view === 'teacher') {
      setView('dashboard');
    }
  }, [view, user]);

  const handleVivaComplete = async (session: VivaSession) => {
    if (!progress.rollNumber) return;
    
    const correctCount = session.questions.filter(q => q.evaluation?.isCorrect).length;
    const vivaScore = Math.min(5, Math.round((correctCount / session.questions.length) * 5));

    try {
      // Update student progress
      await fetch('/api/student/viva', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          rollNumber: progress.rollNumber,
          session,
          vivaScore
        })
      });
      
      // Also update the latest submission with the viva score
      const submissionsRes = await fetch('/api/submissions');
      if (submissionsRes.ok) {
        const allSubmissions = await submissionsRes.json();
        const latestSub = allSubmissions
          .filter((s: any) => s.rollNumber === progress.rollNumber && s.track === 'project')
          .sort((a: any, b: any) => new Date(b.submittedAt).getTime() - new Date(a.submittedAt).getTime())[0];
        
        if (latestSub) {
          const updatedMarks = latestSub.marks ? {
            ...latestSub.marks,
            viva: {
              ...latestSub.marks.viva,
              aiScore: vivaScore,
              total: vivaScore + (latestSub.marks.viva?.teacherScore || 0)
            },
            total: (latestSub.marks.documentation?.total || 0) + 
                   (latestSub.marks.code?.total || 0) + 
                   vivaScore + (latestSub.marks.viva?.teacherScore || 0)
          } : null;

          await fetch(`/api/submissions/${latestSub.id}`, {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              vivaScore,
              vivaSummary: session.summary,
              marks: updatedMarks
            })
          });
        }
      }

      setProgress(prev => ({
        ...prev,
        vivaSessions: [...(prev.vivaSessions || []), session],
        vivaSummary: session.summary,
        vivaScore
      }));
      
      setShowViva(false);
      confetti({
        particleCount: 150,
        spread: 70,
        origin: { y: 0.6 },
        colors: ['#0b8c9f', '#000000', '#ffffff']
      });
    } catch (error) {
      console.error("Failed to save viva session:", error);
    }
  };

  const refreshRecommendations = async () => {
    if (!user || user.role === 'teacher' || !progress.rollNumber) return;
    try {
      const leiResult = await calculateLEI(progress);
      
      await fetch('/api/student/lei', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          rollNumber: progress.rollNumber,
          studentName: progress.name,
          grade: progress.grade,
          lei: leiResult.score,
          leiCategory: leiResult.category,
          leiInsight: leiResult.insight
        })
      });
    } catch (error) {
      console.error("Failed to refresh stats:", error);
    }
  };

  React.useEffect(() => {
    if (user?.role !== 'teacher' && progress.rollNumber) {
      const updateLEIOnServer = async () => {
        const leiResult = await calculateLEI(progress);
        
        // Update LEI
        await fetch('/api/student/lei', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            rollNumber: progress.rollNumber,
            studentName: progress.name,
            grade: progress.grade,
            lei: leiResult.score,
            leiCategory: leiResult.category,
            leiInsight: leiResult.insight
          })
        });
      };
      
      const interval = setInterval(updateLEIOnServer, 300000); // Every 5 minutes
      updateLEIOnServer(); // Initial update
      
      return () => clearInterval(interval);
    }
  }, [user, progress.rollNumber, progress.completedTracks, progress.totalAttempts, progress.timeSpent, progress.streak]);

  React.useEffect(() => {
    localStorage.setItem('rs_learning_progress', JSON.stringify(progress));
  }, [progress]);

  React.useEffect(() => {
    if (user) {
      localStorage.setItem('rs_learning_user', JSON.stringify(user));
    } else {
      localStorage.removeItem('rs_learning_user');
    }
  }, [user]);

  // Streak Logic
  React.useEffect(() => {
    if (progress.name && view === 'dashboard') {
      const today = new Date().toISOString().split('T')[0];
      const lastDate = progress.lastActivityDate ? progress.lastActivityDate.split('T')[0] : null;

      if (lastDate !== today) {
        let newStreak = progress.streak;
        if (lastDate) {
          const yesterday = new Date();
          yesterday.setDate(yesterday.getDate() - 1);
          const yesterdayStr = yesterday.toISOString().split('T')[0];
          
          if (lastDate === yesterdayStr) {
            newStreak += 1;
          } else {
            newStreak = 1;
          }
        } else {
          newStreak = 1;
        }

        setProgress(prev => ({
          ...prev,
          streak: newStreak,
          lastActivityDate: new Date().toISOString()
        }));

        // Check Consistency Badge
        if (newStreak >= 3 && !progress.badges.includes('consistency')) {
          unlockBadge('consistency');
        }
      }
    }
  }, [view]);

  const unlockBadge = (badgeId: string) => {
    if (progress.badges.includes(badgeId)) return;
    const badge = BADGES.find(b => b.id === badgeId);
    if (badge) {
      setNewBadge(badge);
      setProgress(prev => ({
        ...prev,
        badges: [...prev.badges, badgeId],
        xp: prev.xp + 100 // Bonus XP for badge
      }));
      confetti({
        particleCount: 150,
        spread: 100,
        origin: { y: 0.3 },
        colors: ['#0b8c9f', '#ff7a00', '#ffffff']
      });
    }
  };

  const startChallenge = (level: LevelId, track: TrackId) => {
    if (!progress.language) {
      setShowLanguageSelector(true);
      return;
    }
    const bank = QUESTION_BANK[level][progress.language][track];
    
    // Filter out already answered questions for this session
    // But ensure we have at least some questions if all are answered (reset for new cycle)
    let availableQuestions = bank.filter(q => !progress.answeredQuestionIds.includes(q.id));
    
    if (availableQuestions.length === 0) {
      // Reset answered questions for this specific track if all are done
      availableQuestions = [...bank];
      setProgress(prev => ({
        ...prev,
        answeredQuestionIds: prev.answeredQuestionIds.filter(id => !bank.some(bq => bq.id === id))
      }));
    }

    // Shuffle and pick the required number of questions
    const shuffled = [...availableQuestions].sort(() => Math.random() - 0.5);
    setQuestions(shuffled);
    setCurrentQuestionIndex(0);
    setActiveLevel(level);
    setActiveTrack(track);
    setView('challenge');
    setIsAnswered(false);
    setSelectedOption(null);
    setShowHint(false);
    setWrongAttempts(0);
    
    // Effort Tracking
    setTrackStartTime(Date.now());
    setTrackAttempts(0);
    setTrackHintsUsed(0);
  };

  const setLanguage = (lang: any) => {
    setProgress(prev => ({ ...prev, language: lang }));
    setShowLanguageSelector(false);
  };

  const handleAnswer = (optionIndex: number) => {
    if (isAnswered) return;
    
    setTrackAttempts(prev => prev + 1);
    setSelectedOption(optionIndex);
    const isCorrect = optionIndex === questions[currentQuestionIndex].correctAnswer;
    
    if (isCorrect) {
      setIsAnswered(true);
      const xpGain = activeTrack === 'practice' ? 10 : activeTrack === 'reinforcement' ? 20 : 30;
      
      setProgress(prev => {
        const newSolved = prev.questionsSolved + 1;
        if (newSolved === 1 && !prev.badges.includes('starter')) {
          setTimeout(() => unlockBadge('starter'), 500);
        }
        
        // Update Effort Level
        let newEffortLevel = prev.effortLevel;
        if (prev.questionsSolved > 50) newEffortLevel = 'Advanced';
        else if (prev.questionsSolved > 20) newEffortLevel = 'Consistent';
        else if (prev.questionsSolved > 5) newEffortLevel = 'Active';

        return { 
          ...prev, 
          xp: prev.xp + xpGain,
          questionsSolved: newSolved,
          totalAttempts: prev.totalAttempts + 1,
          effortLevel: newEffortLevel as EffortLevel,
          answeredQuestionIds: [...prev.answeredQuestionIds, questions[currentQuestionIndex].id]
        };
      });

      confetti({
        particleCount: 40,
        spread: 50,
        origin: { y: 0.8 },
        colors: ['#0b8c9f', '#ff7a00']
      });
    } else {
      setWrongAttempts(prev => prev + 1);
    }
  };

  const nextQuestion = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(prev => prev + 1);
      setIsAnswered(false);
      setSelectedOption(null);
      setShowHint(false);
      setWrongAttempts(0);
    } else {
      // Track Completed
      const track = TRACKS.find(t => t.id === activeTrack);
      if (track?.codingChallenge) {
        setCode(track.codingChallenge.starterCode);
        setEvaluationResult(null);
        setView('coding');
        return;
      }
      completeTrack();
    }
  };

  const completeTrack = () => {
    const trackKey = `${activeLevel}-${progress.language}-${activeTrack}`;
    const bonusXp = activeTrack === 'basics' ? 50 : activeTrack === 'practice' ? 100 : activeTrack === 'reinforcement' ? 200 : 300;
    
    const timeSpentOnTrack = trackStartTime ? Math.round((Date.now() - trackStartTime) / 60000) : 0;

    setProgress(prev => {
      const newCompletedTracks = { ...prev.completedTracks, [trackKey]: true };
      
      // Badge Logic
      if (activeTrack === 'basics' && !prev.badges.includes('starter')) {
        setTimeout(() => unlockBadge('starter'), 500);
      } else if (activeTrack === 'practice' && !prev.badges.includes('practice_master')) {
        setTimeout(() => unlockBadge('practice_master'), 500);
      } else if (activeTrack === 'reinforcement' && !prev.badges.includes('logic_builder')) {
        setTimeout(() => unlockBadge('logic_builder'), 500);
      } else if (activeTrack === 'final' && !prev.badges.includes('final_challenger')) {
        setTimeout(() => unlockBadge('final_challenger'), 500);
      }

      // Code Champion Logic
      const allTracksInLevel = TRACKS.every(t => newCompletedTracks[`${activeLevel}-${progress.language}-${t.id}`]);
      if (allTracksInLevel && !prev.badges.includes(`level_${activeLevel}_complete`)) {
        setTimeout(() => unlockBadge('code_champion'), 1000);
      }

      return {
        ...prev,
        completedTracks: newCompletedTracks,
        xp: prev.xp + bonusXp,
        timeSpent: prev.timeSpent + timeSpentOnTrack,
        totalAttempts: prev.totalAttempts + trackAttempts,
        hintsUsed: prev.hintsUsed + trackHintsUsed,
        retries: prev.retries + trackRetries,
        activityLog: [...prev.activityLog, { date: new Date().toISOString(), action: `Completed ${activeTrack} track in Level ${activeLevel}` }]
      };
    });

    if (activeTrack === 'final') {
      const project = PROJECTS.find(p => p.level === activeLevel);
      if (project) {
        setActiveProject(project);
        setView('project-intro');
      } else {
        setView('dashboard');
      }
    } else {
      setView('dashboard');
    }

    confetti({
      particleCount: 200,
      spread: 120,
      origin: { y: 0.6 },
      colors: ['#0b8c9f', '#ff7a00', '#ffffff', '#ffd700']
    });
  };

  const evaluateCode = async () => {
    setIsEvaluating(true);
    setEvaluationResult(null);
    setErrorAnalysis(null);
    
    const track = TRACKS.find(t => t.id === activeTrack);
    if (!track?.codingChallenge) {
      setIsEvaluating(false);
      return;
    }

    setTrackAttempts(prev => prev + 1);

    try {
      // Basic auto-evaluation using Function constructor
      const userFn = new Function(`return ${code}`)();
      
      let allPassed = true;
      let failedTest = null;
      for (const test of track.codingChallenge.testCases) {
        const result = userFn(...test.input);
        if (JSON.stringify(result) !== JSON.stringify(test.expected)) {
          allPassed = false;
          failedTest = test;
          break;
        }
      }

      if (allPassed) {
        setEvaluationResult({ success: true, message: "All test cases passed! Great job." });
        setTimeout(() => setView('submission'), 1500);
      } else {
        setEvaluationResult({ success: false, message: "Some test cases failed. Analyzing your code..." });
        setTrackRetries(prev => prev + 1);
        
        // Call AI for error analysis
        const analysis = await analyzeError(
          code,
          JSON.stringify(failedTest?.expected),
          JSON.stringify(userFn(...(failedTest?.input || []))),
          progress.language || 'JavaScript',
          track.codingChallenge.description
        );
        setErrorAnalysis(analysis);
      }
    } catch (error) {
      setEvaluationResult({ success: false, message: "Error in code. Analyzing the issue..." });
      setTrackRetries(prev => prev + 1);
      
      try {
        const analysis = await analyzeError(
          code,
          "Valid execution",
          (error as Error).message,
          progress.language || 'JavaScript',
          track.codingChallenge.description
        );
        setErrorAnalysis(analysis);
      } catch (aiError) {
        setEvaluationResult({ success: false, message: "Error in code: " + (error as Error).message });
      }
    } finally {
      setIsEvaluating(false);
    }
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoginError('');
    try {
      const res = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(loginForm)
      });
      if (res.ok) {
        const userData = await res.json();
        setUser(userData);
        setView(userData.role === 'teacher' ? 'teacher' : 'dashboard');
      } else {
        setLoginError('Invalid username or password');
      }
    } catch (error) {
      setLoginError('Server error. Please try again.');
    }
  };

  const handleDocSubmit = async () => {
    setIsSubmitting(true);
    const timeSpentOnTrack = trackStartTime ? Math.round((Date.now() - trackStartTime) / 60000) : 0;

    try {
      const completedTracksCount = Object.values(progress.completedTracks).filter(Boolean).length;
      const completionRate = Math.round((completedTracksCount / 12) * 100);
      
      const updatedProgress = {
        ...progress,
        timeSpent: progress.timeSpent + timeSpentOnTrack,
        totalAttempts: progress.totalAttempts + trackAttempts,
        hintsUsed: progress.hintsUsed + trackHintsUsed,
        retries: progress.retries + trackRetries,
      };
      
      const leiResult = await calculateLEI(updatedProgress);

      // Plagiarism Detection
      let plagiarismReport = null;
      try {
        const submissionsRes = await fetch('/api/submissions');
        if (submissionsRes.ok) {
          const allSubmissions = await submissionsRes.json();
          const relevantSubmissions = allSubmissions.filter((s: any) => 
            s.track === activeTrack && 
            s.level === activeLevel && 
            s.rollNumber !== progress.rollNumber &&
            s.code
          );
          
          const trackData = TRACKS.find(t => t.id === activeTrack);
          const problemStatement = trackData?.codingChallenge?.description || trackData?.description || "Coding challenge";
          
          plagiarismReport = await detectPlagiarism(
            code,
            relevantSubmissions,
            problemStatement,
            progress.language || 'JavaScript'
          );
        }
      } catch (err) {
        console.error("Plagiarism check failed:", err);
      }

      const submissionData = {
        studentName: progress.name,
        rollNumber: progress.rollNumber,
        grade: progress.grade,
        level: activeLevel,
        track: activeTrack,
        language: progress.language,
        code: code,
        aiFeedback: "Great effort! Your documentation shows a good understanding of the concepts. Keep exploring more complex logic.",
        docText: docText,
        status: 'pending',
        timeSpent: timeSpentOnTrack,
        attempts: trackAttempts,
        hintsUsed: trackHintsUsed,
        retries: trackRetries,
        streak: progress.streak,
        completionRate: completionRate,
        lei: leiResult.score,
        leiCategory: leiResult.category,
        leiInsight: leiResult.insight,
        vivaSummary: progress.vivaSummary,
        plagiarismReport,
        documentationMarks: 0,
        vivaScore: 0
      };

      const res = await fetch('/api/submissions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submissionData)
      });

      if (res.ok) {
        setIsSubmitting(false);
        setDocText('');
        completeTrack();
      }
    } catch (error) {
      console.error('Submission failed:', error);
      setIsSubmitting(false);
    }
  };

  const handleProjectSubmit = async (projectId: string) => {
    setIsEvaluating(true);
    setEvaluationResult(null);
    setErrorAnalysis(null);
    setCurrentHintLevel(0);

    const project = progress.assignedProject || PROJECTS.find(p => p.id === projectId);
    if (!project) return;

    setTrackAttempts(prev => prev + 1);

    try {
      // Extract function name from project input format (e.g., "calculate(10, 0, '/')")
      const fnName = project.inputFormat.split('(')[0];
      
      // Basic auto-evaluation using Function constructor
      // We wrap the code and return the expected function by name
      const userFn = new Function(`
        ${code}
        if (typeof ${fnName} !== 'undefined') return ${fnName};
        return null;
      `)();
      
      if (typeof userFn !== 'function') {
        throw new Error(`Function '${fnName}' not found. Ensure you have defined 'function ${fnName}(...) { ... }' without using 'export' or 'import' statements.`);
      }
      
      let allPassed = true;
      let failedTest = null;
      for (const test of project.testCases) {
        const result = userFn(...test.input);
        if (JSON.stringify(result) !== JSON.stringify(test.expected)) {
          allPassed = false;
          failedTest = { input: test.input, expected: test.expected, actual: result };
          break;
        }
      }

      if (allPassed) {
        setEvaluationResult({ success: true, message: "Project Evaluation Successful! All test cases passed." });
        setProgress(prev => ({ ...prev, projectStatus: 'documentation' }));
        
        setTimeout(() => {
          setView('project-submission');
          setEvaluationResult(null);
        }, 2000);
      } else {
        setEvaluationResult({ success: false, message: "Some test cases failed. Analyzing your code..." });
        setTrackRetries(prev => prev + 1);

        // Call AI for error analysis
        const analysis = await analyzeError(
          code,
          JSON.stringify(failedTest?.expected),
          JSON.stringify(failedTest?.actual),
          progress.language || 'JavaScript',
          project.description
        );
        setErrorAnalysis(analysis);
      }
    } catch (error) {
      setEvaluationResult({ success: false, message: "Error in code. Analyzing the issue..." });
      setTrackRetries(prev => prev + 1);
      
      try {
        const analysis = await analyzeError(
          code,
          "Valid execution",
          (error as Error).message,
          progress.language || 'JavaScript',
          project.description
        );
        setErrorAnalysis(analysis);
      } catch (aiError) {
        setEvaluationResult({ success: false, message: "Error in code: " + (error as Error).message });
      }
    } finally {
      setIsEvaluating(false);
    }
  };

  const handleProjectDocSubmit = async () => {
    if (!activeProject) return;
    setIsSubmitting(true);
    const timeSpentOnTrack = trackStartTime ? Math.round((Date.now() - trackStartTime) / 60000) : 0;

    try {
      const docText = `Objective: ${docContent.objective}\nConcepts Used: ${docContent.conceptsUsed}\nHow It Works: ${docContent.howItWorks}\nWhat I Learned: ${docContent.whatILearned}`;
      
      const completedTracksCount = Object.values(progress.completedTracks).filter(Boolean).length;
      const completionRate = Math.round((completedTracksCount / 12) * 100);
      
      const updatedProgress = {
        ...progress,
        timeSpent: progress.timeSpent + timeSpentOnTrack,
        totalAttempts: progress.totalAttempts + trackAttempts,
        hintsUsed: progress.hintsUsed + trackHintsUsed,
        retries: progress.retries + trackRetries,
      };
      
      const leiResult = await calculateLEI(updatedProgress);

      // AI Documentation & Code Analysis
      const analysis = await analyzeDocumentation({ code, docText }, progress.language || 'JavaScript');

      // Plagiarism Detection
      let plagiarismReport = null;
      try {
        const submissionsRes = await fetch('/api/submissions');
        if (submissionsRes.ok) {
          const allSubmissions = await submissionsRes.json();
          const relevantSubmissions = allSubmissions.filter((s: any) => 
            s.track === 'project' && 
            s.level === activeLevel && 
            s.rollNumber !== progress.rollNumber &&
            s.code
          );
          
          plagiarismReport = await detectPlagiarism(
            code,
            relevantSubmissions,
            activeProject.description,
            progress.language || 'JavaScript'
          );
        }
      } catch (err) {
        console.error("Plagiarism check failed:", err);
      }

      const submissionData = {
        studentName: progress.name,
        rollNumber: progress.rollNumber,
        grade: progress.grade,
        schoolName: progress.schoolName,
        principalName: progress.principalName,
        level: activeLevel,
        track: 'project',
        language: progress.language,
        code: code,
        aiFeedback: analysis?.aiFeedback || "Excellent work on the project! Your code passed all test cases, and your documentation provides clear insights into your implementation.",
        docText: docText,
        status: 'pending',
        timeSpent: timeSpentOnTrack,
        attempts: trackAttempts,
        hintsUsed: trackHintsUsed,
        retries: trackRetries,
        streak: progress.streak,
        completionRate: completionRate,
        lei: leiResult.score,
        leiCategory: leiResult.category,
        leiInsight: leiResult.insight,
        vivaSummary: progress.vivaSummary,
        plagiarismReport,
        marks: analysis?.marks || null,
        documentationMarks: analysis?.marks?.documentation?.total || 0,
        vivaScore: 0,
        teacherVivaMarks: 0
      };

      const res = await fetch('/api/submissions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(submissionData)
      });

      if (res.ok) {
        setIsSubmitting(false);
        setDocText('');
        setDocContent({ objective: '', conceptsUsed: '', howItWorks: '', whatILearned: '' });
        
        setProgress(prev => {
          const newProjects = [...new Set([...prev.completedProjects, activeProject.id])];
          return {
            ...prev,
            completedProjects: newProjects,
            projectStatus: 'completed',
            xp: prev.xp + 500
          };
        });

        if (!progress.badges.includes('project_builder')) {
          unlockBadge('project_builder');
        }

        confetti({
          particleCount: 150,
          spread: 100,
          origin: { y: 0.6 },
          colors: ['#0b8c9f', '#ff7a00']
        });
        
        setView('dashboard');
      }
    } catch (error) {
      console.error('Project submission failed:', error);
      setIsSubmitting(false);
    }
  };

  const generateUniqueProject = async () => {
  if (!progress.language) return;
  setIsGeneratingProject(true);

  try {
    // ✅ TEMP: Direct fallback (NO AI)
    const fallback = PROJECTS
  .filter(p => 
    p.level === activeLevel && 
    Number(progress.grade) >= (p.minClass || 0)
  )[0];
    setActiveProject(fallback);
    setCode(fallback.starterCode);
    setProgress(prev => ({
      ...prev,
      assignedProject: fallback,
      projectStatus: 'coding'
    }));
    setView('project');

  } catch (error) {
    console.error('Project generation failed:', error);
  } finally {
    setIsGeneratingProject(false);
  }
};

  const downloadCert = (level: LevelId, track: string, projectName?: string) => {
    const skills = level === 1 
      ? ['Basic Syntax', 'Variables', 'Print Statements']
      : level === 2 
      ? ['Loops', 'Conditions', 'Arrays', 'Logic Building']
      : ['Advanced Algorithms', 'Problem Solving', 'Project Development'];
    
    generateCertificate(
      progress.name,
      level,
      track,
      skills,
      level === 3,
      progress.grade,
      progress.rollNumber,
      projectName,
      progress.effortLevel,
      progress.schoolName,
      progress.principalName
    );
  };

  if (view === 'onboarding') {
    return (
      <div className="min-h-screen bg-dark-bg flex items-center justify-center p-6">
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="max-w-md w-full bg-dark-card rounded-3xl p-8 shadow-2xl border border-dark-border"
        >
          <div className="flex justify-center mb-6">
            <div className="w-24 h-24 bg-white rounded-2xl flex items-center justify-center shadow-inner p-2 overflow-hidden">
              <img 
                src={logo}
                alt="Logo" 
                className="w-full h-full object-contain"
                onError={(e) => {
                  // Fallback if the URL is still not working
                  (e.target as HTMLImageElement).src = "https://api.dicebear.com/7.x/bottts/svg?seed=RS";
                }}
              />
            </div>
          </div>
          <h1 className="text-3xl font-bold text-center text-white mb-2">RS Learning Lab</h1>
          <p className="text-center text-slate-400 mb-8 italic">"Learning coding, one step at a time."</p>
          
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-1">Student Name</label>
              <input 
                type="text" 
                value={progress.name}
                onChange={(e) => setProgress(prev => ({ ...prev, name: e.target.value }))}
                placeholder="Enter full name"
                className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] focus:border-transparent outline-none transition-all"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-1">Class / Grade</label>
              <input 
                type="text" 
                value={progress.grade || ''}
                onChange={(e) => setProgress(prev => ({ ...prev, grade: e.target.value }))}
                placeholder="e.g. Class 10"
                className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] focus:border-transparent outline-none transition-all"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-1">Roll Number</label>
              <input 
                type="text" 
                value={progress.rollNumber || ''}
                onChange={(e) => setProgress(prev => ({ ...prev, rollNumber: e.target.value }))}
                placeholder="Enter roll number"
                className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] focus:border-transparent outline-none transition-all"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-1">School Name (Optional)</label>
              <input 
                type="text" 
                value={progress.schoolName || ''}
                onChange={(e) => setProgress(prev => ({ ...prev, schoolName: e.target.value }))}
                placeholder="Enter school name"
                className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] focus:border-transparent outline-none transition-all"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-1">Principal Name (Optional)</label>
              <input 
                type="text" 
                value={progress.principalName || ''}
                onChange={(e) => setProgress(prev => ({ ...prev, principalName: e.target.value }))}
                placeholder="Enter principal name"
                className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] focus:border-transparent outline-none transition-all"
              />
            </div>
          <div className="pt-2">
            <p className="text-[10px] text-slate-500 text-center mb-4">
              Data Policy: Collected for educational purposes only.
            </p>
            <button 
              disabled={!progress.name || !progress.grade || !progress.rollNumber}
              onClick={() => {
                setUser({ id: progress.rollNumber, username: progress.name, role: 'student', name: progress.name });
                setView('dashboard');
              }}
              className="w-full bg-[#0b8c9f] text-white py-4 rounded-xl font-bold hover:bg-[#097a8a] transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 shadow-lg shadow-[#0b8c9f]/20"
            >
              Start Journey <ArrowRight size={20} />
            </button>
            {!user && (
              <button 
                onClick={() => setView('login')}
                className="w-full mt-4 text-slate-500 text-sm font-bold hover:text-white transition-colors"
              >
                Teacher Login
              </button>
            )}
          </div>
          </div>
          <div className="mt-8 pt-6 border-t border-dark-border text-center">
            <p className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Powered by RS Learning Lab</p>
            <p className="text-[10px] text-slate-400">Founder: Gokula Krishnan</p>
          </div>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-dark-bg text-slate-50 font-sans">
      {/* Badge Notification */}
      <AnimatePresence>
        {newBadge && (
          <motion.div 
            initial={{ opacity: 0, y: -100 }}
            animate={{ opacity: 1, y: 20 }}
            exit={{ opacity: 0, y: -100 }}
            className="fixed top-0 left-1/2 -translate-x-1/2 z-[100] w-full max-w-sm px-4"
          >
            <div className="bg-dark-card rounded-2xl shadow-2xl border-2 border-[#ff7a00] p-6 flex items-center gap-4 relative overflow-hidden">
              <div className="absolute top-0 left-0 w-full h-1 bg-[#ff7a00]" />
              <div className={cn("w-16 h-16 rounded-xl flex items-center justify-center text-white shrink-0 shadow-lg", newBadge.color)}>
                {React.createElement(ICON_MAP[newBadge.icon] || Star, { size: 32 })}
              </div>
              <div className="flex-1">
                <div className="text-[#ff7a00] font-black text-xs uppercase tracking-widest mb-1">New Badge Earned!</div>
                <h4 className="font-bold text-lg leading-tight text-white">{newBadge.name}</h4>
                <p className="text-xs text-slate-400 mt-1">{newBadge.description}</p>
              </div>
              <button onClick={() => setNewBadge(null)} className="p-1 hover:bg-slate-800 rounded-lg text-slate-500">
                <X size={20} />
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Header */}
      <header className="bg-dark-card/80 backdrop-blur-md border-b border-dark-border sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 h-20 flex items-center justify-between">
          <div className="flex items-center gap-3 cursor-pointer" onClick={() => setView('dashboard')}>
            <div className="bg-white p-1 rounded-lg">
              <img 
                src={logo}
                alt="Logo" 
                className="h-8"
                onError={(e) => {
                  (e.target as HTMLImageElement).src = "https://api.dicebear.com/7.x/bottts/svg?seed=RS";
                }}
              />
            </div>
            <span className="font-bold text-xl tracking-tight hidden sm:block text-white">RS Learning Lab</span>
          </div>

          <div className="flex items-center gap-4 sm:gap-6">
            {user?.role === 'student' && (
              <button 
                onClick={() => setView('leaderboard')}
                className="flex items-center gap-2 text-slate-300 hover:text-[#ff7a00] transition-colors"
              >
                <Trophy size={18} />
                <span className="font-bold text-sm hidden sm:inline">Leaderboard</span>
              </button>
            )}

            {user?.role === 'teacher' && (
              <div className="flex items-center gap-4 sm:gap-6">
                <button 
                  onClick={() => setView('leaderboard')}
                  className="flex items-center gap-2 text-slate-300 hover:text-[#ff7a00] transition-colors"
                >
                  <Trophy size={18} />
                  <span className="font-bold text-sm hidden sm:inline">Leaderboard</span>
                </button>
                <button 
                  onClick={() => setView('teacher')}
                  className="flex items-center gap-2 text-slate-300 hover:text-[#0b8c9f] transition-colors"
                >
                  <LayoutDashboard size={18} />
                  <span className="font-bold text-sm">Teacher Panel</span>
                </button>
              </div>
            )}

            <div className="hidden md:flex items-center gap-2 bg-orange-500/10 px-3 py-1.5 rounded-full border border-orange-500/20">
              <Flame className="text-[#ff7a00]" size={18} fill="#ff7a00" />
              <span className="font-bold text-[#ff7a00]">{progress.streak} Day Streak</span>
            </div>

            <div className="flex items-center gap-2 sm:gap-4 bg-slate-800/50 px-3 py-1.5 sm:px-4 sm:py-2 rounded-full border border-dark-border">
              <div className="flex items-center gap-2">
                <Star className="text-[#ff7a00]" size={18} fill="#ff7a00" />
                <span className="font-bold text-[#ff7a00]">{progress.xp} XP</span>
              </div>
              <div className="w-px h-4 bg-slate-700" />
              <button onClick={() => setView('badges')} className="flex items-center gap-2 hover:text-[#0b8c9f] transition-colors">
                <Award size={18} className="text-[#0b8c9f]" />
                <span className="font-bold text-sm hidden sm:inline text-slate-300">{progress.badges.length} Badges</span>
              </button>
            </div>
            
            <button 
              onClick={() => {
                setUser(null);
                setView('onboarding');
              }}
              className="p-2 text-slate-500 hover:text-red-500 transition-colors"
            >
              <LogOut size={20} />
            </button>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-10">
        <AnimatePresence mode="wait">
          {view === 'login' && (
            <motion.div 
              key="login"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 1.05 }}
              className="max-w-md mx-auto"
            >
              <div className="bg-dark-card rounded-3xl p-8 shadow-2xl border border-dark-border">
                <div className="flex justify-center mb-6">
                  <div className="w-16 h-16 bg-[#0b8c9f]/10 rounded-2xl flex items-center justify-center text-[#0b8c9f]">
                    <Lock size={32} />
                  </div>
                </div>
                <h2 className="text-2xl font-bold text-center text-white mb-2">Teacher Login</h2>
                <p className="text-center text-slate-400 mb-8">Access the evaluation dashboard</p>

                <form onSubmit={handleLogin} className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-slate-300 mb-1">Username</label>
                    <input 
                      type="text"
                      required
                      value={loginForm.username}
                      onChange={(e) => setLoginForm(prev => ({ ...prev, username: e.target.value }))}
                      className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-300 mb-1">Password</label>
                    <input 
                      type="password"
                      required
                      value={loginForm.password}
                      onChange={(e) => setLoginForm(prev => ({ ...prev, password: e.target.value }))}
                      className="w-full px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none"
                    />
                  </div>
                  {loginError && <p className="text-red-500 text-xs font-bold">{loginError}</p>}
                  <button 
                    type="submit"
                    className="w-full bg-[#0b8c9f] text-white py-4 rounded-xl font-bold hover:bg-[#097a8a] transition-all shadow-lg shadow-[#0b8c9f]/20"
                  >
                    Login to Dashboard
                  </button>
                  <button 
                    type="button"
                    onClick={() => setView('onboarding')}
                    className="w-full mt-2 text-slate-500 text-sm hover:text-white transition-colors"
                  >
                    Back to Student Portal
                  </button>
                </form>
              </div>
            </motion.div>
          )}

          {view === 'teacher' && user?.role === 'teacher' && (
            <motion.div 
              key="teacher"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
            >
              <TeacherDashboard user={user} onLogout={() => { setUser(null); setView('onboarding'); }} />
            </motion.div>
          )}

          {view === 'leaderboard' && (
            <motion.div 
              key="leaderboard"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
            >
              <Leaderboard user={user} />
              <div className="mt-12 flex justify-center">
                <button 
                  onClick={() => setView(user?.role === 'teacher' ? 'teacher' : 'dashboard')}
                  className="bg-dark-card px-8 py-3 rounded-xl font-bold border border-dark-border hover:border-[#0b8c9f] transition-all text-white flex items-center gap-2"
                >
                  <ArrowRight size={20} className="rotate-180" /> Back to {user?.role === 'teacher' ? 'Teacher Panel' : 'Dashboard'}
                </button>
              </div>
            </motion.div>
          )}

          {showLanguageSelector && (
            <div className="fixed inset-0 bg-dark-bg/80 backdrop-blur-md z-[100] flex items-center justify-center p-6">
              <motion.div 
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                className="bg-dark-card rounded-3xl p-10 border border-dark-border max-w-xl w-full shadow-2xl"
              >
                <h3 className="text-3xl font-black text-white mb-4 text-center">Select Your Path 🚀</h3>
                <p className="text-slate-400 text-center mb-8">Choose a programming language to begin your learning journey.</p>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {['C', 'C++', 'Java', 'Python', 'JavaScript'].map((lang) => (
                    <button
                      key={lang}
                      onClick={() => setLanguage(lang as any)}
                      className="p-6 rounded-2xl bg-slate-800/50 border border-dark-border text-white font-bold hover:border-[#0b8c9f] hover:bg-slate-800 transition-all flex items-center justify-between group"
                    >
                      <span>{lang}</span>
                      <ArrowRight size={20} className="opacity-0 group-hover:opacity-100 transition-all" />
                    </button>
                  ))}
                </div>
                
                <button 
                  onClick={() => setShowLanguageSelector(false)}
                  className="mt-8 w-full text-slate-500 text-sm font-bold hover:text-white transition-colors"
                >
                  Cancel
                </button>
              </motion.div>
            </div>
          )}

          {view === 'dashboard' && (
            <motion.div 
              key="dashboard"
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: 20 }}
              className="space-y-12"
            >
              {vivaRequestedSubmissions.length > 0 && (
                <motion.div 
                  initial={{ opacity: 0, y: -20 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="bg-yellow-500/10 border border-yellow-500/20 rounded-3xl p-6 mb-8 flex flex-col sm:flex-row items-center justify-between gap-6"
                >
                  <div className="flex items-center gap-4 text-center sm:text-left">
                    <div className="w-12 h-12 bg-yellow-500/20 rounded-2xl flex items-center justify-center text-yellow-500 flex-shrink-0 mx-auto sm:mx-0">
                      <AlertTriangle size={24} />
                    </div>
                    <div>
                      <h4 className="text-lg font-black text-white">Viva Explanation Requested</h4>
                      <p className="text-slate-400 text-sm">Your teacher has requested a viva explanation for your recent submission. Practice explaining your code!</p>
                    </div>
                  </div>
                  <button 
                    onClick={() => setShowViva(true)}
                    className="bg-yellow-500 hover:bg-yellow-600 text-black px-6 py-3 rounded-2xl font-black transition-all whitespace-nowrap shadow-lg shadow-yellow-500/20"
                  >
                    Start Viva Practice
                  </button>
                </motion.div>
              )}

              {/* Welcome & Effort Stats */}
              <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                <div>
                  <h2 className="text-3xl font-black text-white">Welcome back, {progress.name}! 👋</h2>
                  <p className="text-slate-400 mt-1">You're doing great. Keep up the momentum!</p>
                  <div className="flex items-center gap-3 mt-4">
                    <div className={cn(
                      "px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest border",
                      progress.effortLevel === 'Advanced' ? "bg-purple-500/10 text-purple-400 border-purple-500/20" :
                      progress.effortLevel === 'Consistent' ? "bg-blue-500/10 text-blue-400 border-blue-500/20" :
                      progress.effortLevel === 'Active' ? "bg-green-500/10 text-green-400 border-green-500/20" :
                      "bg-slate-500/10 text-slate-400 border-slate-500/20"
                    )}>
                      {progress.effortLevel} Learner
                    </div>
                    <div className="flex items-center gap-1.5 text-xs text-slate-500 font-bold uppercase tracking-widest">
                      <Clock size={14} /> {progress.timeSpent}m Spent
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-4">
                  {progress.streak > 0 && (
                    <div className="bg-dark-card p-4 rounded-2xl shadow-xl border border-orange-500/20 flex items-center gap-4">
                      <div className="w-12 h-12 bg-orange-500 rounded-xl flex items-center justify-center text-white shadow-lg shadow-orange-500/20">
                        <Flame size={24} fill="white" />
                      </div>
                      <div>
                        <div className="text-xs font-bold text-orange-500 uppercase tracking-widest">Current Streak</div>
                        <div className="text-xl font-black text-white">{progress.streak} Days 🔥</div>
                      </div>
                    </div>
                  )}
                  <div className="bg-dark-card p-4 rounded-2xl shadow-xl border border-[#0b8c9f]/20 flex items-center gap-4">
                    <div className="w-12 h-12 bg-[#0b8c9f] rounded-xl flex items-center justify-center text-white shadow-lg shadow-[#0b8c9f]/20">
                      <Trophy size={24} fill="white" />
                    </div>
                    <div>
                      <div className="text-xs font-bold text-[#0b8c9f] uppercase tracking-widest">Total XP</div>
                      <div className="text-xl font-black text-white">{progress.xp} XP</div>
                    </div>
                  </div>
                </div>
              </div>

              {/* AI Viva Simulator Card - Only shown after documentation submission */}
              {progress.projectStatus === 'completed' && (
                <div className="max-w-md mx-auto w-full">
                  <motion.div 
                    whileHover={{ scale: 1.02 }}
                    className="bg-dark-card rounded-3xl border border-[#0b8c9f]/20 p-8 flex flex-col justify-between relative overflow-hidden group"
                  >
                    <div className="absolute top-0 right-0 w-32 h-32 bg-[#0b8c9f]/5 rounded-full -mr-16 -mt-16 blur-2xl group-hover:bg-[#0b8c9f]/10 transition-all" />
                    <div>
                      <div className="w-12 h-12 bg-[#0b8c9f]/10 rounded-2xl flex items-center justify-center text-[#0b8c9f] mb-6">
                        <MessageSquare size={24} />
                      </div>
                      <h3 className="text-2xl font-black text-white mb-2">AI Viva Simulator</h3>
                      <p className="text-slate-400 text-sm leading-relaxed">
                        Practice explaining your project like a real viva. Build confidence and master your technical communication!
                      </p>
                    </div>
                    <button 
                      onClick={() => setShowViva(true)}
                      className="mt-8 w-full bg-[#0b8c9f] hover:bg-[#0b8c9f]/90 text-white py-4 rounded-2xl font-black shadow-lg shadow-[#0b8c9f]/20 transition-all flex items-center justify-center gap-2"
                    >
                      <Play size={18} fill="white" />
                      Start Viva Practice
                    </button>
                  </motion.div>
                </div>
              )}

              {showViva && (
                <VivaSimulator 
                  progress={progress}
                  level={activeLevel}
                  onComplete={handleVivaComplete}
                  onClose={() => setShowViva(false)}
                />
              )}

              {/* Levels */}
              <div className={cn(
                "grid grid-cols-1 gap-8",
                (() => {
                  const grade = parseGrade(progress.grade);
                  if (grade === 12 || (grade && grade >= 11)) return "md:grid-cols-1 max-w-md mx-auto";
                  if (grade && grade >= 6 && grade <= 8) return "md:grid-cols-1 max-w-md mx-auto";
                  if (grade === 10) return "md:grid-cols-1 max-w-md mx-auto";
                  if (grade === 9) return "md:grid-cols-2 max-w-4xl mx-auto";
                  return "md:grid-cols-3";
                })()
              )}>
                {LEVELS.filter(level => {
                  const grade = parseGrade(progress.grade);
                  if (!grade) return true;
                  if (grade === 12 || grade === 11) return level.id >= 3;
                  if (grade >= 6 && grade <= 8) return level.id === 1;
                  if (grade === 9) return level.id <= 2;
                  if (grade === 10) return level.id === 2;
                  return true;
                }).map((level, index, filteredArray) => {
                  const isFirstVisible = index === 0;
                  const isUnlocked = isFirstVisible || progress.completedTracks[`${level.id - 1}-${progress.language}-final`];
                  const isCompleted = progress.completedTracks[`${level.id}-${progress.language}-final`];
                  
                  // Calculate Level Progress
                  const levelTracks = TRACKS.map(t => `${level.id}-${progress.language}-${t.id}`);
                  const completedCount = levelTracks.filter(t => progress.completedTracks[t]).length;
                  const levelProgress = (completedCount / levelTracks.length) * 100;
                  const isLevelFullyCompleted = completedCount === levelTracks.length;

                  return (
                    <div 
                      key={level.id}
                      className={cn(
                        "bg-dark-card rounded-3xl p-8 border-2 transition-all relative overflow-hidden group",
                        isUnlocked ? "border-dark-border shadow-2xl" : "border-slate-800 opacity-40 grayscale"
                      )}
                    >
                      {isCompleted && (
                        <div className="absolute top-4 right-4 text-[#0b8c9f]">
                          <CheckCircle2 size={24} />
                        </div>
                      )}
                      <div className="mb-6">
                        <span className="text-xs font-bold uppercase tracking-widest text-[#0b8c9f] mb-2 block">
                          {level.subtitle}
                        </span>
                        <h3 className="text-2xl font-bold mb-2 text-white">{level.title}</h3>
                        <p className="text-slate-400 text-sm leading-relaxed mb-4">{level.description}</p>
                        
                        {/* Progress Bar */}
                        <div className="space-y-1.5">
                          <div className="flex justify-between text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                            <span>Progress</span>
                            <span>{Math.round(levelProgress)}%</span>
                          </div>
                          <div className="w-full h-2 bg-slate-800 rounded-full overflow-hidden">
                            <motion.div 
                              initial={{ width: 0 }}
                              animate={{ width: `${levelProgress}%` }}
                              className="h-full bg-[#0b8c9f]"
                            />
                          </div>
                        </div>
                      </div>

                      <div className="space-y-4">
                        {TRACKS.map((track) => {
                          const trackKey = `${level.id}-${progress.language}-${track.id}`;
                          const isTrackCompleted = progress.completedTracks[trackKey];
                          const trackIndex = TRACKS.findIndex(t => t.id === track.id);
                          const prevTrackKey = trackIndex > 0 ? `${level.id}-${progress.language}-${TRACKS[trackIndex - 1].id}` : null;
                          const isTrackUnlocked = isUnlocked && (!prevTrackKey || progress.completedTracks[prevTrackKey]);

                          return (
                            <button
                              key={track.id}
                              disabled={!isTrackUnlocked}
                              onClick={() => startChallenge(level.id as LevelId, track.id as TrackId)}
                              className={cn(
                                "w-full flex items-center justify-between p-4 rounded-2xl border transition-all group/btn",
                                isTrackCompleted 
                                  ? "bg-[#0b8c9f]/10 border-[#0b8c9f]/30 text-[#0b8c9f]" 
                                  : isTrackUnlocked 
                                  ? "bg-slate-800/50 border-dark-border text-slate-300 hover:border-[#0b8c9f] hover:bg-slate-800" 
                                  : "bg-slate-900/50 border-transparent text-slate-600 cursor-not-allowed"
                              )}
                            >
                              <div className="flex items-center gap-3">
                                {isTrackCompleted ? <CheckCircle2 size={20} /> : <BookOpen size={20} />}
                                <div className="text-left">
                                  <div className="font-bold text-sm">
                                    {level.id === 3 && track.id === 'basics' && progress.language 
                                      ? `${progress.language} Basics` 
                                      : track.title}
                                  </div>
                                  <div className="text-[10px] opacity-70 uppercase tracking-wider">
                                    {isTrackCompleted ? 'Completed' : 'Ready to Start'}
                                  </div>
                                </div>
                              </div>
                              {isTrackUnlocked && !isTrackCompleted && <ArrowRight size={18} className="group-hover/btn:translate-x-1 transition-transform" />}
                            </button>
                          );
                        })}
                      </div>

                      {/* Documentation Guide & Mini Projects */}
                      <div className="mt-8 pt-6 border-t border-slate-800 space-y-8">
                        {/* Documentation Guide - Level 3 Only */}
                        {level.id === 3 && (
                          <div className={cn(!isLevelFullyCompleted && "opacity-50 pointer-events-none")}>
                            <div className="flex items-center justify-between mb-3">
                              <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Documentation Guide</div>
                              {!isLevelFullyCompleted && <Lock size={12} className="text-slate-500" />}
                            </div>
                            <div className="bg-[#0b8c9f]/5 border border-[#0b8c9f]/20 rounded-2xl p-4 flex items-center justify-between group">
                              <div className="flex items-center gap-4">
                                <div className="p-3 bg-[#0b8c9f]/10 rounded-xl text-[#0b8c9f]">
                                  <FileText size={24} />
                                </div>
                                <div>
                                  <h4 className="font-bold text-white text-sm">Project Documentation Guide</h4>
                                  <p className="text-[10px] text-slate-400">Includes Front Page, Certificate, Acknowledgement</p>
                                </div>
                              </div>
                              <button 
                                onClick={() => generateProjectDoc(progress.name, progress.grade, progress.rollNumber, 'My Final Project', 'FINAL-PROJ', progress.schoolName, progress.principalName)}
                                className="bg-[#0b8c9f] text-white px-4 py-2 rounded-xl text-xs font-bold flex items-center gap-2 hover:bg-[#097a8a] transition-all shadow-lg shadow-[#0b8c9f]/20"
                              >
                                <Download size={16} /> Download Word Guide
                              </button>
                            </div>
                          </div>
                        )}

                        <div>
                          <div className="flex items-center justify-between mb-3">
                            <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Mini Projects</div>
                            {!isLevelFullyCompleted && (
                              <div className="flex items-center gap-1.5 text-[10px] font-bold text-orange-500 uppercase tracking-wider">
                                <Lock size={10} /> Complete all tracks to unlock
                              </div>
                            )}
                          </div>
                          <div className="grid grid-cols-1 gap-3">
                          {PROJECTS
  .filter(p => 
    p.level === 3
  )
  .map(p => {
                            const isProjDone = progress.completedProjects.includes(p.id);
                            return (
                              <button
                                key={p.id}
                                disabled={!isLevelFullyCompleted}
                                onClick={() => { setActiveProject(p); setView('project-intro'); }}
                                className={cn(
                                  "p-4 rounded-xl border text-sm font-bold transition-all flex items-center justify-between group/proj",
                                  isProjDone 
                                    ? "bg-green-500/10 border-green-500/30 text-green-500" 
                                    : !isLevelFullyCompleted
                                    ? "bg-slate-900/50 border-transparent text-slate-600 cursor-not-allowed"
                                    : "bg-slate-800/50 border-dark-border text-slate-400 hover:border-[#0b8c9f] hover:bg-slate-800"
                                )}
                              >
                                <div className="flex items-center gap-3">
                                  <Code2 size={18} />
                                  <span>{p.title}</span>
                                </div>
                                {isProjDone ? (
                                  <CheckCircle2 size={16} />
                                ) : !isLevelFullyCompleted ? (
                                  <Lock size={14} />
                                ) : (
                                  <ArrowRight size={16} className="opacity-0 group-hover/proj:opacity-100 transition-opacity" />
                                )}
                              </button>
                            );
                          })}
                          </div>
                        </div>
                        {isLevelFullyCompleted && progress.completedProjects.some(pid => PROJECTS.find(p => p.id === pid)?.level === level.id) && (
                          <button 
                            onClick={() => downloadCert(level.id as LevelId, 'Final Track', PROJECTS.find(p => progress.completedProjects.includes(p.id) && p.level === level.id)?.title)}
                            className="mt-6 w-full bg-[#ff7a00] text-white py-4 rounded-xl font-bold flex items-center justify-center gap-2 hover:bg-[#e66e00] transition-colors shadow-lg shadow-[#ff7a00]/20"
                          >
                            <Award size={20} /> {level.id === 3 ? 'Premium Certificate' : 'Download Certificate'}
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Daily Goal & Recent Activity */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                <div className="md:col-span-1 bg-dark-card rounded-3xl p-8 border border-dark-border shadow-2xl">
                  <div className="flex items-center justify-between mb-6">
                    <h3 className="text-lg font-bold text-white flex items-center gap-2">
                      <Target size={20} className="text-[#0b8c9f]" /> Daily Goal
                    </h3>
                    <div className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                      {Math.min(progress.questionsSolved % 5, 5)}/5 Solved
                    </div>
                  </div>
                  <div className="space-y-6">
                    <div className="w-full h-3 bg-slate-800 rounded-full overflow-hidden">
                      <motion.div 
                        initial={{ width: 0 }}
                        animate={{ width: `${(Math.min(progress.questionsSolved % 5, 5) / 5) * 100}%` }}
                        className="h-full bg-gradient-to-r from-[#0b8c9f] to-teal-400"
                      />
                    </div>
                    <p className="text-xs text-slate-400 leading-relaxed">
                      Complete 5 questions today to earn a <span className="text-white font-bold">Consistency Bonus</span>!
                    </p>
                    <div className="pt-4 border-t border-slate-800">
                      <div className="flex items-center justify-between text-xs font-bold text-slate-500 uppercase tracking-widest mb-3">
                        Next Milestone
                      </div>
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-slate-800 rounded-lg flex items-center justify-center text-slate-500">
                          <Award size={20} />
                        </div>
                        <div>
                          <div className="text-sm font-bold text-white">Logic Builder</div>
                          <div className="text-[10px] text-slate-500 uppercase tracking-widest">Complete Level 1</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="md:col-span-2 bg-dark-card rounded-3xl p-8 border border-dark-border shadow-2xl">
                  <div className="flex items-center justify-between mb-6">
                    <h3 className="text-lg font-bold text-white flex items-center gap-2">
                      <Clock size={20} className="text-purple-500" /> Recent Activity
                    </h3>
                    <button className="text-[10px] font-bold text-[#0b8c9f] uppercase tracking-widest hover:underline">
                      View All
                    </button>
                  </div>
                  <div className="space-y-4">
                    {progress.activityLog.length > 0 ? (
                      progress.activityLog.slice(-4).reverse().map((log, idx) => (
                        <div key={idx} className="flex items-center justify-between p-4 rounded-2xl bg-slate-800/30 border border-slate-800/50 group hover:border-[#0b8c9f]/30 transition-all">
                          <div className="flex items-center gap-4">
                            <div className="w-10 h-10 rounded-xl bg-slate-800 flex items-center justify-center text-slate-400 group-hover:text-[#0b8c9f] transition-colors">
                              <Play size={18} />
                            </div>
                            <div>
                              <div className="text-sm font-bold text-white">{log.action}</div>
                              <div className="text-[10px] text-slate-500 uppercase tracking-widest">
                                {new Date(log.date).toLocaleDateString()} at {new Date(log.date).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                              </div>
                            </div>
                          </div>
                          <div className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">
                            {progress.language}
                          </div>
                        </div>
                      ))
                    ) : (
                      <div className="py-12 text-center">
                        <div className="w-16 h-16 bg-slate-800/50 rounded-full flex items-center justify-center text-slate-600 mx-auto mb-4">
                          <Clock size={32} />
                        </div>
                        <p className="text-slate-500 text-sm">No recent activity. Start your first track!</p>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </motion.div>
          )}

          {view === 'badges' && (
            <motion.div 
              key="badges"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="space-y-10"
            >
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-3xl font-black text-white">Your Achievements 🏅</h2>
                  <p className="text-slate-400 mt-1">You've unlocked {progress.badges.length} out of {BADGES.length} badges.</p>
                </div>
                <button 
                  onClick={() => setView('dashboard')}
                  className="bg-dark-card px-6 py-2 rounded-xl font-bold border border-dark-border hover:border-[#0b8c9f] transition-all text-white"
                >
                  Back to Dashboard
                </button>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                {BADGES.map((badge) => {
                  const isUnlocked = progress.badges.includes(badge.id);
                  const Icon = ICON_MAP[badge.icon] || Star;

                  return (
                    <motion.div 
                      key={badge.id}
                      whileHover={isUnlocked ? { scale: 1.05 } : {}}
                      className={cn(
                        "bg-dark-card rounded-3xl p-6 border-2 transition-all relative group",
                        isUnlocked 
                          ? "border-[#0b8c9f]/20 shadow-2xl shadow-[#0b8c9f]/5" 
                          : "border-slate-800 opacity-40"
                      )}
                    >
                      <div className={cn(
                        "w-16 h-16 rounded-2xl flex items-center justify-center text-white mb-4 shadow-lg transition-all",
                        isUnlocked ? badge.color : "bg-slate-700"
                      )}>
                        {isUnlocked ? <Icon size={32} /> : <Lock size={32} className="text-slate-500" />}
                      </div>
                      
                      <h4 className={cn("font-bold text-lg mb-1", isUnlocked ? "text-white" : "text-slate-500")}>{badge.name}</h4>
                      <p className="text-xs text-slate-400 leading-relaxed mb-4">{badge.description}</p>
                      
                      <div className="mt-auto pt-4 border-t border-slate-800 flex items-center justify-between">
                        <div className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Condition</div>
                        <div className="text-[10px] font-bold text-[#0b8c9f]">{badge.condition}</div>
                      </div>

                      {!isUnlocked && (
                        <div className="absolute inset-0 bg-dark-bg/40 backdrop-blur-[1px] rounded-3xl flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                          <div className="bg-slate-900 text-white text-[10px] font-bold px-3 py-1.5 rounded-full flex items-center gap-1.5 border border-slate-700">
                            <Lock size={12} /> LOCKED
                          </div>
                        </div>
                      )}
                    </motion.div>
                  );
                })}
              </div>
            </motion.div>
          )}

          {view === 'challenge' && (
            <motion.div 
              key="challenge"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 1.05 }}
              className="max-w-3xl mx-auto"
            >
              <div className="mb-8 flex items-center justify-between">
                <button 
                  onClick={() => setView('dashboard')}
                  className="text-slate-400 hover:text-white flex items-center gap-2 font-medium"
                >
                  <ArrowRight size={20} className="rotate-180" /> Back to Dashboard
                </button>
                <div className="flex items-center gap-4">
                  <div className="text-sm font-bold text-slate-500 uppercase tracking-widest">
                    Question {currentQuestionIndex + 1} of {questions.length}
                  </div>
                  <div className="w-32 h-2 bg-slate-800 rounded-full overflow-hidden">
                    <div 
                      className="h-full bg-[#0b8c9f] transition-all duration-500"
                      style={{ width: `${((currentQuestionIndex + 1) / questions.length) * 100}%` }}
                    />
                  </div>
                </div>
              </div>

              <div className="bg-dark-card rounded-3xl p-10 shadow-2xl border border-dark-border">
                <div className="mb-6">
                  <div className="flex items-center gap-3 mb-4">
                    <div className={cn(
                      "px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest",
                      questions[currentQuestionIndex].type === 'fill-blanks' ? "bg-blue-500/10 text-blue-400 border border-blue-500/20" :
                      questions[currentQuestionIndex].type === 'fix-error' ? "bg-red-500/10 text-red-400 border border-red-500/20" :
                      questions[currentQuestionIndex].type === 'predict-output' ? "bg-purple-500/10 text-purple-400 border border-purple-500/20" :
                      "bg-slate-500/10 text-slate-400 border border-slate-500/20"
                    )}>
                      {questions[currentQuestionIndex].type?.replace('-', ' ') || 'multiple choice'}
                    </div>
                    <div className="px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest bg-teal-500/10 text-teal-400 border border-teal-500/20 flex items-center gap-1.5">
                      <Brain size={12} /> {questions[currentQuestionIndex].concept}
                    </div>
                  </div>
                  <h2 className="text-2xl font-bold leading-tight text-white">
                    {questions[currentQuestionIndex].text}
                  </h2>
                </div>

                {questions[currentQuestionIndex].codeSnippet && (
                  <div className="mb-8 rounded-2xl overflow-hidden border border-slate-800 bg-slate-900/50 p-6 font-mono text-sm leading-relaxed text-slate-300 relative group">
                    <div className="absolute top-4 right-4 text-slate-600 group-hover:text-slate-400 transition-colors">
                      <Code2 size={16} />
                    </div>
                    <pre className="whitespace-pre-wrap">
                      {questions[currentQuestionIndex].type === 'fill-blanks' ? (
                        questions[currentQuestionIndex].codeSnippet?.split('_____').map((part, i, arr) => (
                          <React.Fragment key={i}>
                            {part}
                            {i < arr.length - 1 && (
                              <span className={cn(
                                "inline-block min-w-[80px] h-6 border-b-2 mx-1 px-2 text-center transition-all",
                                isAnswered 
                                  ? "border-[#0b8c9f] text-[#0b8c9f] font-bold" 
                                  : "border-slate-600 text-slate-500"
                              )}>
                                {isAnswered ? questions[currentQuestionIndex].options[questions[currentQuestionIndex].correctAnswer] : '____'}
                              </span>
                            )}
                          </React.Fragment>
                        ))
                      ) : (
                        questions[currentQuestionIndex].codeSnippet
                      )}
                    </pre>
                  </div>
                )}

                <div className="space-y-4">
                  {questions[currentQuestionIndex].options.map((option, idx) => {
                    const isCorrect = idx === questions[currentQuestionIndex].correctAnswer;
                    const isSelected = selectedOption === idx;
                    
                    return (
                      <button
                        key={idx}
                        disabled={isAnswered}
                        onClick={() => handleAnswer(idx)}
                        className={cn(
                          "w-full p-5 rounded-2xl border-2 text-left transition-all flex items-center justify-between group",
                          isAnswered 
                            ? isCorrect 
                              ? "bg-green-500/10 border-green-500/50 text-green-400" 
                              : isSelected ? "bg-red-500/10 border-red-500/50 text-red-400" : "bg-slate-800/50 border-slate-800 opacity-50"
                            : "bg-slate-800/50 border-dark-border text-slate-300 hover:border-[#0b8c9f] hover:bg-slate-800"
                        )}
                      >
                        <span className="font-medium">{option}</span>
                        {isAnswered && isCorrect && <CheckCircle2 size={20} className="text-green-400" />}
                      </button>
                    );
                  })}
                </div>

                {/* Execution Visualizer for Basics */}
                {activeTrack === 'basics' && questions[currentQuestionIndex].executionSteps && (
                  <div className="mt-8 p-6 bg-slate-900/50 rounded-2xl border border-slate-800">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center gap-2 text-[#0b8c9f] font-bold text-sm uppercase tracking-widest">
                        <Play size={16} /> Execution Visualization
                      </div>
                      <button 
                        onClick={() => {
                          setCode(questions[currentQuestionIndex].codeSnippet || '');
                          setView('coding');
                        }}
                        className="text-xs font-bold text-slate-400 hover:text-white flex items-center gap-1.5 transition-colors"
                      >
                        <Code2 size={14} /> Try it Yourself
                      </button>
                    </div>
                    <div className="space-y-4">
                      {questions[currentQuestionIndex].executionSteps?.map((step, idx) => (
                        <div key={idx} className="flex gap-4 items-start group">
                          <div className="w-8 h-8 rounded-lg bg-slate-800 flex items-center justify-center text-xs font-bold text-slate-500 group-hover:bg-[#0b8c9f]/20 group-hover:text-[#0b8c9f] transition-colors">
                            {step.line}
                          </div>
                          <div className="flex-1">
                            <p className="text-sm text-slate-300 mb-2">{step.explanation}</p>
                            {step.variables && (
                              <div className="flex flex-wrap gap-2">
                                {Object.entries(step.variables).map(([key, val]) => (
                                  <div key={key} className="px-2 py-1 bg-slate-800 rounded-md text-[10px] font-mono text-slate-400 border border-slate-700">
                                    <span className="text-[#0b8c9f]">{key}</span>: {val}
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <AnimatePresence>
                  {isAnswered && (
                    <motion.div 
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      className="mt-8 p-6 bg-[#0b8c9f]/10 rounded-2xl border border-[#0b8c9f]/20 shadow-2xl shadow-[#0b8c9f]/5"
                    >
                      <div className="flex items-center justify-between mb-4">
                        <div className="flex items-center gap-2 text-[#0b8c9f] font-bold">
                          <Trophy size={18} /> Great job! 🔥
                        </div>
                        <div className="text-[10px] font-bold text-slate-500 uppercase tracking-widest bg-slate-800 px-2 py-1 rounded-md border border-slate-700">
                          Concept: <span className="text-white">{questions[currentQuestionIndex].concept}</span>
                        </div>
                      </div>
                      <p className="text-slate-300 text-sm leading-relaxed mb-6">
                        {questions[currentQuestionIndex].explanation}
                      </p>
                      <button 
                        onClick={nextQuestion}
                        className="w-full bg-[#0b8c9f] text-white py-4 rounded-xl font-bold flex items-center justify-center gap-2 hover:bg-[#097a8a] transition-all shadow-lg shadow-[#0b8c9f]/20"
                      >
                        {currentQuestionIndex === questions.length - 1 ? 'Finish Track' : 'Next Question'} <ArrowRight size={20} />
                      </button>
                    </motion.div>
                  )}

                  {!isAnswered && (
                    <div className="mt-8 flex items-center justify-between">
                      {((activeTrack === 'practice') || (activeTrack === 'reinforcement' && wrongAttempts > 0) || (activeTrack === 'final' && wrongAttempts > 0)) ? (
                        <button 
                          onClick={() => setShowHint(!showHint)}
                          className="text-[#ff7a00] font-bold text-sm flex items-center gap-2 hover:underline"
                        >
                          <Star size={16} /> {showHint ? 'Hide Hint' : 'Need a Hint?'}
                        </button>
                      ) : <div />}
                      
                      {showHint && (
                        <motion.div 
                          initial={{ opacity: 0, x: 10 }}
                          animate={{ opacity: 1, x: 0 }}
                          className="text-sm text-slate-400 italic bg-orange-500/10 px-4 py-2 rounded-lg border border-orange-500/20"
                        >
                          💡 {questions[currentQuestionIndex].hint}
                        </motion.div>
                      )}
                    </div>
                  )}
                </AnimatePresence>
              </div>
            </motion.div>
          )}

          {view === 'coding' && (
            <motion.div 
              key="coding"
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              className="max-w-4xl mx-auto"
            >
              <div className="bg-dark-card rounded-3xl p-8 shadow-2xl border border-dark-border">
                <div className="flex items-center justify-between mb-8">
                  <div>
                    <h2 className="text-3xl font-bold text-white mb-2">Coding Challenge</h2>
                    <p className="text-slate-400">
                      {TRACKS.find(t => t.id === activeTrack)?.codingChallenge?.title || 
                       TRACKS.find(t => t.id === activeTrack)?.title || 
                       'Interactive Playground'}
                    </p>
                  </div>
                  <div className="p-3 bg-[#0b8c9f]/10 rounded-2xl text-[#0b8c9f]">
                    <Code2 size={32} />
                  </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                  <div className="space-y-6">
                    <div className="p-6 bg-slate-800/50 rounded-2xl border border-dark-border">
                      <h3 className="text-lg font-bold text-white mb-4">Problem Description</h3>
                      <p className="text-slate-300 leading-relaxed">
                        {TRACKS.find(t => t.id === activeTrack)?.codingChallenge?.description || 
                         "Experiment with the code snippet below and see how it works!"}
                      </p>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="p-4 bg-slate-800/50 rounded-xl border border-dark-border">
                        <div className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1">Input Format</div>
                        <code className="text-sm text-[#0b8c9f]">
                          {TRACKS.find(t => t.id === activeTrack)?.codingChallenge?.inputFormat || "N/A"}
                        </code>
                      </div>
                      <div className="p-4 bg-slate-800/50 rounded-xl border border-dark-border">
                        <div className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-1">Expected Output</div>
                        <code className="text-sm text-[#ff7a00]">
                          {TRACKS.find(t => t.id === activeTrack)?.codingChallenge?.outputFormat || "N/A"}
                        </code>
                      </div>
                    </div>
                  </div>

                  <div className="bg-slate-950 rounded-2xl p-6 border border-dark-border flex flex-col h-[400px]">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex gap-1.5">
                        <div className="w-3 h-3 rounded-full bg-red-500" />
                        <div className="w-3 h-3 rounded-full bg-yellow-500" />
                        <div className="w-3 h-3 rounded-full bg-green-500" />
                      </div>
                      <span className="text-[10px] font-bold text-slate-600 uppercase tracking-widest">solution.js</span>
                    </div>
                    <textarea 
                      value={code}
                      onChange={(e) => setCode(e.target.value)}
                      className="flex-1 bg-transparent text-slate-300 font-mono text-sm outline-none resize-none"
                      spellCheck={false}
                    />
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <div className="text-sm">
                    {evaluationResult && !errorAnalysis && (
                      <div className={cn(
                        "flex items-center gap-2 font-bold",
                        evaluationResult.success ? "text-green-400" : "text-red-400"
                      )}>
                        {evaluationResult.success ? <CheckCircle2 size={18} /> : <X size={18} />}
                        {evaluationResult.message}
                      </div>
                    )}
                  </div>
                  <button 
                    disabled={isEvaluating}
                    onClick={evaluateCode}
                    className="bg-[#0b8c9f] text-white px-8 py-4 rounded-xl font-bold hover:bg-[#097a8a] transition-all flex items-center gap-2 shadow-lg shadow-[#0b8c9f]/20 disabled:opacity-50"
                  >
                    {isEvaluating ? 'Evaluating...' : 'Run & Evaluate'} <Play size={20} />
                  </button>
                </div>

                {errorAnalysis && (
                  <ErrorAnalyzerView 
                    analysis={errorAnalysis} 
                    onRetry={() => {
                      setErrorAnalysis(null);
                      setEvaluationResult(null);
                    }}
                    currentHintLevel={currentHintLevel}
                    onShowNextHint={() => setCurrentHintLevel(prev => Math.min(3, prev + 1))}
                  />
                )}
              </div>
            </motion.div>
          )}

          {view === 'submission' && (
            <motion.div 
              key="submission"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="max-w-3xl mx-auto"
            >
              <div className="bg-dark-card rounded-3xl p-8 shadow-2xl border border-dark-border">
                <div className="text-center mb-8">
                  <div className="inline-flex p-4 bg-green-500/10 rounded-full text-green-500 mb-4">
                    <CheckCircle2 size={48} />
                  </div>
                  <h2 className="text-3xl font-bold text-white mb-2">Code Accepted!</h2>
                  <p className="text-slate-400">Final Step: Submit your project documentation</p>
                </div>

                <div className="space-y-6">
                  <div className="p-6 bg-[#0b8c9f]/5 rounded-2xl border border-[#0b8c9f]/20 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="p-3 bg-[#0b8c9f]/10 rounded-xl text-[#0b8c9f]">
                        <FileText size={24} />
                      </div>
                      <div>
                        <h3 className="font-bold text-white">Documentation Template</h3>
                        <p className="text-xs text-slate-400">Includes Front Page, Certificate, Acknowledgement</p>
                      </div>
                    </div>
                    <button 
                      onClick={() => generateProjectDoc(progress.name, progress.grade, progress.rollNumber, TRACKS.find(t => t.id === activeTrack)?.codingChallenge?.title || 'Project', activeTrack, progress.schoolName, progress.principalName)}
                      className="text-[#0b8c9f] font-bold text-sm flex items-center gap-2 hover:underline"
                    >
                      <Download size={18} /> Download Word Template
                    </button>
                  </div>

                  <div className="space-y-4">
                    <label className="block text-sm font-medium text-slate-300">Project Documentation</label>
                    <textarea 
                      value={docText}
                      onChange={(e) => setDocText(e.target.value)}
                      placeholder="Paste your documentation content here or write a summary of your project..."
                      className="w-full h-48 px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] focus:border-transparent outline-none transition-all resize-none"
                    />
                  </div>

                  <button 
                    disabled={!docText || isSubmitting}
                    onClick={handleDocSubmit}
                    className="w-full bg-[#ff7a00] text-white py-4 rounded-xl font-bold hover:bg-[#e66e00] transition-all flex items-center justify-center gap-2 shadow-lg shadow-[#ff7a00]/20 disabled:opacity-50"
                  >
                    {isSubmitting ? 'Submitting...' : 'Complete Track & Submit'} <Upload size={20} />
                  </button>
                </div>
              </div>
            </motion.div>
          )}

          {view === 'project-submission' && activeProject && (
            <motion.div 
              key="project-submission"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="max-w-3xl mx-auto"
            >
              <div className="bg-dark-card rounded-3xl p-8 shadow-2xl border border-dark-border">
                <div className="text-center mb-8">
                  <div className="inline-flex p-4 bg-[#0b8c9f]/10 rounded-full text-[#0b8c9f] mb-4">
                    <Rocket size={48} />
                  </div>
                  <h2 className="text-3xl font-bold text-white mb-2">Project Code Verified!</h2>
                  <p className="text-slate-400">Final Step: Submit your detailed project documentation</p>
                </div>

                <div className="space-y-6">
                  <div className="p-6 bg-slate-800/50 rounded-2xl border border-dark-border">
                    <h3 className="text-lg font-bold text-white mb-2">{activeProject.title}</h3>
                    <p className="text-sm text-slate-400">Your code has passed all technical evaluations. Now, explain your architectural decisions and logic.</p>
                  </div>

                  <div className="p-6 bg-[#0b8c9f]/5 rounded-2xl border border-[#0b8c9f]/20 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <div className="p-3 bg-[#0b8c9f]/10 rounded-xl text-[#0b8c9f]">
                        <FileText size={24} />
                      </div>
                      <div>
                        <h3 className="font-bold text-white">Project Documentation Template</h3>
                        <p className="text-xs text-slate-400">Professional template for your project</p>
                      </div>
                    </div>
                    <button 
                      onClick={() => generateProjectDoc(
                        progress.name, 
                        progress.grade, 
                        progress.rollNumber, 
                        activeProject.title,
                        activeProject.id,
                        progress.schoolName,
                        progress.principalName,
                        docContent
                      )}
                      className="text-[#0b8c9f] font-bold text-sm flex items-center gap-2 hover:underline"
                    >
                      <Download size={18} /> Download Word Documentation
                    </button>
                  </div>

                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">1. Project Objective</label>
                      <textarea 
                        value={docContent.objective}
                        onChange={(e) => setDocContent(prev => ({ ...prev, objective: e.target.value }))}
                        placeholder="What is the goal of this project?"
                        className="w-full h-24 px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none transition-all resize-none"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">2. Concepts Used</label>
                      <textarea 
                        value={docContent.conceptsUsed}
                        onChange={(e) => setDocContent(prev => ({ ...prev, conceptsUsed: e.target.value }))}
                        placeholder="Which programming concepts did you apply? (e.g. loops, arrays, logic)"
                        className="w-full h-24 px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none transition-all resize-none"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">3. How It Works</label>
                      <textarea 
                        value={docContent.howItWorks}
                        onChange={(e) => setDocContent(prev => ({ ...prev, howItWorks: e.target.value }))}
                        placeholder="Explain the logic and flow of your code."
                        className="w-full h-32 px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none transition-all resize-none"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">4. What I Learned</label>
                      <textarea 
                        value={docContent.whatILearned}
                        onChange={(e) => setDocContent(prev => ({ ...prev, whatILearned: e.target.value }))}
                        placeholder="What were your key takeaways from building this?"
                        className="w-full h-24 px-4 py-3 rounded-xl bg-dark-bg border border-dark-border text-white focus:ring-2 focus:ring-[#0b8c9f] outline-none transition-all resize-none"
                      />
                    </div>
                  </div>

                  <button 
                    disabled={!docContent.objective || !docContent.conceptsUsed || !docContent.howItWorks || !docContent.whatILearned || isSubmitting}
                    onClick={handleProjectDocSubmit}
                    className="w-full bg-[#0b8c9f] text-white py-4 rounded-xl font-bold hover:bg-[#097a8a] transition-all flex items-center justify-center gap-2 shadow-lg shadow-[#0b8c9f]/20 disabled:opacity-50"
                  >
                    {isSubmitting ? 'Submitting Project...' : 'Finalize & Submit Project'} <Upload size={20} />
                  </button>
                </div>
              </div>
            </motion.div>
          )}

          {view === 'project-intro' && activeProject && (
            <motion.div 
              key="project-intro"
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="max-w-5xl mx-auto"
            >
              <div className="bg-dark-card rounded-[2.5rem] overflow-hidden shadow-2xl border border-dark-border flex flex-col md:flex-row min-h-[600px]">
                {/* Left Side: Project Visuals & Stats */}
                <div className="md:w-2/5 bg-gradient-to-br from-[#0b8c9f] to-[#086a7a] p-12 text-white flex flex-col justify-between relative overflow-hidden">
                  <div className="absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full -mr-32 -mt-32 blur-3xl" />
                  <div className="absolute bottom-0 left-0 w-64 h-64 bg-black/20 rounded-full -ml-32 -mb-32 blur-3xl" />
                  
                  <div className="relative z-10">
                    <div className="w-16 h-16 bg-white/20 backdrop-blur-md rounded-2xl flex items-center justify-center mb-8 shadow-xl">
                      <Rocket size={32} />
                    </div>
                    <h2 className="text-4xl font-black mb-4 leading-tight">Project<br/>Launchpad</h2>
                    <p className="text-white/80 text-sm leading-relaxed">
                      You've mastered the fundamentals. Now it's time to apply your skills to a real-world challenge.
                    </p>
                  </div>

                  <div className="relative z-10 space-y-6">
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 bg-white/10 rounded-xl flex items-center justify-center">
                        <Target size={20} />
                      </div>
                      <div>
                        <div className="text-[10px] font-bold text-white/60 uppercase tracking-widest">Difficulty</div>
                        <div className="text-sm font-bold">Level {activeProject.level} Challenge</div>
                      </div>
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 bg-white/10 rounded-xl flex items-center justify-center">
                        <Award size={20} />
                      </div>
                      <div>
                        <div className="text-[10px] font-bold text-white/60 uppercase tracking-widest">Reward</div>
                        <div className="text-sm font-bold">500 XP & Certificate</div>
                      </div>
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 bg-white/10 rounded-xl flex items-center justify-center">
                        <Code2 size={20} />
                      </div>
                      <div>
                        <div className="text-[10px] font-bold text-white/60 uppercase tracking-widest">Language</div>
                        <div className="text-sm font-bold">{progress.language}</div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Right Side: Project Content */}
                <div className="md:w-3/5 p-12 flex flex-col justify-between bg-dark-card">
                  <div>
                    <div className="flex items-center gap-2 mb-6">
                      <div className="h-px w-8 bg-[#0b8c9f]" />
                      <span className="text-[10px] font-bold text-[#0b8c9f] uppercase tracking-[0.2em]">Mission Briefing</span>
                    </div>
                    
                    <h3 className="text-3xl font-black text-white mb-6">{activeProject.title}</h3>
                    
                    <div className="prose prose-invert max-w-none mb-10">
                      <p className="text-slate-400 text-lg leading-relaxed">
                        {activeProject.description}
                      </p>
                    </div>

                    <div className="grid grid-cols-1 gap-6 mb-10">
                      <div className="group p-6 bg-slate-800/30 rounded-3xl border border-dark-border hover:border-[#0b8c9f]/30 transition-all">
                        <div className="flex items-center gap-3 mb-4">
                          <div className="w-8 h-8 rounded-lg bg-[#0b8c9f]/10 flex items-center justify-center text-[#0b8c9f]">
                            <Info size={18} />
                          </div>
                          <h4 className="font-bold text-white text-sm uppercase tracking-wider">Input Requirements</h4>
                        </div>
                        <code className="text-xs text-slate-400 font-mono block p-3 bg-black/20 rounded-xl border border-white/5">
                          {activeProject.inputFormat}
                        </code>
                      </div>

                      <div className="group p-6 bg-slate-800/30 rounded-3xl border border-dark-border hover:border-[#ff7a00]/30 transition-all">
                        <div className="flex items-center gap-3 mb-4">
                          <div className="w-8 h-8 rounded-lg bg-[#ff7a00]/10 flex items-center justify-center text-[#ff7a00]">
                            <CheckCircle2 size={18} />
                          </div>
                          <h4 className="font-bold text-white text-sm uppercase tracking-wider">Expected Output</h4>
                        </div>
                        <code className="text-xs text-slate-400 font-mono block p-3 bg-black/20 rounded-xl border border-white/5">
                          {activeProject.outputFormat}
                        </code>
                      </div>
                    </div>
                  </div>

                  <div className="flex flex-col sm:flex-row gap-4">
                    {progress.assignedProject ? (
                      <button 
                        onClick={() => {
                          setActiveProject(progress.assignedProject!);
                          // Reset code and evaluation result when starting a new project
                          setCode(progress.assignedProject!.starterCode);
                          setEvaluationResult(null);
                          setView('project');
                        }}
                        className="flex-1 bg-[#0b8c9f] text-white py-5 rounded-2xl font-bold text-lg hover:bg-[#097a8a] transition-all flex items-center justify-center gap-3 shadow-xl shadow-[#0b8c9f]/20 group"
                      >
                        Initialize Coding <ArrowRight size={24} className="group-hover:translate-x-1 transition-transform" />
                      </button>
                    ) : (
                      <button 
                        disabled={isGeneratingProject}
                        onClick={generateUniqueProject}
                        className="flex-1 bg-[#0b8c9f] text-white py-5 rounded-2xl font-bold text-lg hover:bg-[#097a8a] transition-all flex items-center justify-center gap-3 shadow-xl shadow-[#0b8c9f]/20 group disabled:opacity-50"
                      >
                        {isGeneratingProject ? 'Generating Unique Project...' : 'Initialize Unique Project'} <Rocket size={24} className="group-hover:-translate-y-1 transition-transform" />
                      </button>
                    )}
                    <button 
                      onClick={() => setView('dashboard')}
                      className="px-8 py-5 rounded-2xl font-bold text-slate-400 hover:text-white hover:bg-slate-800 transition-all border border-transparent hover:border-dark-border"
                    >
                      Return to Hub
                    </button>
                  </div>
                </div>
              </div>
            </motion.div>
          )}

          {view === 'project' && activeProject && (
            <motion.div 
              key="project"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="max-w-6xl mx-auto"
            >
              <div className="mb-8 flex items-center justify-between">
                <button 
                  onClick={() => setView('project-intro')}
                  className="group text-slate-400 hover:text-white flex items-center gap-2 font-bold text-sm transition-all"
                >
                  <ArrowRight size={18} className="rotate-180 group-hover:-translate-x-1 transition-transform" /> Back to Briefing
                </button>
                <div className="flex items-center gap-3">
                  <div className="px-3 py-1 rounded-full bg-[#0b8c9f]/10 border border-[#0b8c9f]/20 text-[#0b8c9f] text-[10px] font-bold uppercase tracking-widest">
                    Live Development
                  </div>
                  <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
                </div>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                {/* Left: Project Info Sidebar */}
                <div className="lg:col-span-4 space-y-6">
                  <div className="bg-dark-card rounded-3xl p-8 shadow-2xl border border-dark-border relative overflow-hidden">
                    <div className="absolute top-0 left-0 w-1 h-full bg-[#0b8c9f]" />
                    <h2 className="text-2xl font-black mb-4 text-white">{activeProject.title}</h2>
                    <p className="text-slate-400 text-sm mb-8 leading-relaxed">{activeProject.description}</p>
                    
                    <div className="space-y-6">
                      <div className="space-y-3">
                        <h4 className="text-[10px] font-bold text-slate-500 uppercase tracking-[0.2em]">Technical Specs</h4>
                        <div className="p-4 bg-slate-900/50 rounded-2xl border border-white/5 space-y-4">
                          <div>
                            <div className="text-[9px] font-bold text-[#0b8c9f] uppercase mb-1">Input Signature</div>
                            <code className="text-xs text-slate-300 font-mono">{activeProject.inputFormat}</code>
                          </div>
                          <div>
                            <div className="text-[9px] font-bold text-[#ff7a00] uppercase mb-1">Expected Return</div>
                            <code className="text-xs text-slate-300 font-mono">{activeProject.outputFormat}</code>
                          </div>
                        </div>
                      </div>

                      <div className="p-5 bg-[#0b8c9f]/5 rounded-2xl border border-[#0b8c9f]/10">
                        <div className="flex items-center gap-3 mb-2">
                          <Info size={16} className="text-[#0b8c9f]" />
                          <span className="text-xs font-bold text-white">Pro Tip</span>
                        </div>
                        <p className="text-[11px] text-slate-400 leading-relaxed">
                          Ensure your function returns the exact value specified in the expected return format.
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Right: Code Editor */}
                <div className="lg:col-span-8 flex flex-col gap-6">
                  <div className="bg-slate-950 rounded-[2rem] p-1 shadow-2xl border border-dark-border flex flex-col h-[600px] overflow-hidden">
                    <div className="flex items-center justify-between px-6 py-4 bg-slate-900/50 border-b border-white/5">
                      <div className="flex items-center gap-4">
                        <div className="flex gap-1.5">
                          <div className="w-3 h-3 rounded-full bg-[#ff5f56]" />
                          <div className="w-3 h-3 rounded-full bg-[#ffbd2e]" />
                          <div className="w-3 h-3 rounded-full bg-[#27c93f]" />
                        </div>
                        <div className="h-4 w-px bg-white/10 mx-2" />
                        <div className="flex items-center gap-2">
                          <Code2 size={14} className="text-slate-500" />
                          <span className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">main.{progress.language?.toLowerCase() === 'python' ? 'py' : 'js'}</span>
                        </div>
                      </div>
                      <div className="text-[10px] font-medium text-slate-500 italic">
                        Autosave enabled
                      </div>
                    </div>
                    
                    <div className="flex-1 relative p-6">
                      <textarea 
                        value={code}
                        onChange={(e) => setCode(e.target.value)}
                        readOnly={progress.projectStatus === 'completed'}
                        className={cn(
                          "w-full h-full bg-transparent text-slate-300 font-mono text-sm outline-none resize-none leading-relaxed custom-scrollbar",
                          progress.projectStatus === 'completed' && "opacity-50 cursor-not-allowed"
                        )}
                        spellCheck={false}
                        autoFocus
                      />
                      
                      {evaluationResult && !errorAnalysis && (
                        <motion.div 
                          initial={{ opacity: 0, y: 10 }}
                          animate={{ opacity: 1, y: 0 }}
                          className={`absolute bottom-10 left-10 right-10 p-4 rounded-xl border ${
                            evaluationResult.success 
                              ? 'bg-green-500/10 border-green-500/30 text-green-400' 
                              : 'bg-red-500/10 border-red-500/30 text-red-400'
                          } backdrop-blur-md shadow-2xl z-20`}
                        >
                          <div className="flex items-center gap-3">
                            {evaluationResult.success ? <CheckCircle2 size={20} /> : <AlertTriangle size={20} />}
                            <p className="text-sm font-bold">{evaluationResult.message}</p>
                          </div>
                        </motion.div>
                      )}

                      {errorAnalysis && (
                        <div className="absolute inset-0 bg-slate-950/90 backdrop-blur-sm z-30 overflow-y-auto p-10 custom-scrollbar">
                          <div className="max-w-3xl mx-auto">
                            <ErrorAnalyzerView 
                              analysis={errorAnalysis} 
                              onRetry={() => {
                                setErrorAnalysis(null);
                                setEvaluationResult(null);
                              }}
                              currentHintLevel={currentHintLevel}
                              onShowNextHint={() => setCurrentHintLevel(prev => Math.min(3, prev + 1))}
                            />
                          </div>
                        </div>
                      )}
                    </div>

                    <div className="p-6 bg-slate-900/30 border-t border-white/5 flex items-center justify-between">
                      <div className="text-[10px] text-slate-500 font-mono">
                        Line: {code.split('\n').length}, Col: {code.split('\n').pop()?.length || 0}
                      </div>
                      <button 
                        onClick={() => handleProjectSubmit(activeProject.id)}
                        disabled={isEvaluating || progress.projectStatus === 'completed'}
                        className="bg-[#0b8c9f] hover:bg-[#097a8a] text-white px-8 py-3 rounded-xl font-bold text-sm transition-all flex items-center gap-2 shadow-lg shadow-[#0b8c9f]/20 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {progress.projectStatus === 'completed' ? 'Project Completed' : isEvaluating ? 'Evaluating...' : 'Deploy & Submit'} <ArrowRight size={18} />
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              {/* Project Documentation Sample */}
              <div className="mt-12 bg-dark-card rounded-[2rem] p-10 border border-dark-border shadow-2xl relative overflow-hidden">
                <div className="absolute top-0 right-0 w-32 h-32 bg-[#ff7a00]/5 rounded-full -mr-16 -mt-16 blur-2xl" />
                
                <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6 mb-10">
                  <div className="flex items-center gap-4">
                    <div className="p-4 bg-[#ff7a00]/10 rounded-2xl text-[#ff7a00] shadow-inner">
                      <FileText size={32} />
                    </div>
                    <div>
                      <h3 className="text-2xl font-black text-white">Professional Documentation</h3>
                      <p className="text-slate-400 text-sm">Structure your project like a professional developer.</p>
                    </div>
                  </div>
                  <button 
                    onClick={() => generateProjectDoc(progress.name, progress.grade, progress.rollNumber, activeProject.title, activeProject.id, progress.schoolName, progress.principalName)}
                    className="bg-white/5 hover:bg-white/10 text-white px-6 py-3 rounded-xl text-sm font-bold flex items-center gap-2 border border-white/10 transition-all"
                  >
                    <Download size={18} /> Download Word Guide
                  </button>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                  <div className="lg:col-span-2 space-y-8">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                      {[
                        { title: 'Objective', desc: 'Define the core purpose and goals of your project.', icon: Target, color: 'text-blue-400' },
                        { title: 'Concepts Used', desc: 'List the technical skills and logic applied.', icon: Brain, color: 'text-purple-400' },
                        { title: 'Implementation', desc: 'Step-by-step breakdown of your coding logic.', icon: Code2, color: 'text-green-400' },
                        { title: 'Reflections', desc: 'What challenges did you face and overcome?', icon: Star, color: 'text-yellow-400' }
                      ].map((item, i) => (
                        <div key={i} className="p-6 bg-slate-800/30 rounded-2xl border border-dark-border hover:border-white/10 transition-all group">
                          <div className="flex items-center gap-3 mb-3">
                            <item.icon size={18} className={item.color} />
                            <h4 className="font-bold text-white text-sm">{item.title}</h4>
                          </div>
                          <p className="text-xs text-slate-400 leading-relaxed">{item.desc}</p>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="bg-slate-950 rounded-2xl p-8 border border-dark-border relative group">
                    <div className="absolute top-4 right-4 text-slate-700">
                      <Info size={16} />
                    </div>
                    <h4 className="text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-6">Sample Format</h4>
                    <div className="space-y-4 font-mono text-[10px] text-slate-500">
                      <div className="pb-4 border-b border-white/5">
                        <p className="text-[#0b8c9f] mb-1"># Project: {activeProject.title}</p>
                        <p className="text-slate-400 italic">Project ID: RS-PROJ-{activeProject.id}</p>
                        <p className="text-slate-400 italic">Author: {progress.name}</p>
                      </div>
                      <div className="space-y-2">
                        <p className="text-white">## 1. Objective</p>
                        <p className="pl-4">The primary goal is to create a robust system that...</p>
                      </div>
                      <div className="space-y-2">
                        <p className="text-white">## 2. Technical Stack</p>
                        <p className="pl-4">- Language: {progress.language}</p>
                        <p className="pl-4">- Environment: RS Learning Lab</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </main>

      {/* Footer Branding */}
      <footer className="max-w-7xl mx-auto px-6 py-12 border-t border-dark-border text-center">
        <div className="flex flex-col items-center gap-4">
          <div className="bg-white p-1.5 rounded-xl">
            <img 
              src={logo}
              alt="Logo" 
              className="h-10"
              onError={(e) => {
                (e.target as HTMLImageElement).src = "https://api.dicebear.com/7.x/bottts/svg?seed=RS";
              }}
            />
          </div>
          <div>
            <p className="text-sm font-bold text-white tracking-widest uppercase">Powered by RS Learning Lab</p>
            <p className="text-xs text-slate-500 mt-1">Founder: Gokula Krishnan</p>
          </div>
          <p className="text-[10px] text-slate-600 max-w-md mt-4">
            A structured stage-based learning system designed to build strong foundations in logic and programming.
            © 2026 RS Learning Lab. All rights reserved.
          </p>
        </div>
      </footer>
    </div>
  );
}
