<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-4xl">
        <!-- Initial Setup View -->
        <div id="setup-view" class="bg-white rounded-lg shadow-md p-6">
            <h1 class="text-3xl font-bold text-gray-800 mb-6 text-center">{{ title }}</h1>
            
            <div class="mb-6">
                <h2 class="text-lg font-semibold text-gray-700 mb-3">Select Categories:</h2>
                <div class="space-y-2" id="categories-container">
                    {% for value in categories %}
                    <label class="flex items-center space-x-3 p-3 border rounded-lg hover:bg-gray-50 cursor-pointer transition">
                        <input type="checkbox" name="categories" value="{{ value }}" 
                               class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500 category-checkbox">
                        <span class="text-gray-700">{{ value }}</span>
                    </label>
                    {% endfor %}
                </div>
            </div>
            
            <button id="start-btn" 
                    class="w-full bg-blue-600 text-white font-semibold py-3 px-6 rounded-lg hover:bg-blue-700 transition duration-200">
                Start Quiz
            </button>
        </div>

        <!-- Quiz View with Sidebar -->
        <div id="quiz-view" class="hidden">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                <!-- Sidebar with Categories -->
                <div class="md:col-span-1">
                    <div class="bg-white rounded-lg shadow-md p-4 sticky top-4">
                        <h3 class="font-semibold text-gray-700 mb-3">Categories</h3>
                        <div class="space-y-2" id="sidebar-categories">
                            {% for value in categories %}
                            <label class="flex items-center space-x-2 cursor-pointer">
                                <input type="checkbox" name="sidebar-categories" value="{{ value }}" 
                                       class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500 sidebar-category-checkbox">
                                <span class="text-sm text-gray-600">{{ value }}</span>
                            </label>
                            {% endfor %}
                        </div>
                        <button id="update-categories-btn" 
                                class="w-full mt-4 bg-gray-600 text-white text-sm font-semibold py-2 px-4 rounded hover:bg-gray-700 transition duration-200">
                            Update
                        </button>
                    </div>
                </div>

                <!-- Main Quiz Content -->
                <div class="md:col-span-3">
                    <div class="bg-white rounded-lg shadow-md p-6">
                        <div class="flex justify-between items-center mb-6">
                            <span id="question-counter" class="text-sm text-gray-500">Question 1</span>
                            <span id="selected-categories-display" class="text-xs text-gray-400"></span>
                        </div>
                        
                        <!-- Question Container -->
                        <div id="question-container" class="mb-6">
                            <p id="question-text" class="text-xl text-gray-800 mb-4"></p>
                            <input type="text" id="answer-input" 
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                   placeholder="Your answer...">
                        </div>
                        
                        <button id="submit-btn" 
                                class="w-full bg-green-600 text-white font-semibold py-3 px-6 rounded-lg hover:bg-green-700 transition duration-200">
                            Submit Answer (Enter)
                        </button>

                        <!-- Result Container (initially hidden) -->
                        <div id="result-container" class="mt-6 hidden">
                            <!-- Result content will be inserted here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        .diff {
            font-family: "Courier New", monospace;
            font-size: 1.15em;
            white-space: pre;
            margin-top: 1rem;
        }
        .diff-row {
            margin-bottom: 2px;
            line-height: 1.2;
        }
        .diff-green {
            color: #2e7d32;
            font-weight: bold;
        }
        .diff-red {
            color: #c62828;
            font-weight: bold;
        }
        .diff-grey {
            color: #9e9e9e;
        }
    </style>
    <script>
        // Store selected categories globally
        let selectedCategories = [];
        let currentQuestion = null;
        let questionNumber = 0;
        let showingResult = false;

        // Text diff functions
        function escapeChar(c) {
            return c === " " ? "&nbsp;" : c;
        }

        function alignStrings(a, b) {
            // Handle null/undefined inputs
            a = a || "";
            b = b || "";
            
            const dp = Array.from({ length: a.length + 1 }, () =>
                Array(b.length + 1).fill(0),
            );

            for (let i = 0; i <= a.length; i++) dp[i][0] = i;
            for (let j = 0; j <= b.length; j++) dp[0][j] = j;

            for (let i = 1; i <= a.length; i++) {
                for (let j = 1; j <= b.length; j++) {
                    dp[i][j] =
                        a[i - 1] === b[j - 1]
                            ? dp[i - 1][j - 1]
                            : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
                }
            }

            let i = a.length,
                j = b.length;
            let aAlign = "",
                bAlign = "";

            while (i > 0 || j > 0) {
                if (i > 0 && j > 0 && a[i - 1] === b[j - 1]) {
                    aAlign = a[i - 1] + aAlign;
                    bAlign = b[j - 1] + bAlign;
                    i--;
                    j--;
                } else if (i > 0 && j > 0 && dp[i][j] === dp[i - 1][j - 1] + 1) {
                    aAlign = a[i - 1] + aAlign;
                    bAlign = b[j - 1] + bAlign;
                    i--;
                    j--;
                } else if (i > 0 && dp[i][j] === dp[i - 1][j] + 1) {
                    aAlign = a[i - 1] + aAlign;
                    bAlign = " " + bAlign;
                    i--;
                } else {
                    aAlign = " " + aAlign;
                    bAlign = b[j - 1] + bAlign;
                    j--;
                }
            }

            return { aAlign, bAlign };
        }

        function renderTextDiff(userAnswer, correctAnswer) {
            // Handle null/undefined inputs
            userAnswer = String(userAnswer || "");
            correctAnswer = String(correctAnswer || "");
            
            const { aAlign, bAlign } = alignStrings(userAnswer, correctAnswer);

            let top = "";
            let bottom = "";

            for (let i = 0; i < aAlign.length; i++) {
                const a = aAlign[i];
                const b = bAlign[i];

                // TOP ROW (user input)
                if (a === " " && b !== " ") {
                    top += `<span class="diff-grey">-</span>`;
                } else if (a === b) {
                    top += `<span class="diff-green">${escapeChar(a)}</span>`;
                } else if (a !== " ") {
                    top += `<span class="diff-red">${escapeChar(a)}</span>`;
                }

                // BOTTOM ROW (reference)
                if (b === " ") {
                    bottom += " ";
                } else if (a === b) {
                    bottom += `<span class="diff-green">${escapeChar(b)}</span>`;
                } else {
                    bottom += `<span class="diff-grey">${escapeChar(b)}</span>`;
                }
            }

            return `<div class="diff"><div class="diff-row">${top}</div><div class="diff-row">${bottom}</div></div>`;
        }

        // Get DOM elements
        const setupView = document.getElementById('setup-view');
        const quizView = document.getElementById('quiz-view');
        const startBtn = document.getElementById('start-btn');
        const submitBtn = document.getElementById('submit-btn');
        const updateCategoriesBtn = document.getElementById('update-categories-btn');
        const questionText = document.getElementById('question-text');
        const answerInput = document.getElementById('answer-input');
        const resultContainer = document.getElementById('result-container');
        const questionCounter = document.getElementById('question-counter');
        const selectedCategoriesDisplay = document.getElementById('selected-categories-display');
        const questionContainer = document.getElementById('question-container');

        // Start button click handler
        startBtn.addEventListener('click', async () => {
            // Get selected categories
            const checkboxes = document.querySelectorAll('.category-checkbox:checked');
            selectedCategories = Array.from(checkboxes).map(cb => cb.value);
            
            if (selectedCategories.length === 0) {
                alert('Please select at least one category');
                return;
            }

            // Sync sidebar checkboxes
            syncSidebarCategories();

            // Fetch first question
            await fetchNextQuestion();
        });

        // Update categories button click handler
        updateCategoriesBtn.addEventListener('click', async () => {
            const checkboxes = document.querySelectorAll('.sidebar-category-checkbox:checked');
            selectedCategories = Array.from(checkboxes).map(cb => cb.value);
            
            if (selectedCategories.length === 0) {
                alert('Please select at least one category');
                return;
            }

            // Fetch next question with updated categories
            await fetchNextQuestion();
        });

        // Sync sidebar checkboxes with selected categories
        function syncSidebarCategories() {
            document.querySelectorAll('.sidebar-category-checkbox').forEach(cb => {
                cb.checked = selectedCategories.includes(cb.value);
            });
        }

        // Fetch next question
        async function fetchNextQuestion() {
            try {
                const response = await fetch('api/next', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ categories: selectedCategories })
                });
                
                const data = await response.json();
                
                if (data.complete) {
                    // Quiz complete
                    alert('Quiz complete! Great job!');
                    resetQuiz();
                } else {
                    currentQuestion = data.question;
                    questionNumber++;
                    showQuestion();
                }
            } catch (error) {
                console.error('Error fetching question:', error);
                alert('Failed to load question. Please try again.');
            }
        }

        // Submit button click handler
        submitBtn.addEventListener('click', async () => {
            if (showingResult) {
                // If showing result, Enter goes to next question
                await fetchNextQuestion();
                return;
            }

            const answer = answerInput.value.trim();
            
            if (!answer) {
                alert('Please enter an answer');
                return;
            }

            try {
                const response = await fetch('api/submit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        category: currentQuestion.category,
                        seed: currentQuestion.seed,
                        answer: answer,
                    })
                });
                
                const data = await response.json();
                showResult(data);
            } catch (error) {
                console.error('Error submitting answer:', error);
                alert('Failed to submit answer. Please try again.');
            }
        });

        // Show question view
        function showQuestion() {
            setupView.classList.add('hidden');
            quizView.classList.remove('hidden');
            
            // Reset UI
            resultContainer.classList.add('hidden');
            resultContainer.innerHTML = '';
            questionContainer.classList.remove('hidden');
            submitBtn.textContent = 'Submit Answer (Enter)';
            showingResult = false;
            
            questionText.textContent = currentQuestion.text;
            questionCounter.textContent = `Question ${questionNumber}`;
            selectedCategoriesDisplay.textContent = selectedCategories.join(', ');
            answerInput.value = '';
            answerInput.focus();
        }

        // Show result view
        function showResult(data) {
            showingResult = true;
            questionContainer.classList.add('hidden');
            resultContainer.classList.remove('hidden');
            submitBtn.textContent = 'Next Question (Enter)';
            
            const isCorrect = data.correct;
            const bgColor = isCorrect ? 'bg-green-100' : 'bg-red-100';
            const textColor = isCorrect ? 'text-green-800' : 'text-red-800';
            const icon = isCorrect ? '✓' : '✗';
            const message = isCorrect ? 'Correct!' : 'Incorrect';
            
            // Check if explanation is textdiff placeholder
            const isTextDiff = data.explanation === "{textdiff}";
            
            let explanationHtml = '';
            if (!isCorrect && isTextDiff) {
                explanationHtml = `
                    <div class="bg-gray-50 border-l-4 border-gray-400 p-4">
                        ${renderTextDiff(data.submitted_answer, data.correct_answer)}
                    </div>
                `;
            } else if (!isCorrect && data.explanation) {
                explanationHtml = `<div class="bg-blue-50 border-l-4 border-blue-500 p-4"><p class="text-gray-700"><strong>Explanation:</strong> ${data.explanation}</p></div>`;
            }
            
            resultContainer.innerHTML = `
                <div class="${bgColor} border-l-4 ${isCorrect ? 'border-green-500' : 'border-red-500'} p-4 mb-4">
                    <div class="flex items-center">
                        <span class="text-2xl mr-3">${icon}</span>
                        <div>
                            <p class="font-bold ${textColor} text-lg">${message}</p>
                            <p class="text-gray-600 mt-1">Your answer: <span class="font-semibold">${data.submitted_answer}</span></p>
                            ${!isCorrect && !isTextDiff ? `<p class="text-gray-600 mt-1">Correct answer: <span class="font-semibold">${data.correct_answer}</span></p>` : ''}
                        </div>
                    </div>
                </div>
                ${explanationHtml}
                <div class="mt-4 text-sm text-gray-500 text-center">Press Enter to continue</div>
            `;
            
            // Focus on document to capture Enter key
            document.activeElement.blur();
        }

        // Reset quiz to initial state
        function resetQuiz() {
            quizView.classList.add('hidden');
            setupView.classList.remove('hidden');
            
            // Uncheck all checkboxes
            document.querySelectorAll('.category-checkbox, .sidebar-category-checkbox').forEach(cb => {
                cb.checked = false;
            });
            
            selectedCategories = [];
            currentQuestion = null;
            questionNumber = 0;
            showingResult = false;
        }

        // Allow Enter key to submit answer or go to next question
        document.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !setupView.classList.contains('hidden')) {
                // Don't handle Enter on setup view
                return;
            }
            if (e.key === 'Enter' && !quizView.classList.contains('hidden')) {
                submitBtn.click();
            }
        });
    </script>
</body>
</html>
