export type LevelId = 1 | 2 | 3 | 4;
export type TrackId = 'basics' | 'practice' | 'reinforcement' | 'final';
export type ProgrammingLanguage = 'C' | 'C++' | 'Java' | 'Python' | 'JavaScript';

export interface Question {
  id: string;
  text: string;
  options: string[];
  correctAnswer: number;
  explanation: string;
  hint: string;
  concept: 'Variables' | 'Loops' | 'Functions' | 'OOP' | 'Arrays' | 'Logic' | 'Syntax' | 'Data Types';
  type?: 'multiple-choice' | 'fill-blanks' | 'fix-error' | 'predict-output';
  codeSnippet?: string;
  blankIndex?: number;
  executionSteps?: { line: number; explanation: string; variables?: Record<string, any> }[];
}

export interface Project {
  id: string;
  level: LevelId;
  title: string;
  description: string;
  inputFormat: string;
  outputFormat: string;
  starterCode: string;
  testCases: { input: any[]; expected: any }[];
}

export type EffortLevel = 'Beginner' | 'Active' | 'Consistent' | 'Advanced';

export interface UserProgress {
  xp: number;
  completedTracks: Record<string, boolean>; // key: "level-language-track"
  completedProjects: string[];
  badges: string[]; // IDs of unlocked badges
  streak: number;
  lastActivityDate: string | null; // ISO string
  questionsSolved: number;
  name: string;
  grade: string;
  rollNumber: string;
  schoolName?: string;
  principalName?: string;
  language?: ProgrammingLanguage;
  answeredQuestionIds: string[];
  assignedProject?: Project;
  projectStatus?: 'not-started' | 'coding' | 'documentation' | 'completed';
  
  // Effort Tracking
  timeSpent: number; // in minutes
  totalAttempts: number;
  hintsUsed: number;
  retries: number;
  effortLevel: EffortLevel;
  lastLoginDate: string;
  activityLog: { date: string; action: string }[];
  vivaSessions?: VivaSession[];
  vivaSummary?: VivaSession['summary'];
  vivaScore?: number; // AI Viva Score (0-5)
}

export interface VivaQuestion {
  id: string;
  text: string;
  type: 'Conceptual' | 'Output Prediction' | 'Code Explanation' | 'Design Choice';
  context?: string; // Code snippet or scenario
}

export interface VivaEvaluation {
  isCorrect: boolean;
  feedback: {
    correct: string;
    missing: string;
    improvement: string;
  };
  qualitativeScore: 'Excellent explanation' | 'Good understanding' | 'Needs more clarity';
}

export interface VivaSession {
  id: string;
  level: number;
  language: string;
  questions: {
    question: VivaQuestion;
    answer: string;
    evaluation: VivaEvaluation;
  }[];
  summary: {
    overall: string;
    strengths: string[];
    improvements: string[];
    finalQualitative: string;
  };
  completedAt: string;
}

export interface PlagiarismReport {
  score: number; // 0-100
  status: 'Safe' | 'Needs Review' | 'High Similarity';
  explanation: string;
  similarSubmissions: {
    studentName: string;
    rollNumber: string;
    similarityScore: number;
    reason: string;
  }[];
}

export interface Badge {
  id: string;
  name: string;
  description: string;
  condition: string;
  icon: string; // Lucide icon name or emoji
  color: string;
}

export const BADGES: Badge[] = [
  {
    id: 'starter',
    name: 'Starter Badge',
    description: 'Awarded for completing your very first question!',
    condition: 'Complete 1 question',
    icon: 'Rocket',
    color: 'bg-blue-500'
  },
  {
    id: 'consistency',
    name: 'Consistency Badge',
    description: 'Awarded for solving questions 3 days in a row!',
    condition: '3 day streak',
    icon: 'Flame',
    color: 'bg-orange-500'
  },
  {
    id: 'practice_master',
    name: 'Practice Master',
    description: 'You have mastered the basics in the Practice Track!',
    condition: 'Complete any Practice Track',
    icon: 'Target',
    color: 'bg-teal-500'
  },
  {
    id: 'logic_builder',
    name: 'Logic Builder',
    description: 'Your logical thinking is improving! Reinforcement Track cleared.',
    condition: 'Complete any Reinforcement Track',
    icon: 'Brain',
    color: 'bg-purple-500'
  },
  {
    id: 'final_challenger',
    name: 'Final Challenger',
    description: 'You faced the toughest challenges and won!',
    condition: 'Complete any Final Track',
    icon: 'Trophy',
    color: 'bg-yellow-500'
  },
  {
    id: 'project_builder',
    name: 'Project Builder',
    description: 'Built a real-world application. Impressive!',
    condition: 'Complete 1 mini project',
    icon: 'Laptop',
    color: 'bg-indigo-500'
  },
  {
    id: 'code_champion',
    name: 'Code Champion',
    description: 'Completed an entire level! You are a true champion.',
    condition: 'Complete all tracks in a level',
    icon: 'Crown',
    color: 'bg-amber-500'
  },
  {
    id: 'master_coder',
    name: 'Master Coder',
    description: 'The ultimate achievement. You have completed the entire journey!',
    condition: 'Complete all levels',
    icon: 'Star',
    color: 'bg-rose-500'
  }
];

export const LEVELS = [
  { id: 1, title: 'Level 1', subtitle: 'Classes 6–8', description: 'Foundation: Logic & Basic Concepts' },
  { id: 2, title: 'Level 2', subtitle: 'Classes 9–10', description: 'Intermediate: Algorithms & Problem Solving' },
  { id: 3, title: 'Level 3', subtitle: 'Classes 11–12', description: 'Advanced: Real-world Application & Coding' },
] as const;

export interface Track {
  id: TrackId;
  title: string;
  description: string;
  codingChallenge?: {
    title: string;
    description: string;
    inputFormat: string;
    outputFormat: string;
    starterCode: string;
    testCases: { input: any[]; expected: any }[];
  };
}

export const TRACKS: Track[] = [
  { 
    id: 'basics', 
    title: 'Basics', 
    description: 'Introduction to core concepts and language syntax',
  },
  { 
    id: 'practice', 
    title: 'Practice Track', 
    description: 'Build your foundation with core concepts',
  },
  { 
    id: 'reinforcement', 
    title: 'Reinforcement Track', 
    description: 'Strengthen your logic with challenges',
  },
  { 
    id: 'final', 
    title: 'Final Track', 
    description: 'Master the level with comprehensive tests',
  },
] as const;

export const PROJECTS: Project[] = [
  {
    id: 'calc',
    level: 1,
    title: 'Advanced Computational Logic Engine',
    description: 'Architect a versatile arithmetic processor capable of executing multi-step operations with strict error handling. Your module must support addition (+), subtraction (-), multiplication (*), division (/), modulo (%), and exponentiation (**). Crucially, it must implement a robust validation layer to prevent "Division by Zero" errors and handle invalid operators by returning "Error: Invalid Operator".',
    inputFormat: 'calculate(10, 0, "/")',
    outputFormat: '"Error: Division by Zero"',
    starterCode: '/**\n * @function calculate\n * @description Executes arithmetic operations with built-in error validation.\n * @param {number} num1 - The primary operand.\n * @param {number} num2 - The secondary operand.\n * @param {string} operator - The operation to perform (+, -, *, /, %, **).\n * @returns {number|string} The calculated result or a diagnostic error message.\n */\nfunction calculate(num1, num2, operator) {\n  // Implementation logic here\n  \n  return null;\n}',
    testCases: [
      { input: [10, 5, "+"], expected: 15 },
      { input: [10, 5, "-"], expected: 5 },
      { input: [10, 5, "*"], expected: 50 },
      { input: [10, 5, "/"], expected: 2 },
      { input: [10, 3, "%"], expected: 1 },
      { input: [2, 3, "**"], expected: 8 },
      { input: [10, 0, "/"], expected: "Error: Division by Zero" },
      { input: [10, 5, "invalid"], expected: "Error: Invalid Operator" }
    ]
  },
  {
    id: 'quiz',
    level: 2,
    title: 'Dynamic Performance Analytics Engine',
    description: 'Engineer a sophisticated evaluation system that processes complex student response datasets. The system must calculate a weighted performance index where each question is assigned a specific difficulty coefficient (weight). Additionally, implement a "Penalty System": if a response is incorrect, subtract 50% of its weight from the total score. The final score cannot be negative.',
    inputFormat: 'evaluate([{ans: "A", weight: 10}, {ans: "C", weight: 20}], ["A", "B"])',
    outputFormat: '0',
    starterCode: '/**\n * @function evaluate\n * @description Computes a weighted performance score with penalty logic.\n * @param {Object[]} studentResponses - Array of objects: {ans: string, weight: number}.\n * @param {string[]} correctAnswers - Array of master key strings.\n * @returns {number} The total aggregated weighted score (min 0).\n */\nfunction evaluate(studentResponses, correctAnswers) {\n  let score = 0;\n  // Implementation logic here\n  // 1. Correct: +weight\n  // 2. Incorrect: -0.5 * weight\n  // 3. Final score >= 0\n  \n  return score;\n}',
    testCases: [
      { input: [[{ans: "A", weight: 10}, {ans: "C", weight: 20}], ["A", "C"]], expected: 30 },
      { input: [[{ans: "A", weight: 10}, {ans: "C", weight: 20}], ["A", "B"]], expected: 0 }, // 10 - (0.5 * 20) = 0
      { input: [[{ans: "B", weight: 10}, {ans: "D", weight: 20}], ["A", "C"]], expected: 0 }, // Penalty makes it negative, return 0
      { input: [[{ans: "A", weight: 100}, {ans: "B", weight: 50}], ["A", "C"]], expected: 75 } // 100 - (0.5 * 50) = 75
    ]
  },
  {
    id: 'advanced-logic',
    level: 3,
    title: 'Cryptographic Security & Encryption Module',
    description: 'Develop a high-security cryptographic module implementing a dynamic Caesar Cipher algorithm. The module must perform character-level transformations by shifting ASCII values within the alphabet. Your implementation must handle both uppercase and lowercase letters, preserve spaces and special characters without shifting them, and ensure correct wrapping (e.g., "z" shifted by 1 becomes "a").',
    inputFormat: 'encrypt("Hello World!", 3)',
    outputFormat: '"Khoor Zruog!"',
    starterCode: '/**\n * @function encrypt\n * @description Performs character-level encryption with case sensitivity and symbol preservation.\n * @param {string} text - The plaintext string.\n * @param {number} shift - The integer shift value.\n * @returns {string} The resulting ciphertext string.\n */\nfunction encrypt(text, shift) {\n  let result = "";\n  // Implementation logic here\n  \n  return result;\n}',
    testCases: [
      { input: ["Hello World!", 3], expected: "Khoor Zruog!" },
      { input: ["abc XYZ", 1], expected: "bcd YZA" },
      { input: ["Testing 123", 5], expected: "Yjxying 123" },
      { input: ["Zebra", 1], expected: "Afcsb" }
    ]
  },
  {
    id: 'data-analyzer',
    level: 4,
    title: 'Big Data Statistical Analysis Engine',
    description: 'Construct a high-performance data analysis engine that processes large arrays of sensor readings. Your engine must calculate the mean, median, and mode of the dataset. Additionally, it must identify "Outliers" (values more than 2 standard deviations from the mean) and return an object containing these statistical metrics. Mode should be an array of values (in case of multiple modes).',
    inputFormat: 'analyze([10, 20, 30, 40, 50, 1000])',
    outputFormat: '{mean: 191.67, median: 35, mode: [10, 20, 30, 40, 50, 1000], outliers: [1000]}',
    starterCode: '/**\n * @function analyze\n * @description Performs statistical analysis on a numerical dataset.\n * @param {number[]} data - Array of sensor readings.\n * @returns {Object} {mean: number, median: number, mode: number[], outliers: number[]}.\n */\nfunction analyze(data) {\n  // Implementation logic here\n  \n  return {\n    mean: 0,\n    median: 0,\n    mode: [],\n    outliers: []\n  };\n}',
    testCases: [
      { input: [[10, 20, 30, 40, 50]], expected: { mean: 30, median: 30, mode: [10, 20, 30, 40, 50], outliers: [] } },
      { input: [[1, 2, 2, 3, 4]], expected: { mean: 2.4, median: 2, mode: [2], outliers: [] } },
      { input: [[10, 10, 20, 20, 30]], expected: { mean: 18, median: 20, mode: [10, 20], outliers: [] } }
    ]
  },
];

// Question Bank with specific counts: Level 1 (15), Level 2 (10), Level 3 (5)
export interface Submission {
  id: string;
  studentName: string;
  rollNumber: string;
  grade: string;
  level: number;
  track: string;
  language?: string;
  code?: string;
  aiFeedback: string;
  docText: string;
  status: 'pending' | 'reviewed';
  submittedAt: string;
  
  // School Details
  schoolName?: string;
  principalName?: string;
  
  // Effort Data for Teacher
  timeSpent: number;
  attempts: number;
  hintsUsed: number;
  retries: number;
  streak: number;
  completionRate: number; // 0-100
  lei: number; // Learning Efficiency Index
  leiCategory: 'Active Learner' | 'Consistent Learner' | 'Needs Support' | 'Stalled Learner';
  leiInsight: string;
  vivaSummary?: VivaSession['summary'];
  plagiarismReport?: PlagiarismReport;
  
  // Qualitative Evaluation & Marks (Total: 50)
  marks?: {
    documentation: {
      objective: number; // 0-5
      concepts: number; // 0-5
      explanation: number; // 0-5
      learningOutcome: number; // 0-5
      total: number; // 0-20
    };
    code: {
      logic: number; // 0-5
      output: number; // 0-5
      concepts: number; // 0-5
      total: number; // 0-15
    };
    viva: {
      aiScore: number; // 0-5
      teacherScore: number; // 0-10
      total: number; // 0-15
    };
    total: number; // 0-50
  };
  
  documentationMarks?: number; // Old field, keeping for compatibility
  vivaScore?: number; // AI Viva Score (0-5)
  teacherVivaMarks?: number; // Teacher Viva Marks (0-10)
  vivaRequested?: boolean;
  understandingLevel?: 'Basic' | 'Good' | 'Excellent';
  explanationAbility?: 'Developing' | 'Proficient' | 'Expert';
  teacherRemarks?: string;
  totalScore?: number;
}

export interface User {
  id: string;
  username: string;
  role: 'student' | 'teacher' | 'admin';
  name: string;
  assignedGrade?: string;
}

export interface LeaderboardEntry {
  name: string;
  lei: number; // Learning Effective Index
  grade: string;
  rollNumber: string;
  label: 'Top Contributor' | 'Most Consistent' | 'Active Learner' | 'Rising Star';
}

// Question Bank with specific counts: Basics (20), Practice (15), Reinforcement (10), Final (10)
const LANGUAGES: ProgrammingLanguage[] = ['C', 'C++', 'Java', 'Python', 'JavaScript'];

const createQuestion = (
  id: string, 
  text: string, 
  options: string[], 
  correctAnswer: number, 
  explanation: string, 
  hint: string,
  concept: Question['concept'],
  type: 'multiple-choice' | 'fill-blanks' | 'fix-error' | 'predict-output' = 'multiple-choice',
  codeSnippet?: string,
  blankIndex?: number,
  executionSteps?: { line: number; explanation: string; variables?: Record<string, any> }[]
): Question => ({
  id, text, options, correctAnswer, explanation, hint, concept, type, codeSnippet, blankIndex, executionSteps
});

const getFallbackQuestion = (concept: string, lang: string, level: number, track: string, index: number): Question => {
  const questions: Record<string, any> = {
    'Variables': {
      text: `Which of the following is a valid way to update a variable 'x' by adding 1 to it in ${lang}?`,
      options: lang === 'Python' ? ['x += 1', 'x =+ 1', 'x++', 'x = x + "1"'] : ['x++;', 'x += 1;', 'x = x + 1;', 'All of these'],
      correct: lang === 'Python' ? 0 : 3,
      explanation: 'Incrementing a variable can be done using the += operator or by adding 1 to the current value.',
      hint: 'Think about the shorthand operators.'
    },
    'Loops': {
      text: `How many times will a loop run if it starts at 0 and ends when it is less than 5?`,
      options: ['4', '5', '6', '0'],
      correct: 1,
      explanation: 'The loop will run for values 0, 1, 2, 3, and 4, which is 5 times.',
      hint: 'Count from 0 to 4.'
    },
    'Functions': {
      text: `What is the purpose of the 'return' keyword in a function?`,
      options: ['To stop the program', 'To send a value back to where the function was called', 'To print a message', 'To start a loop'],
      correct: 1,
      explanation: 'The return statement exits a function and optionally passes a value back to the caller.',
      hint: 'Think about the output of a function.'
    },
    'Arrays': {
      text: `What is the index of the second element in an array?`,
      options: ['0', '1', '2', 'Second'],
      correct: 1,
      explanation: 'Since array indexing starts at 0, the first element is at index 0 and the second is at index 1.',
      hint: 'Remember zero-based indexing.'
    },
    'Logic': {
      text: `What is the result of 'not True' (or !true) in ${lang}?`,
      options: ['True', 'False', 'None', 'Error'],
      correct: 1,
      explanation: 'The NOT operator flips the boolean value.',
      hint: 'Opposite of true.'
    },
    'Syntax': {
      text: `Which of these is used to end a statement in ${lang}?`,
      options: lang === 'Python' ? ['A new line', ';', ':', '.' ] : [';', 'A new line', ':', '.'],
      correct: 0,
      explanation: lang === 'Python' ? 'Python uses new lines to separate statements.' : 'JavaScript uses semicolons to end statements, although they are optional in many cases.',
      hint: 'Think about how lines end.'
    },
    'Data Types': {
      text: `Which of these is a floating-point number (decimal) in ${lang}?`,
      options: ['10', '"10.5"', '10.5', 'True'],
      correct: 2,
      explanation: 'Floating-point numbers are numbers with decimal points.',
      hint: 'Look for the dot.'
    },
    'OOP': {
      text: `What is a 'Class' in Object-Oriented Programming?`,
      options: ['A specific object', 'A blueprint for creating objects', 'A type of loop', 'A way to handle errors'],
      correct: 1,
      explanation: 'A class defines the properties and behaviors that its objects will have.',
      hint: 'Think about blueprints.'
    }
  };

  const q = questions[concept] || questions['Variables'];
  return createQuestion(
    `gen-${level}-${lang}-${track}-${index}`,
    q.text,
    q.options,
    q.correct,
    q.explanation,
    q.hint,
    concept as any
  );
};

const generateQuestions = (): Record<LevelId, Record<ProgrammingLanguage, Record<TrackId, Question[]>>> => {
  const bank: any = { 1: {}, 2: {}, 3: {} };

  LANGUAGES.forEach(lang => {
    [1, 2, 3].forEach(level => {
      bank[level][lang] = {
        basics: [],
        practice: [],
        reinforcement: [],
        final: []
      };

      // Helper to add questions with concept variety
      const addTrackQuestions = (track: TrackId, count: number, levelNum: number) => {
        const concepts: Question['concept'][] = ['Variables', 'Loops', 'Functions', 'Arrays', 'Logic', 'Syntax', 'Data Types'];
        if (levelNum === 3) concepts.push('OOP');

        for (let i = 1; i <= count; i++) {
          const concept = concepts[i % concepts.length];
          let q: Question;

          // Level 1: Foundation (Classes 6-8)
          if (levelNum === 1) {
            if (track === 'basics') {
              if (i === 1) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `In ${lang}, what is the correct way to store the number 25 in a variable named 'age'?`,
                  lang === 'Python' ? ['age = 25', 'var age = 25', 'int age = 25', 'age : 25'] : ['let age = 25;', 'age = 25;', 'var age = 25;', 'All of these'],
                  0,
                  'Variables are used to store data values for later use in your program.',
                  'Look for the assignment operator (=).',
                  'Variables',
                  'multiple-choice'
                );
              } else if (i === 2) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What will be the result of this calculation in ${lang}?`,
                  ['15', '20', '25', '30'],
                  1,
                  'The expression adds 10 and 10 to get 20.',
                  'Basic addition.',
                  'Logic',
                  'predict-output',
                  lang === 'Python' ? 'x = 10\ny = 10\nprint(x + y)' : 'let x = 10;\nlet y = 10;\nconsole.log(x + y);'
                );
              } else if (i === 3) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Fill in the blank to complete the print statement in ${lang}.`,
                  lang === 'Python' ? ['print', 'show', 'display', 'output'] : ['console.log', 'print', 'alert', 'log'],
                  0,
                  `The standard way to output text in ${lang} is using the ${lang === 'Python' ? 'print()' : 'console.log()'} function.`,
                  'Think about how we show results.',
                  'Syntax',
                  'fill-blanks',
                  lang === 'Python' ? '_____("Hello!")' : '_____("Hello!");',
                  0
                );
              } else if (i === 4) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Which of these is a valid variable name in ${lang}?`,
                  ['1st_name', 'first-name', 'first_name', 'first name'],
                  2,
                  'Variable names cannot start with numbers, cannot contain spaces, and usually use underscores or camelCase.',
                  'Avoid spaces and starting with numbers.',
                  'Variables',
                  'multiple-choice'
                );
              } else if (i === 5) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is the output of this ${lang} code?`,
                  ['Hello World', 'HelloWorld', 'Hello World!', 'Error'],
                  0,
                  'String concatenation combines two strings into one.',
                  'Look at the space between the words.',
                  'Data Types',
                  'predict-output',
                  lang === 'Python' ? 'a = "Hello"\nb = "World"\nprint(a + " " + b)' : 'let a = "Hello";\nlet b = "World";\nconsole.log(a + " " + b);'
                );
              } else if (i === 6) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is a 'comment' used for in ${lang}?`,
                  ['To make the code run faster', 'To explain the code to humans', 'To store secret data', 'To stop the program'],
                  1,
                  'Comments are ignored by the computer and are only for humans to read.',
                  'Think about documentation.',
                  'Syntax'
                );
              } else if (i === 7) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Which symbol is used for multiplication in ${lang}?`,
                  ['x', '*', '^', '&'],
                  1,
                  'The asterisk (*) is the standard symbol for multiplication in almost all programming languages.',
                  'It is above the number 8 on most keyboards.',
                  'Logic'
                );
              } else if (i === 8) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is the value of 'result' after this code runs?`,
                  ['True', 'False', 'None', 'Error'],
                  0,
                  '10 is indeed greater than 5, so the condition is True.',
                  'Is 10 > 5?',
                  'Logic',
                  'predict-output',
                  lang === 'Python' ? 'result = 10 > 5' : 'let result = 10 > 5;'
                );
              } else if (i === 9) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Which of these is a 'String' in ${lang}?`,
                  ['123', 'True', '"Hello"', 'None'],
                  2,
                  'Strings are sequences of characters enclosed in quotes.',
                  'Look for the quotes.',
                  'Data Types'
                );
              } else if (i === 10) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What does the '+' operator do when used with two strings?`,
                  ['Adds them as numbers', 'Subtracts one from another', 'Joins them together (Concatenation)', 'Deletes them'],
                  2,
                  'Using + with strings "glues" them together.',
                  'Think about joining words.',
                  'Data Types'
                );
              } else if (i === 11) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Which of these is a Boolean value in ${lang}?`,
                  lang === 'Python' ? ['True', '"True"', '100', '3.14'] : ['true', '"true"', '100', '3.14'],
                  0,
                  'Booleans represent one of two values: True or False (or true/false in JS).',
                  'It is not a string.',
                  'Data Types'
                );
              } else if (i === 12) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is the result of 10 / 2 in ${lang}?`,
                  ['5', '5.0', '2', '2.5'],
                  lang === 'Python' ? 1 : 0,
                  lang === 'Python' ? 'In Python 3, the / operator always returns a float.' : 'In JavaScript, 10 / 2 is 5.',
                  'Think about the data type of the result.',
                  'Logic'
                );
              } else if (i === 13) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Which keyword is used to start an 'if' statement in ${lang}?`,
                  ['if', 'when', 'check', 'condition'],
                  0,
                  'The "if" keyword is used to start a conditional statement.',
                  'It is the same in almost all languages.',
                  'Syntax'
                );
              } else if (i === 14) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is the output of this code?`,
                  ['10', '5', '15', 'Error'],
                  2,
                  'The code adds 5 to the existing value of x.',
                  'x starts at 10.',
                  'Logic',
                  'predict-output',
                  lang === 'Python' ? 'x = 10\nx = x + 5\nprint(x)' : 'let x = 10;\nx = x + 5;\nconsole.log(x);'
                );
              } else if (i === 15) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Which of these is used to define a block of code in ${lang}?`,
                  lang === 'Python' ? ['Indentation', 'Curly braces {}', 'Parentheses ()', 'Square brackets []'] : ['Curly braces {}', 'Indentation', 'Parentheses ()', 'Square brackets []'],
                  0,
                  lang === 'Python' ? 'Python uses indentation (whitespace) to define blocks of code.' : 'JavaScript uses curly braces {} to define blocks of code.',
                  'How do we group lines of code together?',
                  'Syntax'
                );
              } else if (i === 16) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `How do you call a function named 'greet' in ${lang}?`,
                  ['greet()', 'call greet', 'greet[]', 'run greet'],
                  0,
                  'Functions are called by using their name followed by parentheses.',
                  'Parentheses are key.',
                  'Functions'
                );
              } else if (i === 17) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is the result of 5 - 2 in ${lang}?`,
                  ['3', '7', '10', '2.5'],
                  0,
                  'Subtraction uses the minus (-) symbol.',
                  'Basic math.',
                  'Logic'
                );
              } else if (i === 18) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is the first character of the string "Code"?`,
                  ['C', 'o', 'd', 'e'],
                  0,
                  'In programming, we start counting from 0, but the question asks for the character itself.',
                  'Look at the word.',
                  'Data Types'
                );
              } else if (i === 19) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `What is 'True and False' in ${lang}?`,
                  ['True', 'False', 'None', 'Error'],
                  1,
                  'The AND operator requires both sides to be true to result in true.',
                  'Both must be true.',
                  'Logic'
                );
              } else if (i === 20) {
                q = createQuestion(
                  `l1-${lang}-b${i}`,
                  `Which keyword is used to repeat code a certain number of times?`,
                  ['for', 'if', 'var', 'print'],
                  0,
                  'The "for" keyword is commonly used to create loops.',
                  'Think about repetition.',
                  'Loops'
                );
              } else {
                q = getFallbackQuestion(concept, lang, 1, track, i);
              }
            } else if (track === 'practice') {
              if (i === 1) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `How would you swap the values of two variables 'a' and 'b' in ${lang}?`,
                  lang === 'Python' ? ['a, b = b, a', 'swap(a, b)', 'a = b; b = a', 'temp = a; a = b; b = temp'] : ['let temp = a; a = b; b = temp;', 'a = b; b = a;', 'swap(a, b);', 'a, b = b, a;'],
                  0,
                  'Swapping values often requires a temporary variable, though some languages like Python have shortcuts.',
                  'Think about how to not lose the first value.',
                  'Variables'
                );
              } else if (i === 2) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `Which condition checks if a number 'n' is EVEN?`,
                  ['n % 2 == 0', 'n % 2 == 1', 'n / 2 == 0', 'n * 2 == 0'],
                  0,
                  'An even number has a remainder of 0 when divided by 2.',
                  'Use the modulo operator (%).',
                  'Logic'
                );
              } else if (i === 3) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `What is the area of a rectangle with length 5 and width 10?`,
                  ['15', '50', '25', '100'],
                  1,
                  'Area = length * width. So 5 * 10 = 50.',
                  'Multiply the two numbers.',
                  'Logic'
                );
              } else if (i === 4) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `Fix the error in this string declaration:`,
                  ['Add a closing quote', 'Change name to Name', 'Remove the =', 'Add a semicolon'],
                  0,
                  'Strings must start and end with matching quotes.',
                  'Look at the end of the string.',
                  'Syntax',
                  'fix-error',
                  lang === 'Python' ? 'name = "Alice' : 'let name = "Alice'
                );
              } else if (i === 5) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `What will be printed?`,
                  ['10', '55', '5 + 5', 'Error'],
                  0,
                  'The variables x and y are added together.',
                  'x is 5, y is 5.',
                  'Logic',
                  'predict-output',
                  lang === 'Python' ? 'x = 5\ny = 5\nprint(x + y)' : 'let x = 5;\nlet y = 5;\nconsole.log(x + y);'
                );
              } else if (i === 6) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `What is the result of 2 ** 3 in ${lang}?`,
                  ['6', '8', '9', '5'],
                  1,
                  'The ** operator is used for exponentiation (2 to the power of 3).',
                  '2 * 2 * 2 = ?',
                  'Logic'
                );
              } else if (i === 7) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `How do you find the length of a string 's' in ${lang}?`,
                  lang === 'Python' ? ['len(s)', 's.length', 's.size()', 'count(s)'] : ['s.length', 'len(s)', 's.size()', 's.count'],
                  0,
                  lang === 'Python' ? 'The len() function returns the number of items in an object.' : 'The .length property returns the length of a string.',
                  'How do we measure size?',
                  'Syntax'
                );
              } else if (i === 8) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `Which of these will result in an error in ${lang}?`,
                  lang === 'Python' ? ['"Hello" + 5', '"Hello" + "5"', '5 + 5', '"5" + "5"'] : ['5 + "5"', '"Hello" + 5', '5 - "2"', 'None of these'],
                  lang === 'Python' ? 0 : 3,
                  lang === 'Python' ? 'In Python, you cannot add a string and an integer directly.' : 'In JavaScript, 5 + "5" results in "55" (coercion), and 5 - "2" results in 3.',
                  'Think about mixing types.',
                  'Data Types'
                );
              } else if (i === 9) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `What is the result of 10 - 4?`,
                  ['6', '14', '40', '2.5'],
                  0,
                  '10 minus 4 equals 6.',
                  'Basic subtraction.',
                  'Logic'
                );
              } else if (i === 10) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `What is the output of "Hi" * 3 in Python? (In JS, think about "Hi".repeat(3))`,
                  ['HiHiHi', 'Hi 3', 'HiHi', 'Error'],
                  0,
                  'Multiplying a string by a number repeats it.',
                  'Repeat the word.',
                  'Data Types'
                );
              } else if (i === 11) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `How do you check the type of a variable 'x' in ${lang}?`,
                  lang === 'Python' ? ['type(x)', 'typeof x', 'x.type()', 'check(x)'] : ['typeof x', 'type(x)', 'x.type', 'x.getType()'],
                  0,
                  'The type/typeof function tells you if a variable is a string, number, etc.',
                  'Checking the category.',
                  'Data Types'
                );
              } else if (i === 12) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `Which operator checks if a value is LESS THAN OR EQUAL to another?`,
                  ['<=', '>=', '==', '!='],
                  0,
                  'The <= operator combines less than (<) and equal to (=).',
                  'Look at the symbols.',
                  'Logic'
                );
              } else if (i === 13) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `What is 'True or False' in ${lang}?`,
                  ['True', 'False', 'None', 'Error'],
                  0,
                  'The OR operator only needs one side to be true to result in true.',
                  'Either one.',
                  'Logic'
                );
              } else if (i === 14) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `What is the value of 'a' after this code?`,
                  ['10', '20', '30', 'Error'],
                  1,
                  'The variable a is reassigned from 10 to 20.',
                  'Look at the last assignment.',
                  'Variables',
                  'predict-output',
                  lang === 'Python' ? 'a = 10\na = 20' : 'let a = 10; a = 20;'
                );
              } else if (i === 15) {
                q = createQuestion(
                  `l1-${lang}-p${i}`,
                  `Fix the syntax error:`,
                  lang === 'Python' ? ['Add a colon :', 'Remove the if', 'Change == to =', 'Add parentheses'] : ['Add curly braces {}', 'Remove the if', 'Change == to =', 'Add parentheses'],
                  0,
                  'In Python, if statements must end with a colon.',
                  'Look at the end of the line.',
                  'Syntax',
                  'fix-error',
                  lang === 'Python' ? 'if x == 10\n  print("Hi")' : 'if x == 10 { console.log("Hi"); }'
                );
              } else {
                q = getFallbackQuestion(concept, lang, 1, track, i);
              }
            } else if (track === 'reinforcement') {
                if (i === 1) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `What is the output of this simple loop?`,
                    ['0 1 2', '1 2 3', '0 1 2 3', 'Error'],
                    0,
                    'The loop runs 3 times, starting from 0.',
                    'Count from 0 to 2.',
                    'Loops',
                    'predict-output',
                    lang === 'Python' ? 'for i in range(3):\n  print(i, end=" ")' : 'for (let i = 0; i < 3; i++) {\n  process.stdout.write(i + " ");\n}'
                  );
                } else if (i === 2) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `What is the value of 'x' after this code?`,
                    ['15', '10', '5', 'Error'],
                    0,
                    'x starts at 10, then 5 is added to it.',
                    '10 + 5 = ?',
                    'Variables',
                    'predict-output',
                    lang === 'Python' ? 'x = 10\nx = x + 5' : 'let x = 10; x = x + 5;'
                  );
                } else if (i === 3) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `What is the result of 'True and False' in ${lang}?`,
                    ['True', 'False', 'None', 'Error'],
                    1,
                    'The AND operator requires both sides to be true.',
                    'Is both true?',
                    'Logic'
                  );
                } else if (i === 4) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `What is the result of 10 > 5 and 3 < 1 in ${lang}?`,
                    ['True', 'False', 'None', 'Error'],
                    1,
                    'The AND operator requires both sides to be true. Since 3 < 1 is false, the whole expression is false.',
                    'Check both conditions.',
                    'Logic'
                  );
                } else if (i === 5) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `Which of these is used to add a comment in ${lang}?`,
                    lang === 'Python' ? ['#', '//', '/*', '--'] : ['//', '#', '/*', '--'],
                    0,
                    `In ${lang}, ${lang === 'Python' ? '#' : '//'} is used for single-line comments.`,
                    'Think about documentation.',
                    'Syntax'
                  );
                } else if (i === 6) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `What is the value of 'y' after: x = 5; y = x + 2;?`,
                    ['5', '7', '2', 'Error'],
                    1,
                    'y is assigned the value of x (5) plus 2, which is 7.',
                    'Basic substitution.',
                    'Variables'
                  );
                } else if (i === 7) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `What does 'range(5)' (or similar loop) produce in terms of count?`,
                    ['4 values', '5 values', '6 values', 'Infinite values'],
                    1,
                    'A range from 0 to 5 (exclusive) produces 5 values: 0, 1, 2, 3, 4.',
                    'Count from 0.',
                    'Loops'
                  );
                } else if (i === 8) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `Which operator is used for 'not equal to' in ${lang}?`,
                    ['!=', '==', '<>', 'not='],
                    0,
                    'The != operator checks if two values are different.',
                    'Look for the exclamation mark.',
                    'Logic'
                  );
                } else if (i === 9) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `What is the result of "5" + "5" in ${lang}?`,
                    ['10', '"55"', '55', 'Error'],
                    1,
                    'Adding two strings together joins them (concatenation).',
                    'Think about joining text.',
                    'Data Types'
                  );
                } else if (i === 10) {
                  q = createQuestion(
                    `l1-${lang}-r${i}`,
                    `How do you start a 'while' loop in ${lang}?`,
                    ['while condition:', 'loop while:', 'repeat while:', 'during condition:'],
                    0,
                    'The while keyword starts a loop that runs as long as a condition is true.',
                    'It is a standard keyword.',
                    'Loops'
                  );
              } else {
                q = getFallbackQuestion(concept, lang, 1, track, i);
              }
            } else if (track === 'final') {
                if (i === 1) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `Final Challenge: What is the result of (10 + 5) * 2?`,
                    ['30', '20', '25', '15'],
                    0,
                    'Parentheses are evaluated first: 10 + 5 = 15. Then 15 * 2 = 30.',
                    'Order of operations.',
                    'Logic'
                  );
                } else if (i === 2) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `How many items are in this list/array?`,
                    ['3', '2', '4', '1'],
                    0,
                    'The list contains three items: 10, 20, and 30.',
                    'Count the elements.',
                    'Arrays',
                    'predict-output',
                    lang === 'Python' ? 'items = [10, 20, 30]\nprint(len(items))' : 'let items = [10, 20, 30];\nconsole.log(items.length);'
                  );
                } else if (i === 3) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `Which of these is a valid integer in ${lang}?`,
                    ['"10"', '10.5', '10', 'True'],
                    2,
                    'Integers are whole numbers without decimals or quotes.',
                    'Look for a whole number.',
                    'Data Types'
                  );
                } else if (i === 4) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `What is the output of: print(2 + 3 * 4)?`,
                    ['20', '14', '24', '18'],
                    1,
                    'Multiplication happens before addition: 3 * 4 = 12, then 12 + 2 = 14.',
                    'PEMDAS/BODMAS rules.',
                    'Logic'
                  );
                } else if (i === 5) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `How do you define a function in ${lang}?`,
                    lang === 'Python' ? ['def my_func():', 'function my_func():', 'func my_func():', 'define my_func():'] : ['function myFunc() { }', 'def myFunc() { }', 'func myFunc() { }', 'let myFunc = () => { }'],
                    0,
                    `Functions are defined using the ${lang === 'Python' ? 'def' : 'function'} keyword.`,
                    'Look for the keyword.',
                    'Functions'
                  );
                } else if (i === 6) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `What is the index of the last element in a list of 5 items?`,
                    ['5', '4', '0', '1'],
                    1,
                    'Since indexing starts at 0, the 5th item is at index 4.',
                    'Count from 0.',
                    'Arrays'
                  );
                } else if (i === 7) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `Which of these is a comparison operator?`,
                    ['=', '==', '+', '*'],
                    1,
                    '== is used to compare two values, while = is for assignment.',
                    'Checking for equality.',
                    'Logic'
                  );
                } else if (i === 8) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `What does 'break' do in a loop?`,
                    ['Skips one turn', 'Stops the loop entirely', 'Restarts the loop', 'Speeds up the loop'],
                    1,
                    'The break statement exits the loop immediately.',
                    'Stop the repetition.',
                    'Loops'
                  );
                } else if (i === 9) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `What is the result of 7 % 2?`,
                    ['3', '1', '0', '3.5'],
                    1,
                    '7 divided by 2 is 3 with a remainder of 1.',
                    'Think about the remainder.',
                    'Logic'
                  );
                } else if (i === 10) {
                  q = createQuestion(
                    `l1-${lang}-f${i}`,
                    `Which of these is a valid string in ${lang}?`,
                    ["'Hello'", 'Hello', '123', 'True'],
                    0,
                    'Strings must be enclosed in quotes.',
                    'Look for quotes.',
                    'Data Types'
                  );
              } else {
                q = getFallbackQuestion(concept, lang, 1, track, i);
              }
            }
          } 
          // Level 2: Intermediate (Classes 9-10)
          else if (levelNum === 2) {
            if (track === 'basics') {
              if (i === 1) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is the purpose of a 'for' loop in ${lang}?`,
                  ['To make a decision', 'To repeat a block of code a specific number of times', 'To store multiple values', 'To define a function'],
                  1,
                  'Loops are used for iteration, allowing you to run the same code multiple times efficiently.',
                  'Think about repetition.',
                  'Loops'
                );
              } else if (i === 2) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What will be the output of this ${lang} code?`,
                  ['0 1 2 3 4', '1 2 3 4 5', '0 1 2 3', '1 2 3 4'],
                  0,
                  `In ${lang}, loops usually start from 0 and go up to (but not including) the end value.`,
                  'Check the starting and ending points.',
                  'Loops',
                  'predict-output',
                  lang === 'Python' ? 'for i in range(5):\n  print(i, end=" ")' : 'for (let i = 0; i < 5; i++) {\n  process.stdout.write(i + " ");\n}'
                );
              } else if (i === 3) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `Which keyword is used to define a function in ${lang}?`,
                  lang === 'Python' ? ['def', 'function', 'func', 'define'] : ['function', 'def', 'func', 'let'],
                  0,
                  `The ${lang === 'Python' ? 'def' : 'function'} keyword is used to declare a new function.`,
                  'Look for the keyword that starts a function.',
                  'Functions',
                  'multiple-choice'
                );
              } else if (i === 4) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is the result of 10 % 3 in ${lang}?`,
                  ['3', '1', '0', '0.33'],
                  1,
                  'The modulo operator (%) returns the remainder of a division.',
                  'Think about the remainder.',
                  'Logic',
                  'multiple-choice'
                );
              } else if (i === 5) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `Fix the error in this ${lang} code to make it print 'Success'.`,
                  ['Change = to ==', 'Change == to =', 'Add a semicolon', 'Remove the if'],
                  0,
                  'The comparison operator is ==, while = is for assignment.',
                  'Look at the if condition.',
                  'Syntax',
                  'fix-error',
                  lang === 'Python' ? 'status = "ok"\nif status = "ok":\n  print("Success")' : 'let status = "ok";\nif (status = "ok") {\n  console.log("Success");\n}'
                );
              } else if (i === 6) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is an 'Array' (or List) used for?`,
                  ['To store a single number', 'To store multiple values in a single variable', 'To perform math calculations', 'To define a loop'],
                  1,
                  'Arrays/Lists are collections of items stored under one name.',
                  'Think about a list of items.',
                  'Arrays'
                );
              } else if (i === 7) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `How do you access the FIRST element of an array named 'fruits'?`,
                  ['fruits[1]', 'fruits[0]', 'fruits.first()', 'fruits{0}'],
                  1,
                  'In most programming languages, array indexing starts at 0.',
                  'Remember zero-based indexing.',
                  'Arrays'
                );
              } else if (i === 8) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What does the 'and' operator (or &&) do?`,
                  ['Returns true if either side is true', 'Returns true only if both sides are true', 'Flips true to false', 'Adds two numbers'],
                  1,
                  'The AND operator requires both conditions to be met.',
                  'Both must be true.',
                  'Logic'
                );
              } else if (i === 9) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is a 'parameter' in a function?`,
                  ['The result returned by the function', 'A value passed into the function', 'The name of the function', 'A type of loop'],
                  1,
                  'Parameters are variables listed in the function definition that receive values when the function is called.',
                  'Input to the function.',
                  'Functions'
                );
              } else if (i === 10) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What will be the output of this code?`,
                  ['10', '20', '30', 'Error'],
                  1,
                  'The function double(x) returns x * 2. So double(10) is 20.',
                  'Trace the function call.',
                  'Functions',
                  'predict-output',
                  lang === 'Python' ? 'def double(x):\n  return x * 2\nprint(double(10))' : 'function double(x) {\n  return x * 2;\n}\nconsole.log(double(10));'
                );
              } else if (i === 11) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is the difference between '==' and '===' in JavaScript? (If ${lang} is Python, think about '==' vs 'is')`,
                  lang === 'Python' ? ['== checks value, is checks identity', '== checks identity, is checks value', 'They are the same', 'is is for strings only'] : ['== checks value, === checks value and type', '== checks value and type, === checks value', 'They are the same', '=== is for numbers only'],
                  0,
                  lang === 'Python' ? '== compares values, while "is" checks if both variables refer to the same object in memory.' : '== performs type coercion before comparing, while === does not.',
                  'One is stricter than the other.',
                  'Logic'
                );
              } else if (i === 12) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is a 'while' loop used for?`,
                  ['To repeat code as long as a condition is true', 'To repeat code a fixed number of times', 'To define a function', 'To store data'],
                  0,
                  'A while loop continues to execute its block as long as the specified condition remains true.',
                  'Think about a condition-based loop.',
                  'Loops'
                );
              } else if (i === 13) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is a 'Nested if' statement?`,
                  ['An if statement inside another if statement', 'An if statement that never ends', 'A way to define a function', 'A type of loop'],
                  0,
                  'Nesting allows you to check for multiple conditions in a hierarchical way.',
                  'If within if.',
                  'Logic'
                );
              } else if (i === 14) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `Which method would you use to remove the LAST element from a list/array in ${lang}?`,
                  lang === 'Python' ? ['pop()', 'remove()', 'delete()', 'clear()'] : ['pop()', 'shift()', 'splice()', 'delete'],
                  0,
                  'The pop() method removes and returns the last item in a list or array.',
                  'Opposite of push/append.',
                  'Arrays'
                );
              } else if (i === 15) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `How do you convert a string to ALL UPPERCASE in ${lang}?`,
                  lang === 'Python' ? ['s.upper()', 's.uppercase()', 'upper(s)', 's.toUpper()'] : ['s.toUpperCase()', 's.upper()', 'toUpperCase(s)', 's.UPPER()'],
                  0,
                  'String methods allow you to transform text easily.',
                  'Look for "upper".',
                  'Data Types'
                );
              } else if (i === 16) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is the output of this ${lang} code?`,
                  ['Alice', '25', 'name', 'Error'],
                  0,
                  'Dictionaries/Objects store data in key-value pairs. user["name"] accesses the value associated with the key "name".',
                  'Accessing by key.',
                  'Data Types',
                  'predict-output',
                  lang === 'Python' ? 'user = {"name": "Alice", "age": 25}\nprint(user["name"])' : 'let user = {name: "Alice", age: 25};\nconsole.log(user.name);'
                );
              } else if (i === 17) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What does the 'not' operator (or !) do?`,
                  ['Reverses the boolean value', 'Adds two numbers', 'Checks if two values are equal', 'Starts a loop'],
                  0,
                  'The NOT operator flips True to False and vice versa.',
                  'Opposite.',
                  'Logic'
                );
              } else if (i === 18) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What happens if a function does not have a 'return' statement?`,
                  lang === 'Python' ? ['It returns None', 'It returns 0', 'It causes an error', 'It returns True'] : ['It returns undefined', 'It returns null', 'It causes an error', 'It returns 0'],
                  0,
                  'Functions that don\'t explicitly return a value still return a "null-like" value by default.',
                  'Default return.',
                  'Functions'
                );
              } else if (i === 19) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `What is 'Local Scope' in a function?`,
                  ['Variables that only exist inside the function', 'Variables that exist everywhere', 'Variables that are secret', 'Variables that never change'],
                  0,
                  'Local variables are only accessible within the block of code where they are defined.',
                  'Inside vs Outside.',
                  'Variables'
                );
              } else if (i === 20) {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `Which function is used to get input from the user in ${lang}?`,
                  lang === 'Python' ? ['input()', 'get()', 'read()', 'prompt()'] : ['prompt()', 'input()', 'readline()', 'get()'],
                  0,
                  'Getting user input is essential for interactive programs.',
                  'Asking the user.',
                  'Syntax'
                );
              } else {
                q = createQuestion(
                  `l2-${lang}-b${i}`,
                  `Intermediate ${concept}: How does ${lang} handle this?`,
                  [`Correct way`, `Incorrect way`, `Deprecated way`, `Error-prone way`],
                  0,
                  `${concept} is a key part of intermediate programming.`,
                  `Consider ${concept.toLowerCase()} behavior.`,
                  concept
                );
              }
            } else if (track === 'practice') {
                if (i === 1) {
                  q = createQuestion(
                    `l2-${lang}-p${i}`,
                    `Which method would you use to add an element to the END of an array in ${lang}?`,
                    lang === 'Python' ? ['append()', 'push()', 'add()', 'insert()'] : ['push()', 'append()', 'add()', 'insert()'],
                    0,
                    lang === 'Python' ? 'The append() method adds an item to the end of a list.' : 'The push() method adds one or more elements to the end of an array.',
                    'Think about "adding to the end".',
                    'Arrays'
                  );
                } else if (i === 2) {
                  q = createQuestion(
                    `l2-${lang}-p${i}`,
                    `What is the output of this ${lang} code?`,
                    ['[2, 4, 6]', '[1, 2, 3]', '[1, 3, 5]', 'Error'],
                    0,
                    'The code uses a map/list comprehension to double each number.',
                    'Each number is multiplied by 2.',
                    'Arrays',
                    'predict-output',
                    lang === 'Python' ? 'nums = [1, 2, 3]\nnew_nums = [x * 2 for x in nums]\nprint(new_nums)' : 'let nums = [1, 2, 3];\nlet newNums = nums.map(x => x * 2);\nconsole.log(newNums);'
                  );
                } else if (i === 3) {
                  q = createQuestion(
                    `l2-${lang}-p${i}`,
                    `How do you slice a list to get the first 3 elements in ${lang}?`,
                    lang === 'Python' ? ['my_list[:3]', 'my_list[1:3]', 'my_list[0:2]', 'my_list.slice(3)'] : ['my_list.slice(0, 3)', 'my_list[0:3]', 'my_list.get(3)', 'my_list.first(3)'],
                    0,
                    'Slicing allows you to extract a portion of a list or array.',
                    'Start at 0, end at 3.',
                    'Arrays'
                  );
                } else if (i === 4) {
                  q = createQuestion(
                    `l2-${lang}-p${i}`,
                    `What is the output of this loop?`,
                    ['0 2 4', '0 1 2 3 4', '2 4', '0 2'],
                    0,
                    'The range function can take a step value. range(0, 5, 2) means start at 0, go up to 5, jumping by 2.',
                    'Step by 2.',
                    'Loops',
                    'predict-output',
                    lang === 'Python' ? 'for i in range(0, 5, 2):\n  print(i, end=" ")' : 'for (let i = 0; i < 5; i += 2) {\n  process.stdout.write(i + " ");\n}'
                  );
                } else if (i === 5) {
                  q = createQuestion(
                    `l2-${lang}-p${i}`,
                    `How do you check if a key exists in a dictionary/object in ${lang}?`,
                    lang === 'Python' ? ['"key" in my_dict', 'my_dict.has("key")', 'my_dict.exists("key")', 'key in my_dict.keys()'] : ['"key" in my_obj', 'my_obj.hasOwnProperty("key")', 'my_obj.has("key")', 'Both A and B'],
                    lang === 'Python' ? 0 : 3,
                    'Checking for keys prevents errors when accessing data.',
                    'Look for the "in" keyword or hasOwnProperty.',
                    'Data Types'
                  );
                } else if (i === 6) {
                  q = createQuestion(
                    `l2-${lang}-p${i}`,
                    `What is the output of this function call?`,
                    ['15', '5', '10', 'Error'],
                    0,
                    'The function add(a, b) returns a + b. add(5, 10) is 15.',
                    'Sum of 5 and 10.',
                    'Functions',
                    'predict-output',
                    lang === 'Python' ? 'def add(a, b):\n  return a + b\nprint(add(5, 10))' : 'function add(a, b) {\n  return a + b;\n}\nconsole.log(add(5, 10));'
                  );
                } else if (i === 7) {
                  q = createQuestion(
                    `l2-${lang}-p${i}`,
                    `How do you create an empty list/array in ${lang}?`,
                    lang === 'Python' ? ['[]', '{}', '()', 'list()'] : ['[]', '{}', 'new Array()', 'Array()'],
                    0,
                    'Square brackets [] are used to define a list or array.',
                    'Empty brackets.',
                    'Arrays'
                  );
                }
            } else if (track === 'reinforcement') {
                  if (i === 1) {
                    q = createQuestion(
                      `l2-${lang}-r${i}`,
                      `What is the output of this nested loop?`,
                      ['00 01 10 11', '00 01 02 10', '0 1 2 3', 'Error'],
                      0,
                      'Nested loops run the inner loop completely for each iteration of the outer loop.',
                      'Trace i=0, then j=0,1...',
                      'Loops',
                      'predict-output',
                      lang === 'Python' ? 'for i in range(2):\n  for j in range(2):\n    print(f"{i}{j}", end=" ")' : 'for (let i = 0; i < 2; i++) {\n  for (let j = 0; j < 2; j++) {\n    process.stdout.write(i + "" + j + " ");\n  }\n}'
                    );
                  } else if (i === 2) {
                    q = createQuestion(
                      `l2-${lang}-r${i}`,
                      `Which function correctly finds the maximum value in a list?`,
                      lang === 'Python' ? ['max(list)', 'highest(list)', 'list.max()', 'top(list)'] : ['Math.max(...list)', 'list.max()', 'max(list)', 'list.highest()'],
                      0,
                      'Built-in functions make common tasks like finding the maximum value very easy.',
                      'Look for the standard library function.',
                      'Arrays'
                    );
                  } else if (i === 3) {
                    q = createQuestion(
                      `l2-${lang}-r${i}`,
                      `What is the result of 5 > 3 and 10 < 20 in ${lang}?`,
                      ['True', 'False', 'None', 'Error'],
                      0,
                      'Both conditions are true, so the AND operator results in true.',
                      'Check both sides.',
                      'Logic'
                    );
                  } else if (i === 4) {
                    q = createQuestion(
                      `l2-${lang}-r${i}`,
                      `How do you add an element to the END of a list/array in ${lang}?`,
                      lang === 'Python' ? ['append()', 'add()', 'push()', 'insert()'] : ['push()', 'append()', 'add()', 'insert()'],
                      0,
                      'The append/push method adds a new item to the end of the collection.',
                      'Think about adding to the end.',
                      'Arrays'
                    );
                  } else if (i === 5) {
                    q = createQuestion(
                      `l2-${lang}-r${i}`,
                      `What is the output of this code with a 'while' loop?`,
                      ['5 4 3 2 1', '1 2 3 4 5', '5 4 3 2', '4 3 2 1'],
                      0,
                      'The loop counts down from 5 as long as x is greater than 0.',
                      'Trace the countdown.',
                      'Loops',
                      'predict-output',
                      lang === 'Python' ? 'x = 5\nwhile x > 0:\n  print(x, end=" ")\n  x -= 1' : 'let x = 5;\nwhile (x > 0) {\n  process.stdout.write(x + " ");\n  x--;\n}'
                    );
              } else {
                q = getFallbackQuestion(concept, lang, 2, track, i);
              }
              } else if (track === 'final') {
                  if (i === 1) {
                    q = createQuestion(
                      `l2-${lang}-f${i}`,
                      `Which of these is a valid way to create a function that returns the square of a number?`,
                      lang === 'Python' ? ['def sq(x): return x*x', 'sq(x) = x*x', 'function sq(x) { return x*x }', 'def sq x: x*x'] : ['function sq(x) { return x*x; }', 'let sq = x => x*x;', 'const sq = function(x) { return x*x; };', 'All of these'],
                      lang === 'Python' ? 0 : 3,
                      'Functions can be defined in various ways depending on the language.',
                      'Look for the return keyword.',
                      'Functions'
                    );
                  } else if (i === 2) {
                    q = createQuestion(
                      `l2-${lang}-f${i}`,
                      `What is the output of this code using a list and a loop?`,
                      ['2 4 6', '1 2 3', '4 8 12', 'Error'],
                      0,
                      'The loop iterates through the list and multiplies each number by 2.',
                      'Trace the multiplication.',
                      'Arrays',
                      'predict-output',
                      lang === 'Python' ? 'nums = [1, 2, 3]\nfor n in nums:\n  print(n * 2, end=" ")' : 'let nums = [1, 2, 3];\nfor (let n of nums) {\n  process.stdout.write(n * 2 + " ");\n}'
                    );
              } else {
                q = getFallbackQuestion(concept, lang, 2, track, i);
              }
              }
          }
          // Level 3: Advanced (Classes 11-12)
          else {
            if (track === 'basics') {
              if (i === 1) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `In Object-Oriented Programming, what does 'Encapsulation' mean?`,
                  ['Inheriting properties from a parent', 'Hiding internal details and showing only necessary parts', 'Creating multiple functions with the same name', 'Running code asynchronously'],
                  1,
                  'Encapsulation bundles data and methods that work on that data within one unit, like a class.',
                  'Think about "capsules" or hiding.',
                  'OOP'
                );
              } else if (i === 2) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is 'Inheritance' in OOP?`,
                  ['A way to hide data', 'A mechanism where a new class is based on an existing class', 'A method to run code in parallel', 'A type of loop'],
                  1,
                  'Inheritance allows a class (child) to inherit attributes and methods from another class (parent).',
                  'Think about family traits.',
                  'OOP'
                );
              } else if (i === 3) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is 'Polymorphism'?`,
                  ['The ability of different classes to be treated as instances of the same parent class', 'Hiding data inside a class', 'Creating a class from another class', 'A way to handle errors'],
                  0,
                  'Polymorphism allows one interface to be used for a general class of actions.',
                  'Many forms.',
                  'OOP'
                );
              } else if (i === 4) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is a 'Constructor' in a class?`,
                  ['A method used to delete an object', 'A special method called when an object is created', 'A way to inherit from another class', 'A type of variable'],
                  1,
                  'Constructors initialize a newly created object.',
                  'It "constructs" the object.',
                  'OOP'
                );
              } else if (i === 5) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is the difference between a Class and an Object?`,
                  ['A Class is a blueprint, an Object is an instance of that blueprint', 'An Object is a blueprint, a Class is an instance', 'They are the same thing', 'A Class is a function, an Object is a variable'],
                  0,
                  'A class defines the structure, while an object is a concrete realization of that structure.',
                  'Blueprints vs Buildings.',
                  'OOP'
                );
              } else if (i === 6) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is 'Abstraction' in OOP?`,
                  ['Hiding the implementation details and showing only the functionality', 'Inheriting from multiple classes', 'Creating many objects', 'Handling errors'],
                  0,
                  'Abstraction simplifies complex reality by modeling classes appropriate to the problem.',
                  'Focus on what it does, not how.',
                  'OOP'
                );
              } else if (i === 7) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is the purpose of a 'try-except' (or try-catch) block?`,
                  ['To make code run faster', 'To handle errors and prevent the program from crashing', 'To define a loop', 'To create a class'],
                  1,
                  'Exception handling allows a program to deal with unexpected events gracefully.',
                  'Catching mistakes.',
                  'Logic'
                );
              } else if (i === 8) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is 'Recursion'?`,
                  ['A loop that never ends', 'A function that calls itself', 'A way to store data', 'A type of class'],
                  1,
                  'Recursion is a programming technique where a function calls itself to solve a problem.',
                  'Self-reference.',
                  'Functions'
                );
              } else if (i === 9) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What will be the output of this recursive function?`,
                  ['1', '120', '24', '5'],
                  1,
                  'This is the factorial function. factorial(5) is 5 * 4 * 3 * 2 * 1 = 120.',
                  'Trace the calls: 5 * fact(4)...',
                  'Functions',
                  'predict-output',
                  lang === 'Python' ? 'def fact(n):\n  if n == 1: return 1\n  return n * fact(n-1)\nprint(fact(5))' : 'function fact(n) {\n  if (n === 1) return 1;\n  return n * fact(n-1);\n}\nconsole.log(fact(5));'
                );
              } else if (i === 10) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is the 'self' (or 'this') keyword used for in a class?`,
                  ['To refer to the class itself', 'To refer to the current instance of the object', 'To create a new variable', 'To stop a loop'],
                  1,
                  'Self/This allows you to access attributes and methods of the specific object being worked with.',
                  'Refers to the current object.',
                  'OOP'
                );
              } else if (i === 11) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is a 'Closure' in programming?`,
                  ['A function that has access to its outer scope even after the outer function has returned', 'A way to close a program', 'A type of loop', 'A private class'],
                  0,
                  'Closures allow functions to "remember" the environment in which they were created.',
                  'Think about scope and functions.',
                  'Functions'
                );
              } else if (i === 12) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is a 'Mutable' object in ${lang}?`,
                  ['An object that can be changed after it is created', 'An object that cannot be changed', 'A type of function', 'A way to handle errors'],
                  0,
                  lang === 'Python' ? 'Lists and Dictionaries are mutable, while Tuples and Strings are immutable.' : 'Objects and Arrays are mutable in JavaScript.',
                  'Think about "changeable".',
                  'Data Types'
                );
              } else if (i === 13) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is the output of this ${lang} code?`,
                  lang === 'Python' ? ['[1, 4, 9, 16]', '[1, 2, 3, 4]', '[2, 4, 6, 8]', 'Error'] : ['[1, 4, 9, 16]', '[1, 2, 3, 4]', '[2, 4, 6, 8]', 'Error'],
                  0,
                  'This is a list comprehension (Python) or map (JS) that squares each number.',
                  'Multiply each number by itself.',
                  'Arrays',
                  'predict-output',
                  lang === 'Python' ? 'nums = [1, 2, 3, 4]\nsquares = [x**2 for x in nums]\nprint(squares)' : 'let nums = [1, 2, 3, 4];\nlet squares = nums.map(x => x**2);\nconsole.log(squares);'
                );
              } else if (i === 14) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What does the 'break' statement do in a loop?`,
                  ['Exits the loop immediately', 'Skips the current iteration', 'Restarts the loop', 'Slows down the loop'],
                  0,
                  'The break statement terminates the loop it is in.',
                  'Stop everything.',
                  'Loops'
                );
              } else if (i === 15) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is a 'Dictionary' (or Object) in ${lang}?`,
                  ['A collection of key-value pairs', 'A list of numbers', 'A type of function', 'A way to sort data'],
                  0,
                  'Dictionaries/Objects allow you to store data associated with unique keys.',
                  'Think about a real dictionary (word -> definition).',
                  'Data Types'
                );
              } else if (i === 16) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `How do you handle multiple exceptions in ${lang}?`,
                  lang === 'Python' ? ['Using multiple except blocks', 'Using one try block only', 'You cannot', 'Using an if statement'] : ['Using multiple catch blocks', 'Using one try block only', 'You cannot', 'Using an if statement'],
                  0,
                  'You can have multiple except blocks to handle different types of errors specifically.',
                  'Catching different mistakes.',
                  'Logic'
                );
              } else if (i === 17) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is 'Method Overriding'?`,
                  ['When a child class provides a specific implementation of a method already defined in its parent class', 'When a function calls itself', 'When a variable is renamed', 'When a class has two methods with the same name but different parameters'],
                  0,
                  'Overriding allows a child class to change the behavior of an inherited method.',
                  'Parent vs Child behavior.',
                  'OOP'
                );
              } else if (i === 18) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is the purpose of 'global' variables?`,
                  ['Variables that can be accessed from anywhere in the program', 'Variables that are only inside a function', 'Variables that are secret', 'Variables that never change'],
                  0,
                  'Global variables have a scope that spans the entire program.',
                  'Everywhere access.',
                  'Variables'
                );
              } else if (i === 19) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is a 'Lambda' function in ${lang}?`,
                  ['An anonymous, one-line function', 'A function that runs in the background', 'A type of class', 'A way to import modules'],
                  0,
                  'Lambdas are small, anonymous functions defined without a name.',
                  'Short and nameless.',
                  'Functions'
                );
              } else if (i === 20) {
                q = createQuestion(
                  `l3-${lang}-b${i}`,
                  `What is 'Static Method' in a class?`,
                  ['A method that belongs to the class rather than an instance of the class', 'A method that cannot be changed', 'A method that runs automatically', 'A method that only works with numbers'],
                  0,
                  'Static methods are called on the class itself, not on an object of the class.',
                  'Class-level vs Instance-level.',
                  'OOP'
                );
              } else {
                q = getFallbackQuestion(concept, lang, 3, track, i);
              }
            } else if (track === 'practice') {
                if (i === 1) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `Which of the following correctly implements a 'private' attribute in a class in ${lang}?`,
                    lang === 'Python' 
                      ? ['class User:\n  def __init__(self):\n    self.__name = "Alice"', 'class User:\n  def __init__(self):\n    self.name = "Alice"', 'class User:\n  private name = "Alice"', 'class User:\n  def __init__(self):\n    self._name = "Alice"']
                      : ['class User {\n  #name = "Alice";\n}', 'class User {\n  private name = "Alice";\n}', 'class User {\n  _name = "Alice";\n}', 'class User {\n  name: "Alice";\n}'],
                    0,
                    lang === 'Python' ? 'Python uses double underscores for name mangling to suggest privacy.' : 'Modern JavaScript uses the # prefix for truly private class fields.',
                    'Think about data hiding syntax.',
                    'OOP'
                  );
                } else if (i === 2) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is the purpose of 'super()' in a child class constructor?`,
                    ['To call the parent class constructor', 'To create a new object', 'To delete the object', 'To call a static method'],
                    0,
                    'super() is used to give access to methods and properties of a parent or sibling class.',
                    'Think about inheritance.',
                    'OOP'
                  );
                } else if (i === 3) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is the output of this code involving inheritance?`,
                    ['Animal speaks Dog barks', 'Animal speaks Animal speaks', 'Dog barks Dog barks', 'Error'],
                    0,
                    'The child class method overrides the parent class method.',
                    'Polymorphism in action.',
                    'OOP',
                    'predict-output',
                    lang === 'Python' ? 'class Animal:\n  def speak(self):\n    print("Animal speaks", end=" ")\nclass Dog(Animal):\n  def speak(self):\n    print("Dog barks")\nd = Dog()\nd.speak()' : 'class Animal {\n  speak() {\n    process.stdout.write("Animal speaks ");\n  }\n}\nclass Dog extends Animal {\n  speak() {\n    console.log("Dog barks");\n  }\n}\nlet d = new Dog();\nd.speak();'
                  );
                } else if (i === 4) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `Which of the following is the correct recursive implementation of a factorial function in ${lang}?`,
                    lang === 'Python' 
                      ? ['def fact(n):\n  if n == 0: return 1\n  return n * fact(n-1)', 'def fact(n):\n  return n * fact(n-1)', 'def fact(n):\n  if n == 0: return 0\n  return fact(n-1)', 'def fact(n):\n  return n * n']
                      : ['function fact(n) {\n  if (n === 0) return 1;\n  return n * fact(n - 1);\n}', 'function fact(n) {\n  return n * fact(n - 1);\n}', 'function fact(n) {\n  if (n === 0) return 0;\n  return fact(n - 1);\n}', 'function fact(n) {\n  return n * n;\n}'],
                    0,
                    'A recursive factorial function needs a base case (n=0 returns 1) and a recursive step (n * fact(n-1)).',
                    'Look for the base case and the recursive call.',
                    'Logic'
                  );
                } else if (i === 5) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `Which code snippet correctly uses a closure to create a counter in ${lang}?`,
                    lang === 'Python' 
                      ? ['def make_counter():\n  count = 0\n  def inc():\n    nonlocal count\n    count += 1\n    return count\n  return inc', 'def make_counter():\n  count = 0\n  def inc():\n    count += 1\n    return count\n  return inc', 'def make_counter():\n  global count\n  count = 0\n  return lambda: count + 1', 'count = 0\ndef inc():\n  return count + 1']
                      : ['function makeCounter() {\n  let count = 0;\n  return function() {\n    count++;\n    return count;\n  };\n}', 'function makeCounter() {\n  var count = 0;\n  return count++;\n}', 'let count = 0;\nfunction makeCounter() {\n  return count++;\n}', 'function makeCounter(count) {\n  return () => count++;\n}'],
                    0,
                    'A closure allows a function to access variables from its outer scope even after the outer function has finished executing.',
                    'Look for the nested function and the variable it captures.',
                    'Functions'
                  );
                } else if (i === 6) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `How do you handle a specific error like 'ZeroDivisionError' in ${lang}?`,
                    lang === 'Python' ? ['except ZeroDivisionError:', 'except Error:', 'catch ZeroDivisionError:', 'if error == 0:'] : ['catch (error) { if (error instanceof TypeError) ... }', 'catch ZeroDivisionError:', 'except ZeroDivisionError:', 'if error == 0:'],
                    0,
                    'Specific exception handling allows for better error recovery.',
                    'Catch the specific name.',
                    'Logic'
                  );
                } else if (i === 7) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is the output of this code involving a closure?`,
                    ['1 2', '1 1', '2 2', 'Error'],
                    0,
                    'The closure captures the counter variable, so it persists between calls.',
                    'State preservation.',
                    'Functions',
                    'predict-output',
                    lang === 'Python' ? 'def make_counter():\n  count = 0\n  def increment():\n    nonlocal count\n    count += 1\n    return count\n  return increment\nc = make_counter()\nprint(c(), c())' : 'function makeCounter() {\n  let count = 0;\n  return function() {\n    count++;\n    return count;\n  };\n}\nlet c = makeCounter();\nconsole.log(c(), c());'
                  );
                } else if (i === 8) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `Which of the following correctly defines an abstract method in ${lang}?`,
                    lang === 'Python' 
                      ? ['from abc import abstractmethod\n@abstractmethod\ndef area(self): pass', 'def area(self): abstract', 'abstract def area(self):', 'def area(self): pass']
                      : ['// JS uses classes that throw errors for abstraction\nclass Shape {\n  area() { throw new Error("Method must be implemented"); }\n}', 'abstract area() { }', 'function area() = 0;', 'area: abstract'],
                    0,
                    'Abstract methods are intended to be overridden by subclasses.',
                    'Look for the abstract keyword or pattern.',
                    'OOP'
                  );
                } else if (i === 9) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is the output of this code with multiple inheritance (Python) or mixins (JS)?`,
                    ['A B', 'A A', 'B B', 'Error'],
                    0,
                    'Multiple inheritance allows a class to inherit from more than one parent.',
                    'Combining behaviors.',
                    'OOP',
                    'predict-output',
                    lang === 'Python' ? 'class A: pass\nclass B: pass\nclass C(A, B): pass\nprint(C.__mro__)' : '// JS uses mixins or composition for multiple behaviors\nlet sayHiMixin = { sayHi() { console.log("Hi"); } };\nclass User { }\nObject.assign(User.prototype, sayHiMixin);\nnew User().sayHi();'
                  );
                } else if (i === 10) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `How do you create a 'Static' method in ${lang}?`,
                    lang === 'Python' ? ['Using @staticmethod decorator', 'Using static keyword', 'Using self', 'You cannot'] : ['Using static keyword', 'Using @staticmethod', 'Using this', 'You cannot'],
                    0,
                    'Static methods belong to the class, not an instance.',
                    'Class-level method.',
                    'OOP'
                  );
                } else if (i === 11) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is the output of this list comprehension with a condition?`,
                    ['[4, 16]', '[1, 4, 9, 16]', '[1, 9]', 'Error'],
                    0,
                    'The condition filters the list before applying the transformation.',
                    'Filter and Map.',
                    'Arrays',
                    'predict-output',
                    lang === 'Python' ? 'nums = [1, 2, 3, 4]\nevens = [x**2 for x in nums if x % 2 == 0]\nprint(evens)' : 'let nums = [1, 2, 3, 4];\nlet evens = nums.filter(x => x % 2 === 0).map(x => x**2);\nconsole.log(evens);'
                  );
                } else if (i === 12) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `How do you handle multiple exceptions in one block in ${lang}?`,
                    lang === 'Python' ? ['except (TypeError, ValueError):', 'except TypeError or ValueError:', 'catch [TypeError, ValueError]:', 'if error in [TypeError, ValueError]:'] : ['catch (error) { ... }', 'catch TypeError, ValueError:', 'except (TypeError, ValueError):', 'if error in [TypeError, ValueError]:'],
                    0,
                    'You can catch multiple exceptions by grouping them in a tuple (Python).',
                    'Grouping errors.',
                    'Logic'
                  );
                } else if (i === 13) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is the output of this code with 'global' variables?`,
                    ['20', '10', 'Error', 'None'],
                    0,
                    'The global keyword allows a function to modify a variable in the global scope.',
                    'Global scope modification.',
                    'Variables',
                    'predict-output',
                    lang === 'Python' ? 'x = 10\ndef change():\n  global x\n  x = 20\nchange()\nprint(x)' : 'let x = 10;\nfunction change() {\n  x = 20;\n}\nchange();\nconsole.log(x);'
                  );
                } else if (i === 14) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is a 'Generator' in Python? (In JS, think about Generator functions)`,
                    ['A function that returns an iterator using the yield keyword', 'A function that generates random numbers', 'A type of loop', 'A way to handle errors'],
                    0,
                    'Generators allow you to iterate over large datasets efficiently by yielding values one at a time.',
                    'Yielding values.',
                    'Functions'
                  );
                } else if (i === 15) {
                  q = createQuestion(
                    `l3-${lang}-p${i}`,
                    `What is 'Method Resolution Order' (MRO) in Python?`,
                    ['The order in which Python looks for a method in a hierarchy of classes', 'The order in which methods are defined', 'The order in which objects are created', 'A way to sort methods'],
                    0,
                    'MRO determines which implementation of a method to use in multiple inheritance.',
                    'Class hierarchy search.',
                    'OOP'
                  );
              } else {
                q = getFallbackQuestion(concept, lang, 3, track, i);
              }
            } else if (track === 'reinforcement') {
                  if (i === 1) {
                    q = createQuestion(
                      `l3-${lang}-r${i}`,
                      `What is the time complexity of accessing an element in an array by index?`,
                      ['O(1)', 'O(n)', 'O(log n)', 'O(n^2)'],
                      0,
                      'Accessing an element by index in an array is a constant time operation.',
                      'Think about direct memory access.',
                      'Arrays'
                    );
                  } else if (i === 2) {
                    q = createQuestion(
                      `l3-${lang}-r${i}`,
                      `Which of the following is NOT a valid way to iterate over a list in ${lang}?`,
                      lang === 'Python' ? ['for i in range(len(list)):', 'for item in list:', 'while i < len(list):', 'foreach(item in list):'] : ['for (let i = 0; i < list.length; i++)', 'list.forEach(item => ...)', 'for (let item of list)', 'list.mapEach(item => ...)'],
                      3,
                      'Standard iteration methods include for loops, while loops, and built-in iteration methods like forEach.',
                      'Look for the non-standard keyword.',
                      'Loops'
                    );
                  } else if (i === 3) {
                    q = createQuestion(
                      `l3-${lang}-r${i}`,
                      `What is the output of this code involving a decorator (Python) or higher-order function (JS)?`,
                      ['Before After', 'After Before', 'Before', 'Error'],
                      0,
                      'Decorators wrap a function, allowing you to run code before and after the original function.',
                      'Trace the wrapper execution.',
                      'Functions',
                      'predict-output',
                      lang === 'Python' ? 'def dec(f):\n  def wrap():\n    print("Before", end=" ")\n    f()\n    print("After")\n  return wrap\n@dec\ndef hi(): print("Hi", end=" ")\nhi()' : 'function dec(f) {\n  return function() {\n    process.stdout.write("Before ");\n    f();\n    console.log("After");\n  };\n}\nconst hi = dec(() => process.stdout.write("Hi "));\nhi();'
                    );
              } else {
                q = getFallbackQuestion(concept, lang, 3, track, i);
              }
              } else if (track === 'final') {
                  if (i === 1) {
                    q = createQuestion(
                      `l3-${lang}-f${i}`,
                      `What is the main advantage of using a 'Set' over a 'List' in ${lang}?`,
                      ['Sets automatically handle duplicate values', 'Sets are always sorted', 'Sets use less memory', 'Sets allow duplicate values'],
                      0,
                      'Sets are collections of unique elements, making them ideal for removing duplicates.',
                      'Think about uniqueness.',
                      'Data Types'
                    );
                  } else if (i === 2) {
                    q = createQuestion(
                      `l3-${lang}-f${i}`,
                      `Which of the following correctly implements a Singleton pattern in ${lang}?`,
                      lang === 'Python' ? ['Using a class variable to store the instance', 'Creating a new object every time', 'Using a global variable', 'Inheriting from multiple classes'] : ['Using a static property to store the single instance', 'Using a regular constructor', 'Using an array', 'Using a for loop'],
                      0,
                      'The Singleton pattern ensures a class has only one instance and provides a global point of access to it.',
                      'Think about unique instances.',
                      'OOP'
                    );
              } else {
                q = getFallbackQuestion(concept, lang, 3, track, i);
              }
              }
            }
            bank[levelNum][lang][track].push(q);
          }
        };

      addTrackQuestions('basics', 20, level);
      addTrackQuestions('practice', 15, level);
      addTrackQuestions('reinforcement', 10, level);
      addTrackQuestions('final', 10, level);
    });
  });

  return bank;
};

export const QUESTION_BANK: Record<LevelId, Record<ProgrammingLanguage, Record<TrackId, Question[]>>> = generateQuestions();
