'use client';

import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import { 
  InteractiveExamData, 
  InteractiveQuestion, 
  AdminQuizConfig, 
  BehaviorData,
  PersonalityProfile,
  InteractiveQuizResult,
  BehaviorMetric
} from '../types';

interface Question {
  id: string;
  question: string;
  options?: string[];
  correctAnswer?: number | string | string[];
}

interface ExamData {
  id: string;
  title: string;
  duration: number; // in minutes
  questions: Question[];
  passingGrade?: number;
  description?: string;
}

// Enhanced ExamData that supports both standard and interactive quizzes
interface EnhancedExamData extends ExamData {
  examType?: 'standard' | 'interactive';
  interactiveData?: InteractiveExamData;
  adminConfig?: AdminQuizConfig;
}

interface ExamState {
  examData: EnhancedExamData | null;
  currentQuestion: number;
  answers: Record<number, number | any>; // Enhanced to support various answer types
  flaggedQuestions: Set<number>;
  timeRemaining: number; // in seconds
  isSubmitted: boolean;
  showSubmitModal: boolean;
  
  // Interactive Quiz Enhancement: Behavior Tracking
  behaviorTracking: {
    enabled: boolean;
    sessionId: string;
    startTime: Date | null;
    behaviorData: Partial<BehaviorData>;
    currentMetrics: BehaviorMetric[];
  };
  
  // Interactive Quiz Enhancement: Interactive Elements State
  interactiveState: {
    currentQuestionType: 'mcq' | 'enhanced_mcq' | 'puzzle' | 'scenario' | 'simulation' | 'randomizer' | 'drag_drop' | 'puzzle_gambar_icon' | 'true_false_cepat' | 'mini_simulation_rpg' | 'mini_survey_reflection' | 'video_scenario' | 'image_hotspot' | 'media_gallery';
    dragDropState: Record<string, any>;
    puzzleState: Record<string, any>;
    scenarioState: Record<string, any>;
    confidenceRatings: Record<number, number>;
    hesitationTimes: Record<number, number>;
    answerChanges: Record<number, number>;
  };
  
  // Puzzle and Scenario States
  puzzleStates?: Record<number, any>;
  scenarioStates?: Record<number, any>;
  
  // Interactive Quiz Enhancement: Admin Configuration
  adminSettings: {
    config: AdminQuizConfig | null;
    enabledFeatures: string[];
    uiLanguage: 'indonesia' | 'english';
    personalityProfiling: boolean;
  };
  
  // Sprint 2 Enhancement: UI State Management
  ui: {
    showIntroModal: boolean;
    showResultsModal: boolean;
    feedbackVisible: boolean;
    isKeyboardUser: boolean;
  };
  
  // Sprint 2 Enhancement: Navigation State
  navigation: {
    questionStatuses: ('unanswered' | 'current' | 'answered')[];
    canNavigate: boolean;
    hasMinimumAnswers: boolean;
    navigationHistory: number[];
    questionViewMode: 'grid' | 'list';
    searchQuery: string;
    filterMode: 'all' | 'answered' | 'unanswered' | 'flagged' | 'bookmarked';
  };
  
  // Sprint 2 Enhancement: Autosave State
  autosave: {
    lastSaved: Date | null;
    isOnline: boolean;
    saveStatus: 'saved' | 'saving' | 'offline' | 'error';
    pendingChanges: boolean;
    saveError: string | null;
  };
  
  // Sprint 2 Enhancement: Accessibility State
  accessibility: {
    announcements: string[];
    highContrast: boolean;
    fontSize: 'small' | 'medium' | 'large';
  };
  
  // Sprint 2 Enhancement: Bookmarks
  bookmarkedQuestions: Set<number>;
}

type ExamAction =
  | { type: 'SET_EXAM_DATA'; payload: EnhancedExamData }
  | { type: 'SET_CURRENT_QUESTION'; payload: number }
  | { type: 'SET_ANSWER'; payload: { questionIndex: number; answer: number | any } }
  | { type: 'TOGGLE_FLAG'; payload: number }
  | { type: 'TICK_TIMER' }
  | { type: 'SUBMIT_EXAM' }
  | { type: 'SHOW_SUBMIT_MODAL'; payload: boolean }
  | { type: 'RESET_EXAM' }
  // Sprint 2 Enhancement: New Actions
  | { type: 'TOGGLE_BOOKMARK'; payload: number }
  | { type: 'SET_SAVE_STATUS'; payload: 'saved' | 'saving' | 'offline' | 'error' }
  | { type: 'SET_SAVE_ERROR'; payload: string | null }
  | { type: 'ADD_TO_HISTORY'; payload: number }
  | { type: 'SET_VIEW_MODE'; payload: 'grid' | 'list' }
  | { type: 'SET_SEARCH_QUERY'; payload: string }
  | { type: 'SET_FILTER_MODE'; payload: 'all' | 'answered' | 'unanswered' | 'flagged' | 'bookmarked' }
  | { type: 'SET_UI_STATE'; payload: Partial<ExamState['ui']> }
  | { type: 'SET_ACCESSIBILITY'; payload: Partial<ExamState['accessibility']> }
  // Interactive Quiz Enhancement: New Actions
  | { type: 'INIT_BEHAVIOR_TRACKING'; payload: { sessionId: string; metrics: BehaviorMetric[] } }
  | { type: 'UPDATE_BEHAVIOR_DATA'; payload: Partial<BehaviorData> }
  | { type: 'SET_INTERACTIVE_STATE'; payload: Partial<ExamState['interactiveState']> }
  | { type: 'SET_ADMIN_CONFIG'; payload: AdminQuizConfig }
  | { type: 'SET_CONFIDENCE_RATING'; payload: { questionIndex: number; rating: number } }
  | { type: 'TRACK_HESITATION'; payload: { questionIndex: number; duration: number } }
  | { type: 'TRACK_ANSWER_CHANGE'; payload: { questionIndex: number } }
  | { type: 'SET_DRAG_DROP_STATE'; payload: { questionId: string; state: any } }
  | { type: 'SET_PUZZLE_STATE'; payload: { questionId: string; state: any } }
  | { type: 'SET_SCENARIO_STATE'; payload: { questionId: string; state: any } };

const initialState: ExamState = {
  examData: null,
  currentQuestion: 0,
  answers: {},
  flaggedQuestions: new Set(),
  timeRemaining: 0,
  isSubmitted: false,
  showSubmitModal: false,
  
  // Interactive Quiz Enhancement: Initial Behavior Tracking State
  behaviorTracking: {
    enabled: false,
    sessionId: '',
    startTime: null,
    behaviorData: {},
    currentMetrics: [],
  },
  
  // Interactive Quiz Enhancement: Initial Interactive State
  interactiveState: {
    currentQuestionType: 'mcq',
    dragDropState: {},
    puzzleState: {},
    scenarioState: {},
    confidenceRatings: {},
    hesitationTimes: {},
    answerChanges: {},
  },
  
  // Interactive Quiz Enhancement: Initial Admin Settings
  adminSettings: {
    config: null,
    enabledFeatures: [],
    uiLanguage: 'indonesia',
    personalityProfiling: false,
  },
  
  // Sprint 2 Enhancement: Initial UI State
  ui: {
    showIntroModal: false,
    showResultsModal: false,
    feedbackVisible: false,
    isKeyboardUser: false,
  },
  
  // Sprint 2 Enhancement: Initial Navigation State
  navigation: {
    questionStatuses: [],
    canNavigate: true,
    hasMinimumAnswers: false,
    navigationHistory: [],
    questionViewMode: 'grid',
    searchQuery: '',
    filterMode: 'all',
  },
  
  // Sprint 2 Enhancement: Initial Autosave State
  autosave: {
    lastSaved: null,
    isOnline: true,
    saveStatus: 'saved',
    pendingChanges: false,
    saveError: null,
  },
  
  // Sprint 2 Enhancement: Initial Accessibility State
  accessibility: {
    announcements: [],
    highContrast: false,
    fontSize: 'medium',
  },
  
  // Sprint 2 Enhancement: Initial Bookmarks
  bookmarkedQuestions: new Set(),
};

function examReducer(state: ExamState, action: ExamAction): ExamState {
  switch (action.type) {
    case 'SET_EXAM_DATA':
      return {
        ...state,
        examData: action.payload,
        timeRemaining: action.payload.duration * 60, // convert minutes to seconds
      };
    
    case 'SET_CURRENT_QUESTION':
      return {
        ...state,
        currentQuestion: action.payload,
      };
    
    case 'SET_ANSWER':
      return {
        ...state,
        answers: {
          ...state.answers,
          [action.payload.questionIndex]: action.payload.answer,
        },
      };
    
    case 'TOGGLE_FLAG':
      const newFlaggedQuestions = new Set(state.flaggedQuestions);
      if (newFlaggedQuestions.has(action.payload)) {
        newFlaggedQuestions.delete(action.payload);
      } else {
        newFlaggedQuestions.add(action.payload);
      }
      return {
        ...state,
        flaggedQuestions: newFlaggedQuestions,
      };
    
    case 'TICK_TIMER':
      const newTimeRemaining = Math.max(0, state.timeRemaining - 1);
      return {
        ...state,
        timeRemaining: newTimeRemaining,
        isSubmitted: newTimeRemaining === 0 ? true : state.isSubmitted,
      };
    
    case 'SUBMIT_EXAM':
      return {
        ...state,
        isSubmitted: true,
      };
    
    case 'SHOW_SUBMIT_MODAL':
      return {
        ...state,
        showSubmitModal: action.payload,
      };
    
    case 'RESET_EXAM':
      return initialState;
    
    // Sprint 2 Enhancement: New Reducer Cases
    case 'TOGGLE_BOOKMARK':
      const newBookmarkedQuestions = new Set(state.bookmarkedQuestions);
      if (newBookmarkedQuestions.has(action.payload)) {
        newBookmarkedQuestions.delete(action.payload);
      } else {
        newBookmarkedQuestions.add(action.payload);
      }
      return {
        ...state,
        bookmarkedQuestions: newBookmarkedQuestions,
      };
    
    case 'SET_SAVE_STATUS':
      return {
        ...state,
        autosave: {
          ...state.autosave,
          saveStatus: action.payload,
          lastSaved: action.payload === 'saved' ? new Date() : state.autosave.lastSaved,
        },
      };
    
    case 'SET_SAVE_ERROR':
      return {
        ...state,
        autosave: {
          ...state.autosave,
          saveError: action.payload,
          saveStatus: action.payload ? 'error' : state.autosave.saveStatus,
        },
      };
    
    case 'ADD_TO_HISTORY':
      const newHistory = [...state.navigation.navigationHistory];
      if (newHistory[newHistory.length - 1] !== action.payload) {
        newHistory.push(action.payload);
        // Keep only last 10 items in history
        if (newHistory.length > 10) {
          newHistory.shift();
        }
      }
      return {
        ...state,
        navigation: {
          ...state.navigation,
          navigationHistory: newHistory,
        },
      };
    
    case 'SET_VIEW_MODE':
      return {
        ...state,
        navigation: {
          ...state.navigation,
          questionViewMode: action.payload,
        },
      };
    
    case 'SET_SEARCH_QUERY':
      return {
        ...state,
        navigation: {
          ...state.navigation,
          searchQuery: action.payload,
        },
      };
    
    case 'SET_FILTER_MODE':
      return {
        ...state,
        navigation: {
          ...state.navigation,
          filterMode: action.payload,
        },
      };
    
    case 'SET_UI_STATE':
      return {
        ...state,
        ui: {
          ...state.ui,
          ...action.payload,
        },
      };
    
    case 'SET_ACCESSIBILITY':
      return {
        ...state,
        accessibility: {
          ...state.accessibility,
          ...action.payload,
        },
      };
    
    // Interactive Quiz Enhancement: New Reducer Cases
    case 'INIT_BEHAVIOR_TRACKING':
      return {
        ...state,
        behaviorTracking: {
          ...state.behaviorTracking,
          enabled: true,
          sessionId: action.payload.sessionId,
          startTime: new Date(),
          currentMetrics: action.payload.metrics,
          behaviorData: {
            sessionId: action.payload.sessionId,
            userId: '', // Will be set from context
            examId: state.examData?.id || '',
            startTime: new Date(),
            totalTime: 0,
            timePerQuestion: [],
            pauseDurations: [],
            clickEvents: [],
            scrollEvents: [],
            focusEvents: [],
            answerChanges: [],
            hesitationPoints: [],
            confidenceLevels: [],
            rapidClicking: false,
            excessiveScrolling: false,
            longPauses: false,
            accuracyOverTime: [],
            difficultyResponse: [],
          },
        },
      };
    
    case 'UPDATE_BEHAVIOR_DATA':
      return {
        ...state,
        behaviorTracking: {
          ...state.behaviorTracking,
          behaviorData: {
            ...state.behaviorTracking.behaviorData,
            ...action.payload,
          },
        },
      };
    
    case 'SET_INTERACTIVE_STATE':
      return {
        ...state,
        interactiveState: {
          ...state.interactiveState,
          ...action.payload,
        },
      };
    
    case 'SET_ADMIN_CONFIG':
      return {
        ...state,
        adminSettings: {
          ...state.adminSettings,
          config: action.payload,
          enabledFeatures: action.payload.enabledFeatures ? Object.entries(action.payload.enabledFeatures)
            .filter(([_, enabled]) => enabled)
            .map(([feature, _]) => feature) : [],
          uiLanguage: action.payload.uiSettings?.language || 'indonesia',
          personalityProfiling: action.payload.customSettings?.generatePersonalityReport || false,
        },
      };
    
    case 'SET_CONFIDENCE_RATING':
      return {
        ...state,
        interactiveState: {
          ...state.interactiveState,
          confidenceRatings: {
            ...state.interactiveState.confidenceRatings,
            [action.payload.questionIndex]: action.payload.rating,
          },
        },
      };
    
    case 'TRACK_HESITATION':
      return {
        ...state,
        interactiveState: {
          ...state.interactiveState,
          hesitationTimes: {
            ...state.interactiveState.hesitationTimes,
            [action.payload.questionIndex]: action.payload.duration,
          },
        },
      };
    
    case 'TRACK_ANSWER_CHANGE':
      return {
        ...state,
        interactiveState: {
          ...state.interactiveState,
          answerChanges: {
            ...state.interactiveState.answerChanges,
            [action.payload.questionIndex]: (state.interactiveState.answerChanges[action.payload.questionIndex] || 0) + 1,
          },
        },
      };
    
    case 'SET_DRAG_DROP_STATE':
      return {
        ...state,
        interactiveState: {
          ...state.interactiveState,
          dragDropState: {
            ...state.interactiveState.dragDropState,
            [action.payload.questionId]: action.payload.state,
          },
        },
      };
    
    case 'SET_PUZZLE_STATE':
      return {
        ...state,
        interactiveState: {
          ...state.interactiveState,
          puzzleState: {
            ...state.interactiveState.puzzleState,
            [action.payload.questionId]: action.payload.state,
          },
        },
      };
    
    case 'SET_SCENARIO_STATE':
      return {
        ...state,
        interactiveState: {
          ...state.interactiveState,
          scenarioState: {
            ...state.interactiveState.scenarioState,
            [action.payload.questionId]: action.payload.state,
          },
        },
      };

    default:
      return state;
  }
}

interface ExamContextType {
  state: ExamState;
  dispatch: React.Dispatch<ExamAction>;
  // Helper functions
  setExamData: (examData: EnhancedExamData) => void;
  goToQuestion: (questionIndex: number) => void;
  selectAnswer: (questionIndex: number, answer: number | any) => void;
  toggleFlag: (questionIndex: number) => void;
  submitExam: () => void;
  resetExam: () => void;
  
  // Sprint 2 Enhancement: New Helper Functions
  toggleBookmark: (questionIndex: number) => void;
  setSaveStatus: (status: 'saved' | 'saving' | 'offline' | 'error') => void;
  setSaveError: (error: string | null) => void;
  addToHistory: (questionIndex: number) => void;
  setViewMode: (mode: 'grid' | 'list') => void;
  setSearchQuery: (query: string) => void;
  setFilterMode: (mode: 'all' | 'answered' | 'unanswered' | 'flagged' | 'bookmarked') => void;
  setUIState: (state: Partial<ExamState['ui']>) => void;
  setAccessibility: (settings: Partial<ExamState['accessibility']>) => void;
  
  // Interactive Quiz Enhancement: New Helper Functions
  initBehaviorTracking: (sessionId: string, metrics: BehaviorMetric[]) => void;
  updateBehaviorData: (data: Partial<BehaviorData>) => void;
  setInteractiveState: (state: Partial<ExamState['interactiveState']>) => void;
  setAdminConfig: (config: AdminQuizConfig) => void;
  setConfidenceRating: (questionIndex: number, rating: number) => void;
  trackHesitation: (questionIndex: number, duration: number) => void;
  trackAnswerChange: (questionIndex: number) => void;
  setDragDropState: (questionId: string, state: any) => void;
  setPuzzleState: (questionId: string, state: any) => void;
  setScenarioState: (questionId: string, state: any) => void;
  
  // Computed values
  answeredCount: number;
  flaggedCount: number;
  progressPercentage: number;
  formattedTimeRemaining: string;
  
  // Sprint 2 Enhancement: New Computed Values
  bookmarkedCount: number;
  filteredQuestions: number[];
  canSubmit: boolean;
  hasUnsavedChanges: boolean;
  
  // Interactive Quiz Enhancement: New Computed Values
  isInteractiveQuiz: boolean;
  currentQuestionType: string;
  behaviorTrackingEnabled: boolean;
  adminLanguage: 'indonesia' | 'english';
}

const ExamContext = createContext<ExamContextType | undefined>(undefined);

export function ExamProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(examReducer, initialState);

  // Timer effect
  useEffect(() => {
    if (state.timeRemaining > 0 && !state.isSubmitted) {
      const timer = setInterval(() => {
        dispatch({ type: 'TICK_TIMER' });
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [state.timeRemaining, state.isSubmitted]);

  // Helper functions
  const setExamData = (examData: EnhancedExamData) => {
    dispatch({ type: 'SET_EXAM_DATA', payload: examData });
  };

  const goToQuestion = (questionIndex: number) => {
    dispatch({ type: 'SET_CURRENT_QUESTION', payload: questionIndex });
  };

  const selectAnswer = (questionIndex: number, answer: number | any) => {
    dispatch({ type: 'SET_ANSWER', payload: { questionIndex, answer } });
  };

  const toggleFlag = (questionIndex: number) => {
    dispatch({ type: 'TOGGLE_FLAG', payload: questionIndex });
  };

  const submitExam = () => {
    dispatch({ type: 'SUBMIT_EXAM' });
  };

  const resetExam = () => {
    dispatch({ type: 'RESET_EXAM' });
  };

  // Sprint 2 Enhancement: New Helper Functions
  const toggleBookmark = (questionIndex: number) => {
    dispatch({ type: 'TOGGLE_BOOKMARK', payload: questionIndex });
  };

  const setSaveStatus = (status: 'saved' | 'saving' | 'offline' | 'error') => {
    dispatch({ type: 'SET_SAVE_STATUS', payload: status });
  };

  const setSaveError = (error: string | null) => {
    dispatch({ type: 'SET_SAVE_ERROR', payload: error });
  };

  const addToHistory = (questionIndex: number) => {
    dispatch({ type: 'ADD_TO_HISTORY', payload: questionIndex });
  };

  const setViewMode = (mode: 'grid' | 'list') => {
    dispatch({ type: 'SET_VIEW_MODE', payload: mode });
  };

  const setSearchQuery = (query: string) => {
    dispatch({ type: 'SET_SEARCH_QUERY', payload: query });
  };

  const setFilterMode = (mode: 'all' | 'answered' | 'unanswered' | 'flagged' | 'bookmarked') => {
    dispatch({ type: 'SET_FILTER_MODE', payload: mode });
  };

  const setUIState = (uiState: Partial<ExamState['ui']>) => {
    dispatch({ type: 'SET_UI_STATE', payload: uiState });
  };

  const setAccessibility = (settings: Partial<ExamState['accessibility']>) => {
    dispatch({ type: 'SET_ACCESSIBILITY', payload: settings });
  };

  // Interactive Quiz Enhancement: New Helper Functions
  const initBehaviorTracking = (sessionId: string, metrics: BehaviorMetric[]) => {
    dispatch({ type: 'INIT_BEHAVIOR_TRACKING', payload: { sessionId, metrics } });
  };

  const updateBehaviorData = (data: Partial<BehaviorData>) => {
    dispatch({ type: 'UPDATE_BEHAVIOR_DATA', payload: data });
  };

  const setInteractiveState = (interactiveState: Partial<ExamState['interactiveState']>) => {
    dispatch({ type: 'SET_INTERACTIVE_STATE', payload: interactiveState });
  };

  const setAdminConfig = (config: AdminQuizConfig) => {
    dispatch({ type: 'SET_ADMIN_CONFIG', payload: config });
  };

  const setConfidenceRating = (questionIndex: number, rating: number) => {
    dispatch({ type: 'SET_CONFIDENCE_RATING', payload: { questionIndex, rating } });
  };

  const trackHesitation = (questionIndex: number, duration: number) => {
    dispatch({ type: 'TRACK_HESITATION', payload: { questionIndex, duration } });
  };

  const trackAnswerChange = (questionIndex: number) => {
    dispatch({ type: 'TRACK_ANSWER_CHANGE', payload: { questionIndex } });
  };

  const setDragDropState = (questionId: string, dragDropState: any) => {
    dispatch({ type: 'SET_DRAG_DROP_STATE', payload: { questionId, state: dragDropState } });
  };

  const setPuzzleState = (questionId: string, puzzleState: any) => {
    dispatch({ type: 'SET_PUZZLE_STATE', payload: { questionId, state: puzzleState } });
  };

  const setScenarioState = (questionId: string, scenarioState: any) => {
    dispatch({ type: 'SET_SCENARIO_STATE', payload: { questionId, state: scenarioState } });
  };

  // Computed values
  const answeredCount = Object.keys(state.answers).length;
  const flaggedCount = state.flaggedQuestions.size;
  const progressPercentage = state.examData 
    ? (answeredCount / state.examData.questions.length) * 100 
    : 0;

  const formattedTimeRemaining = (() => {
    const hours = Math.floor(state.timeRemaining / 3600);
    const minutes = Math.floor((state.timeRemaining % 3600) / 60);
    const seconds = state.timeRemaining % 60;
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  })();

  // Sprint 2 Enhancement: New Computed Values
  const bookmarkedCount = state.bookmarkedQuestions.size;
  
  const filteredQuestions = (() => {
    if (!state.examData) return [];
    
    const questionIndices = Array.from({ length: state.examData.questions.length }, (_, i) => i);
    
    return questionIndices.filter(index => {
      const isAnswered = index in state.answers;
      const isFlagged = state.flaggedQuestions.has(index);
      const isBookmarked = state.bookmarkedQuestions.has(index);
      
      switch (state.navigation.filterMode) {
        case 'answered':
          return isAnswered;
        case 'unanswered':
          return !isAnswered;
        case 'flagged':
          return isFlagged;
        case 'bookmarked':
          return isBookmarked;
        default:
          return true;
      }
    });
  })();

  const canSubmit = state.examData ? answeredCount >= Math.ceil(state.examData.questions.length * 0.5) : false;
  const hasUnsavedChanges = state.autosave.pendingChanges;

  // Interactive Quiz Enhancement: New Computed Values
  const isInteractiveQuiz = state.examData?.examType === 'interactive';
  const currentQuestionType = state.interactiveState.currentQuestionType;
  const behaviorTrackingEnabled = false; // Disabled for now
  const adminLanguage = state.adminSettings.uiLanguage;

  const contextValue: ExamContextType = {
    state,
    dispatch,
    setExamData,
    goToQuestion,
    selectAnswer,
    toggleFlag,
    submitExam,
    resetExam,
    // Sprint 2 helper functions
    toggleBookmark,
    setSaveStatus,
    setSaveError,
    addToHistory,
    setViewMode,
    setSearchQuery,
    setFilterMode,
    setUIState,
    setAccessibility,
    // Interactive Quiz Enhancement: New helper functions
    initBehaviorTracking,
    updateBehaviorData,
    setInteractiveState,
    setAdminConfig,
    setConfidenceRating,
    trackHesitation,
    trackAnswerChange,
    setDragDropState,
    setPuzzleState,
    setScenarioState,
    // Original computed values
    answeredCount,
    flaggedCount,
    progressPercentage,
    formattedTimeRemaining,
    // Sprint 2 computed values
    bookmarkedCount,
    filteredQuestions,
    canSubmit,
    hasUnsavedChanges,
    // Interactive Quiz Enhancement: New computed values
    isInteractiveQuiz,
    currentQuestionType,
    behaviorTrackingEnabled,
    adminLanguage,
  };

  return (
    <ExamContext.Provider value={contextValue}>
      {children}
    </ExamContext.Provider>
  );
}

export function useExam() {
  const context = useContext(ExamContext);
  if (context === undefined) {
    throw new Error('useExam must be used within an ExamProvider');
  }
  return context;
}

export type { ExamData, Question, ExamState };