Now it's just finishing the session instead of going over the incorrectly answered: Navigated to http://localhost:8000/C:/Desktop/web/
lockdown-install.js:1 Removing unpermitted intrinsics
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 0
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '5 × 6', feedbackIndex: 0}
gameLogic.js:23 [DEBUG] Generated new problems during session initialization.
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 0
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '5 × 6', feedbackIndex: 0}
gameLogic.js:23 [DEBUG] Session initialized. Displaying first problem.
settings.js:192 [DEBUG] Settings initialized. {}
settings.js:192 [DEBUG] Settings loaded successfully. {mode: 'addition', selectedNumerators: Array(11), selectedDenominators: Array(11)}
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 0
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '11 + 10', feedbackIndex: 0}
eventHandlers.js:14 Initializing event handlers...
settings.js:192 [DEBUG] Settings loaded successfully. {mode: 'addition', selectedNumerators: Array(11), selectedDenominators: Array(11)}
eventHandlers.js:19 Enter key pressed. Submitting answer...
gameLogic.js:23 [DEBUG] Checking answer for problem: {problem: '11 + 10', userAnswer: 21, correctAnswer: 21}
gameLogic.js:23 [DEBUG] Correct answer provided. {problem: {…}}
gameLogic.js:23 [DEBUG] Attempted to remove problem not found in incorrectProblems: {id: undefined}
gameLogic.js:23 [DEBUG] Moving to next problem. New currentProblemIndex: 1
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 1
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '8 + 7', feedbackIndex: 1}
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 1
gameLogic.js:23 [DEBUG] Input field re-enabled and focused after moving to next problem.
eventHandlers.js:19 Enter key pressed. Submitting answer...
gameLogic.js:23 [DEBUG] Checking answer for problem: {problem: '8 + 7', userAnswer: 15, correctAnswer: 15}
gameLogic.js:23 [DEBUG] Correct answer provided. {problem: {…}}
gameLogic.js:23 [DEBUG] Attempted to remove problem not found in incorrectProblems: {id: undefined}
gameLogic.js:23 [DEBUG] Moving to next problem. New currentProblemIndex: 2
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 2
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '11 + 10', feedbackIndex: 2}
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 2
gameLogic.js:23 [DEBUG] Input field re-enabled and focused after moving to next problem.
eventHandlers.js:19 Enter key pressed. Submitting answer...
gameLogic.js:23 [DEBUG] Checking answer for problem: {problem: '11 + 10', userAnswer: 21, correctAnswer: 21}
gameLogic.js:23 [DEBUG] Correct answer provided. {problem: {…}}
gameLogic.js:23 [DEBUG] Attempted to remove problem not found in incorrectProblems: {id: undefined}
gameLogic.js:23 [DEBUG] Moving to next problem. New currentProblemIndex: 3
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 3
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '3 + 5', feedbackIndex: 3}
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 3
gameLogic.js:23 [DEBUG] Input field re-enabled and focused after moving to next problem.
eventHandlers.js:19 Enter key pressed. Submitting answer...
gameLogic.js:23 [DEBUG] Checking answer for problem: {problem: '3 + 5', userAnswer: 1, correctAnswer: 8}
gameLogic.js:23 [DEBUG] Problem added to incorrectProblems. {problem: {…}}
gameLogic.js:23 [DEBUG] Incorrect answer provided. {correctAnswer: 8, problem: '3 + 5'}
gameLogic.js:23 [DEBUG] Updated problemElement innerHTML: 3 + 5 = <span class="correct-answer">8</span>
eventHandlers.js:19 Enter key pressed. Submitting answer...
gameLogic.js:23 [DEBUG] Checking answer for problem: {problem: '3 + 5', userAnswer: null, correctAnswer: 8}
gameLogic.js:23 [DEBUG] Invalid input: User answer is not a number. {userInput: ''}
gameLogic.js:23 [DEBUG] Invalid input feedback displayed.
gameLogic.js:23 [DEBUG] Input field reset for next problem.
gameLogic.js:23 [DEBUG] Moving to next problem. New currentProblemIndex: 4
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 4
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '6 + 4', feedbackIndex: 4}
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 4
gameLogic.js:23 [DEBUG] Input field re-enabled and focused after moving to next problem.
eventHandlers.js:19 Enter key pressed. Submitting answer...
gameLogic.js:23 [DEBUG] Checking answer for problem: {problem: '6 + 4', userAnswer: 10, correctAnswer: 10}
gameLogic.js:23 [DEBUG] Correct answer provided. {problem: {…}}
gameLogic.js:23 [DEBUG] Problem removed from incorrectProblems: {id: undefined}
gameLogic.js:23 [DEBUG] Moving to next problem. New currentProblemIndex: 5
gameLogic.js:23 [DEBUG] All problems answered correctly. Finishing session.
gameLogic.js:23 [DEBUG] Finishing session. Remaining incorrect problems: [{…}]
gameLogic.js:23 [DEBUG] Creating feedback boxes for incorrect problems.
gameLogic.js:23 [DEBUG] Feedback box created for problem: {num1: 3, num2: 5, answer: 8, correctAnswers: 0, incorrectAnswers: 1, …}
gameLogic.js:23 [DEBUG] Session finished. Only incorrect problems saved to local storage.
gameLogic.js:23 [DEBUG] Hiding feedback boxes. Total feedback boxes: 1 Incorrect count: 1
gameLogic.js:23 [DEBUG] Displaying feedback box at index 0.
gameLogic.js:23 [DEBUG] Final state of feedback boxes after hiding/showing:
gameLogic.js:23 [DEBUG] Feedback box 0: Display = block
gameLogic.js:23 [DEBUG] Input box has been reset and focused after session end.
gameLogic.js:23 [DEBUG] Highlighted feedback box at index: 0
gameLogic.js:23 [DEBUG] Displaying problem: {problem: '10 + 9', feedbackIndex: 0}
gameLogic.js:23 [DEBUG] Regenerating problems after session end.

// Import necessary modules and functions
import { 
    state, 
    saveProblemsToLocalStorage, 
    updateStatistics 
} from './state.js';
import { elements } from './elements.js';
import { generateProblems, 
    createFeedbackBox 
} from './problemGeneration.js';
import { debugMode } from './settings.js';

// Constants
const FEEDBACK_DISPLAY_DURATION = 500; // milliseconds
const ENTER_KEY = 'Enter';

// Flags to manage state transitions
let isMovingToNextProblem = false;

// Helper function to log debugging information based on debugMode
const logDebug = (message, ...data) => {
    if (debugMode) {
        console.debug(`[DEBUG] ${message}`, ...data);
    }
};

// Utility function to safely parse user input
const parseUserAnswer = (input) => {
    const parsed = parseInt(input, 10);
    return isNaN(parsed) ? null : parsed;
};

// Function to display feedback (✓ or ✗) with appropriate styling
const displayFeedback = (resultSymbol, resultClass, feedbackBox) => {
    if (!feedbackBox) {
        logDebug('Error: Feedback box is not found.');
        return;
    }

    feedbackBox.innerHTML = `<span class="${resultClass}">${resultSymbol}</span>`;

    // Ensure the symbol is centered
    const symbolSpan = feedbackBox.querySelector(`.${resultClass}`);
    if (symbolSpan) {
        Object.assign(symbolSpan.style, {
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
        });
    }

    setTimeout(() => {
        feedbackBox.classList.remove('correct-symbol', 'incorrect-symbol');
    }, FEEDBACK_DISPLAY_DURATION);
};

// Function to handle answer checking and feedback
export const checkAnswer = () => {
    const userInput = elements.answerInput.value.trim();
    const userAnswer = parseUserAnswer(userInput);
    const currentProblem = state.problems[state.currentProblemIndex];

    if (!currentProblem) {
        logDebug('Error: Current problem is undefined.');
        return;
    }

    const feedbackBox = elements.feedbackBoxes.children[currentProblem.feedbackIndex] || elements.feedbackBoxes.children[state.currentProblemIndex];
    currentProblem.feedbackIndex = currentProblem.feedbackIndex || state.currentProblemIndex;

    logDebug('Checking answer for problem:', {
        problem: `${currentProblem.num1} ${state.isMultiplication ? '×' : '+'} ${currentProblem.num2}`,
        userAnswer,
        correctAnswer: currentProblem.answer
    });

    if (userAnswer === null) {
        logDebug('Invalid input: User answer is not a number.', { userInput });
        // Provide user feedback for invalid input
        displayInvalidInputFeedback();
        return;
    }

    // Disable the input while processing the answer
    elements.answerInput.readOnly = true;

    if (userAnswer === currentProblem.answer) {
        handleCorrectAnswer(currentProblem, feedbackBox);
    } else {
        handleIncorrectAnswer(currentProblem, feedbackBox);
    }
};

// Handle correct answers
const handleCorrectAnswer = (problem, feedbackBox) => {
    problem.answeredIncorrectly = false;
    problem.correctAnswers += 1;
    state.correctAnswers += 1;
    state.totalPoints += 1;

    const resultSymbol = '✓';  // Check mark
    const resultClass = 'correct-symbol';
    feedbackBox.classList.add(resultClass);

    logDebug('Correct answer provided.', { problem });

    displayFeedback(resultSymbol, resultClass, feedbackBox);
    removeFromIncorrectProblems(problem.id); // Use unique ID for removal
    moveToNextProblem();
};

// Handle incorrect answers
const handleIncorrectAnswer = (problem, feedbackBox) => {
    problem.answeredIncorrectly = true;
    problem.incorrectAnswers += 1;
    state.incorrectAnswers += 1;

    const resultSymbol = '✗';  // X mark
    const resultClass = 'incorrect-symbol';

    if (!state.incorrectProblems.some(p => p.id === problem.id)) {
        state.incorrectProblems.push(problem);
        logDebug('Problem added to incorrectProblems.', { problem });
    } else {
        logDebug('Problem already in incorrectProblems.', { problem });
    }

    logDebug('Incorrect answer provided.', {
        correctAnswer: problem.answer,
        problem: `${problem.num1} ${state.isMultiplication ? '×' : '+'} ${problem.num2}`
    });

    // Display correct answer next to the equation
    displayCorrectAnswer(problem);

    displayFeedback(resultSymbol, resultClass, feedbackBox);

    // Prepare input for the next action
    elements.answerInput.value = '';
    elements.answerInput.placeholder = 'Press Enter to continue';

    const handleEnterPress = (e) => {
        if (e.key === ENTER_KEY) {
            elements.answerInput.removeEventListener('keypress', handleEnterPress);
            resetInputForNextProblem();
            moveToNextProblem();
        }
    };

    // Ensure no duplicate listeners
    elements.answerInput.removeEventListener('keypress', handleEnterPress);
    elements.answerInput.addEventListener('keypress', handleEnterPress);
};

// Function to display the correct answer next to the problem
const displayCorrectAnswer = (problem) => {
    try {
        const problemElement = document.getElementById('problem');
        if (problemElement) {
            const operator = state.isMultiplication ? '×' : '+';
            problemElement.innerHTML = `${problem.num1} ${operator} ${problem.num2} = <span class="correct-answer">${problem.answer}</span>`;
            logDebug('Updated problemElement innerHTML:', problemElement.innerHTML);
        } else {
            logDebug('Error: problemElement is null or undefined');
        }
    } catch (error) {
        logDebug('Error displaying correct answer:', error);
    }
};

// Function to display feedback for invalid inputs
const displayInvalidInputFeedback = () => {
    // Implement visual feedback for invalid inputs
    // For example, shaking the input box or displaying an error message
    elements.answerInput.classList.add('invalid-input');
    logDebug('Invalid input feedback displayed.');
    setTimeout(() => {
        elements.answerInput.classList.remove('invalid-input');
    }, FEEDBACK_DISPLAY_DURATION);
};

// Function to reset input field for the next problem
const resetInputForNextProblem = () => {
    elements.answerInput.readOnly = false;
    elements.answerInput.value = '';
    elements.answerInput.placeholder = '';
    elements.answerInput.focus();
    logDebug('Input field reset for next problem.');
};

// Function to remove a problem from the incorrectProblems list using unique ID
const removeFromIncorrectProblems = (problemId) => {
    const index = state.incorrectProblems.findIndex(p => p.id === problemId);
    if (index !== -1) {
        state.incorrectProblems.splice(index, 1);
        logDebug('Problem removed from incorrectProblems:', { id: problemId });
    } else {
        logDebug('Attempted to remove problem not found in incorrectProblems:', { id: problemId });
    }
};

// Function to move to the next problem
export const moveToNextProblem = () => {
    if (isMovingToNextProblem) {
        logDebug('Already moving to the next problem. Exiting moveToNextProblem.');
        return;  // Prevent multiple simultaneous transitions
    }
    isMovingToNextProblem = true;

    // Disable input during the transition
    elements.answerInput.readOnly = true;

    state.currentProblemIndex++;

    logDebug('Moving to next problem. New currentProblemIndex:', state.currentProblemIndex);

    // Check if we have reached the end of current problems
    if (state.currentProblemIndex >= state.problems.length) {
        if (state.incorrectProblems.length > 0) {
            state.problems = [...state.incorrectProblems];
            logDebug('Reassigning state.problems to incorrectProblems:', state.problems);
            // Do NOT reset incorrectProblems here to maintain tracking
            state.currentProblemIndex = 0;
            logDebug('Reset currentProblemIndex to 0 for incorrectProblems.');
        } else {
            logDebug('All problems answered correctly. Finishing session.');
            finishSession();
            isMovingToNextProblem = false;
            return;
        }
    }

    if (state.currentProblemIndex < state.problems.length) {
        displayProblem();

        // Highlight the feedback box for the current problem
        const feedbackIndex = state.problems[state.currentProblemIndex].feedbackIndex || state.currentProblemIndex;
        const feedbackBox = elements.feedbackBoxes.children[feedbackIndex];
        if (feedbackBox) {
            feedbackBox.classList.add('highlighted-problem');
            logDebug('Highlighted feedback box at index:', feedbackIndex);
        } else {
            logDebug('Error: Feedback box not found for the current problem index:', feedbackIndex);
        }

    } else {
        finishSession();
    }

    // Re-enable input after transition completes
    setTimeout(() => {
        isMovingToNextProblem = false;
        elements.answerInput.readOnly = false;
        elements.answerInput.focus();
        logDebug('Input field re-enabled and focused after moving to next problem.');
    }, FEEDBACK_DISPLAY_DURATION);
};

// Function to finish the session and handle incorrect problems
export const finishSession = () => {
    try {
        // Retain only the problems that were answered incorrectly
        const remainingIncorrect = state.problems.filter(problem => problem.answeredIncorrectly);
        logDebug('Finishing session. Remaining incorrect problems:', remainingIncorrect);
        state.problems = remainingIncorrect;

        // Clear existing feedback boxes and recreate for incorrect problems
        elements.feedbackBoxes.innerHTML = '';
        if (state.problems.length > 0) {
            logDebug('Creating feedback boxes for incorrect problems.');
            state.problems.forEach(problem => {
                createFeedbackBox(problem.feedbackIndex);
                logDebug('Feedback box created for problem:', problem);
            });
        } else {
            logDebug('All problems were answered correctly. Session finished.');
        }

        saveProblemsToLocalStorage(state.problems);
        logDebug('Session finished. Only incorrect problems saved to local storage.');
        updateStatistics();

        // Hide all feedback boxes except those for incorrect problems
        hideAllFeedbackBoxesExceptIncorrect();

        // Ensure the input box is enabled and focused for the next session
        resetInputAfterSession();

        // Optionally regenerate problems after finishing
        setTimeout(() => {
            generateProblems();
            logDebug('Regenerating problems after session end.');
        }, 100);
    } catch (error) {
        logDebug('Error finishing session:', error);
    }
};

// Function to hide all feedback boxes except those for incorrect problems
const hideAllFeedbackBoxesExceptIncorrect = () => {
    try {
        const totalFeedbackBoxes = elements.feedbackBoxes.children.length;
        const incorrectCount = state.problems.length;

        logDebug('Hiding feedback boxes. Total feedback boxes:', totalFeedbackBoxes, 'Incorrect count:', incorrectCount);

        Array.from(elements.feedbackBoxes.children).forEach((box, index) => {
            if (index < incorrectCount) {
                box.style.display = 'block';
                logDebug(`Displaying feedback box at index ${index}.`);
            } else {
                box.style.display = 'none';
                logDebug(`Hiding feedback box at index ${index}.`);
            }
        });

        logDebug('Final state of feedback boxes after hiding/showing:');
        Array.from(elements.feedbackBoxes.children).forEach((box, index) => {
            logDebug(`Feedback box ${index}: Display = ${box.style.display}`);
        });
    } catch (error) {
        logDebug('Error hiding feedback boxes:', error);
    }
};

// Function to reset input state after session ends
const resetInputAfterSession = () => {
    elements.answerInput.readOnly = false;
    elements.answerInput.value = '';
    elements.answerInput.placeholder = '';
    elements.answerInput.focus();
    logDebug('Input box has been reset and focused after session end.');
};

// Function to display the current problem
export const displayProblem = () => {
    const problem = state.problems[state.currentProblemIndex];

    if (!problem) {
        logDebug('Error: Problem to display is undefined.');
        finishSession();
        return;
    }

    // Remove highlighting from all feedback boxes
    Array.from(elements.feedbackBoxes.children).forEach(box => {
        box.classList.remove('highlighted-problem');
    });

    try {
        const operator = state.isMultiplication ? '×' : '+';
        elements.problemDisplay.textContent = `${problem.num1} ${operator} ${problem.num2} = `;
        elements.answerInput.value = '';
        elements.answerInput.focus();

        const feedbackIndex = problem.feedbackIndex !== undefined ? problem.feedbackIndex : state.currentProblemIndex;
        const currentFeedbackBox = elements.feedbackBoxes.children[feedbackIndex];

        if (currentFeedbackBox) {
            currentFeedbackBox.classList.add('highlighted-problem');
            logDebug('Highlighted feedback box at index:', feedbackIndex);
        } else {
            logDebug('Error: Feedback box not found for feedback index:', feedbackIndex);
        }

        logDebug('Displaying problem:', {
            problem: `${problem.num1} ${operator} ${problem.num2}`,
            feedbackIndex
        });
    } catch (error) {
        logDebug('Error displaying problem:', error);
    }
};

// Function to initialize the session by displaying the first problem
export const initializeSession = () => {
    try {
        if (!state.problems || state.problems.length === 0) {
            generateProblems();
            logDebug('Generated new problems during session initialization.');
        }
        state.currentProblemIndex = 0;
        displayProblem();
        logDebug('Session initialized. Displaying first problem.');
    } catch (error) {
        logDebug('Error initializing session:', error);
    }
};

// Ensure that the session is initialized when the script is loaded
initializeSession();