<%- include('partials/header') %>

<div class="container py-5">
    <div class="row">
        <div class="col-12">
            <h2 class="mb-4"><i class="fas fa-question-circle me-2"></i>AI Quiz Generator</h2>
        </div>
    </div>
    
    <!-- Quiz Generator Form -->
    <div id="quiz-generator" class="row">
        <div class="col-lg-8">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0"><i class="fas fa-cogs me-2"></i>Generate New Quiz</h4>
                </div>
                <div class="card-body">
                    <form id="quizForm">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="topic" class="form-label">Topic/Subject</label>
                                <input type="text" class="form-control" id="topic" name="topic" placeholder="e.g., JavaScript, Biology, History" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="difficulty" class="form-label">Difficulty Level</label>
                                <select class="form-select" id="difficulty" name="difficulty" required>
                                    <option value="">Select Difficulty</option>
                                    <option value="beginner">Beginner</option>
                                    <option value="intermediate">Intermediate</option>
                                    <option value="advanced">Advanced</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="questionCount" class="form-label">Number of Questions</label>
                                <select class="form-select" id="questionCount" name="questionCount" required>
                                    <option value="">Select Count</option>
                                    <option value="5">5 Questions</option>
                                    <option value="10">10 Questions</option>
                                    <option value="15">15 Questions</option>
                                    <option value="20">20 Questions</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="quizType" class="form-label">Quiz Type</label>
                                <select class="form-select" id="quizType" name="quizType" required>
                                    <option value="">Select Type</option>
                                    <option value="multiple-choice">Multiple Choice</option>
                                    <option value="true-false">True/False</option>
                                    <option value="short-answer">Short Answer</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-magic me-2"></i>Generate Quiz
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h5><i class="fas fa-info-circle me-2"></i>How It Works</h5>
                    <ul class="list-unstyled">
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Choose your topic and difficulty</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Select question count and type</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>AI generates personalized quiz</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Take the quiz and get instant feedback</li>
                    </ul>
                </div>
            </div>
            
            <div class="card border-0 shadow-sm mt-3">
                <div class="card-body">
                    <h5><i class="fas fa-lightbulb me-2"></i>Tips</h5>
                    <ul class="small">
                        <li>Be specific with your topic for better questions</li>
                        <li>Start with beginner if you're new to the subject</li>
                        <li>Multiple choice is great for concept testing</li>
                        <li>True/False is perfect for fact checking</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Loading State -->
    <div id="quiz-loading" class="text-center py-5 d-none">
        <div class="spinner-border text-primary mb-3" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <h4>Generating Your Quiz...</h4>
        <p class="text-muted">Our AI is creating personalized questions for you</p>
    </div>
    
    <!-- Quiz Container -->
    <div id="quiz-container" class="d-none">
        <div class="row">
            <div class="col-lg-8">
                <div class="card shadow-sm border-0">
                    <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                        <h4 class="mb-0" id="quiz-title">Quiz</h4>
                        <div>
                            <span class="badge bg-light text-dark" id="quiz-progress">Question 1 of 10</span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="quiz-questions"></div>
                        
                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-outline-secondary" id="prev-btn" disabled>
                                <i class="fas fa-chevron-left me-2"></i>Previous
                            </button>
                            <button type="button" class="btn btn-primary" id="next-btn">
                                Next<i class="fas fa-chevron-right ms-2"></i>
                            </button>
                            <button type="button" class="btn btn-success d-none" id="submit-btn">
                                <i class="fas fa-check me-2"></i>Submit Quiz
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <h5><i class="fas fa-list me-2"></i>Quiz Overview</h5>
                        <div id="quiz-overview"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Results Container -->
    <div id="results-container" class="d-none">
        <div class="row">
            <div class="col-lg-8">
                <div class="card shadow-sm border-0">
                    <div class="card-header bg-info text-white">
                        <h4 class="mb-0"><i class="fas fa-chart-line me-2"></i>Quiz Results</h4>
                    </div>
                    <div class="card-body">
                        <div id="results-summary" class="text-center mb-4"></div>
                        <div id="results-details"></div>
                        
                        <div class="text-center mt-4">
                            <button type="button" class="btn btn-primary me-2" id="new-quiz-btn">
                                <i class="fas fa-plus me-2"></i>Generate New Quiz
                            </button>
                            <a href="/quiz-history" class="btn btn-outline-info me-2">
                                <i class="fas fa-history me-2"></i>View History
                            </a>
                            <button type="button" class="btn btn-outline-secondary" id="review-btn">
                                <i class="fas fa-eye me-2"></i>Review Answers
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <h5><i class="fas fa-trophy me-2"></i>Performance</h5>
                        <div id="performance-chart"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let currentQuiz = null;
let currentQuestion = 0;
let userAnswers = [];

// Helper function to escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

document.addEventListener('DOMContentLoaded', function() {
    const quizForm = document.getElementById('quizForm');
    const quizGenerator = document.getElementById('quiz-generator');
    const quizLoading = document.getElementById('quiz-loading');
    const quizContainer = document.getElementById('quiz-container');
    const resultsContainer = document.getElementById('results-container');
    
    console.log('Quiz page loaded');
    
    if (!quizForm) {
        console.error('Quiz form not found!');
        alert('Error: Quiz form not found. Please refresh the page.');
        return;
    }
    
    // Add event listener for form submission
    quizForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        console.log('Form submitted');
        
        try {
            await generateQuiz();
        } catch (error) {
            console.error('Error generating quiz:', error);
            alert('Error generating quiz: ' + error.message);
            if (quizGenerator) quizGenerator.classList.remove('d-none');
            if (quizLoading) quizLoading.classList.add('d-none');
        }
    });
    
    async function generateQuiz() {
        console.log('Generating quiz...');
        
        const formData = new FormData(quizForm);
        const quizData = {
            topic: formData.get('topic'),
            difficulty: formData.get('difficulty'),
            questionCount: parseInt(formData.get('questionCount')),
            quizType: formData.get('quizType')
        };
        
        console.log('Quiz data:', quizData);
        
        // Validate form data
        if (!quizData.topic || !quizData.difficulty || !quizData.questionCount || !quizData.quizType) {
            console.error('Validation failed:', quizData);
            alert('Please fill in all fields');
            return;
        }
        
        // Show loading
        if (quizGenerator) quizGenerator.classList.add('d-none');
        if (quizLoading) quizLoading.classList.remove('d-none');
        
        try {
            console.log('Sending request to API...');
            
            const response = await fetch('/api/generate-quiz', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(quizData)
            });
            
            console.log('Response status:', response.status);
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('API Error:', response.status, errorText);
                throw new Error(`API Error: ${response.status} - ${errorText}`);
            }
            
            const result = await response.json();
            console.log('Quiz generated successfully');
            
            if (result.success) {
                currentQuiz = result.quiz;
                currentQuestion = 0;
                userAnswers = new Array(currentQuiz.length).fill(null);
                
                displayQuiz(result);
            } else {
                console.error('Quiz generation failed:', result.error);
                alert('Error generating quiz: ' + (result.error || 'Unknown error'));
                if (quizGenerator) quizGenerator.classList.remove('d-none');
            }
        } catch (error) {
            console.error('Quiz generation error:', error);
            alert('Error: ' + error.message);
            if (quizGenerator) quizGenerator.classList.remove('d-none');
        } finally {
            if (quizLoading) quizLoading.classList.add('d-none');
        }
    }
    
    function displayQuiz(quizData) {
        console.log('Displaying quiz:', quizData);
        
        if (!quizContainer) {
            console.error('Quiz container not found!');
            return;
        }
        
        quizContainer.classList.remove('d-none');
        
        const quizTitle = document.getElementById('quiz-title');
        if (quizTitle) {
            quizTitle.textContent = `${quizData.topic} Quiz`;
        }
        
        displayQuestion(currentQuestion);
        displayOverview();
        
        // Navigation buttons
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const submitBtn = document.getElementById('submit-btn');
        const newQuizBtn = document.getElementById('new-quiz-btn');
        
        if (prevBtn) {
            prevBtn.addEventListener('click', () => {
                if (currentQuestion > 0) {
                    currentQuestion--;
                    displayQuestion(currentQuestion);
                }
            });
        }
        
        if (nextBtn) {
            nextBtn.addEventListener('click', () => {
                if (currentQuestion < currentQuiz.length - 1) {
                    currentQuestion++;
                    displayQuestion(currentQuestion);
                }
            });
        }
        
        if (submitBtn) {
            submitBtn.addEventListener('click', submitQuiz);
        }
        
        if (newQuizBtn) {
            newQuizBtn.addEventListener('click', () => {
                resetQuiz();
            });
        }
    }
    
    function displayQuestion(index) {
        if (!currentQuiz || index >= currentQuiz.length) {
            console.error('Invalid question index or quiz not loaded');
            return;
        }
        
        const question = currentQuiz[index];
        const questionsDiv = document.getElementById('quiz-questions');
        
        if (!questionsDiv) {
            console.error('Questions div not found!');
            return;
        }
        
        let html = `
            <div class="mb-4">
                <h5 class="mb-3">Question ${index + 1}</h5>
                <p class="lead">${escapeHtml(question.question)}</p>
            </div>
        `;
        
        if (question.options) {
            // Multiple choice
            html += '<div class="mb-3">';
            question.options.forEach((option, i) => {
                const isSelected = userAnswers[index] === option.charAt(0);
                html += `
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="question_${index}" 
                               id="q${index}_${i}" value="${escapeHtml(option.charAt(0))}" ${isSelected ? 'checked' : ''}>
                        <label class="form-check-label" for="q${index}_${i}">
                            ${escapeHtml(option)}
                        </label>
                    </div>
                `;
            });
            html += '</div>';
        } else if (question.correct === 'True' || question.correct === 'False') {
            // True/False
            html += `
                <div class="mb-3">
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="question_${index}" 
                               id="q${index}_true" value="True" ${userAnswers[index] === 'True' ? 'checked' : ''}>
                        <label class="form-check-label" for="q${index}_true">True</label>
                    </div>
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="radio" name="question_${index}" 
                               id="q${index}_false" value="False" ${userAnswers[index] === 'False' ? 'checked' : ''}>
                        <label class="form-check-label" for="q${index}_false">False</label>
                    </div>
                </div>
            `;
        } else {
            // Short answer
            html += `
                <div class="mb-3">
                    <textarea class="form-control" name="question_${index}" 
                              placeholder="Enter your answer here...">${userAnswers[index] || ''}</textarea>
                </div>
            `;
        }
        
        questionsDiv.innerHTML = html;
        
        // Update progress
        const progressEl = document.getElementById('quiz-progress');
        if (progressEl) {
            progressEl.textContent = `Question ${index + 1} of ${currentQuiz.length}`;
        }
        
        // Update navigation buttons
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const submitBtn = document.getElementById('submit-btn');
        
        // Check if all questions are answered
        const allAnswered = userAnswers.every(answer => answer !== null && answer !== '');
        
        if (prevBtn) prevBtn.disabled = index === 0;
        
        // Show next button if not on last question
        if (nextBtn) {
            if (index === currentQuiz.length - 1) {
                nextBtn.classList.add('d-none');
            } else {
                nextBtn.classList.remove('d-none');
            }
        }
        
        // Show submit button if all questions answered or on last question
        if (submitBtn) {
            if (allAnswered) {
                submitBtn.classList.remove('d-none');
                submitBtn.innerHTML = '<i class="fas fa-trophy me-2"></i>Complete Quiz';
                submitBtn.classList.remove('btn-success');
                submitBtn.classList.add('btn-primary');
            } else if (index === currentQuiz.length - 1) {
                submitBtn.classList.remove('d-none');
                submitBtn.innerHTML = '<i class="fas fa-check me-2"></i>Submit Quiz';
                submitBtn.classList.remove('btn-primary');
                submitBtn.classList.add('btn-success');
            } else {
                submitBtn.classList.add('d-none');
            }
        }
        
        // Save answer when changed
        const inputs = questionsDiv.querySelectorAll('input, textarea');
        inputs.forEach(input => {
            input.addEventListener('change', (e) => {
                userAnswers[index] = e.target.value;
                displayOverview();
                updateNavigationButtons(); // Update buttons when answers change
            });
        });
    }
    
    function updateNavigationButtons() {
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const submitBtn = document.getElementById('submit-btn');
        
        // Check if all questions are answered
        const allAnswered = userAnswers.every(answer => answer !== null && answer !== '');
        
        if (prevBtn) prevBtn.disabled = currentQuestion === 0;
        
        // Show next button if not on last question
        if (nextBtn) {
            if (currentQuestion === currentQuiz.length - 1) {
                nextBtn.classList.add('d-none');
            } else {
                nextBtn.classList.remove('d-none');
            }
        }
        
        // Show submit button if all questions answered or on last question
        if (submitBtn) {
            if (allAnswered) {
                submitBtn.classList.remove('d-none');
                submitBtn.innerHTML = '<i class="fas fa-trophy me-2"></i>Complete Quiz';
                submitBtn.classList.remove('btn-success');
                submitBtn.classList.add('btn-primary');
            } else if (currentQuestion === currentQuiz.length - 1) {
                submitBtn.classList.remove('d-none');
                submitBtn.innerHTML = '<i class="fas fa-check me-2"></i>Submit Quiz';
                submitBtn.classList.remove('btn-primary');
                submitBtn.classList.add('btn-success');
            } else {
                submitBtn.classList.add('d-none');
            }
        }
    }
    
    function displayOverview() {
        const overviewDiv = document.getElementById('quiz-overview');
        let html = '<div class="row">';
        
        currentQuiz.forEach((_, i) => {
            const isAnswered = userAnswers[i] !== null && userAnswers[i] !== '';
            const isCurrent = i === currentQuestion;
            
            html += `
                <div class="col-4 mb-2">
                    <button class="btn btn-sm w-100 ${isCurrent ? 'btn-primary' : isAnswered ? 'btn-success' : 'btn-outline-secondary'}" 
                            onclick="goToQuestion(${i})">
                        ${i + 1}
                    </button>
                </div>
            `;
        });
        
        html += '</div>';
        overviewDiv.innerHTML = html;
        
        // Update navigation buttons when overview changes
        updateNavigationButtons();
    }
    
    window.goToQuestion = function(index) {
        currentQuestion = index;
        displayQuestion(currentQuestion);
        updateNavigationButtons();
    };
    
    async function submitQuiz() {
        try {
            const response = await fetch('/api/submit-quiz', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    answers: userAnswers,
                    quiz: currentQuiz,
                    topic: document.getElementById('topic').value,
                    difficulty: document.getElementById('difficulty').value,
                    quizType: document.getElementById('quizType').value
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                displayResults(result);
            } else {
                alert('Error submitting quiz: ' + result.error);
            }
        } catch (error) {
            alert('Error: ' + error.message);
        }
    }
    
    function displayResults(results) {
        quizContainer.classList.add('d-none');
        resultsContainer.classList.remove('d-none');
        
        const summaryDiv = document.getElementById('results-summary');
        const percentage = results.percentage;
        let grade = 'F';
        let badgeClass = 'bg-danger';
        
        if (percentage >= 90) { grade = 'A'; badgeClass = 'bg-success'; }
        else if (percentage >= 80) { grade = 'B'; badgeClass = 'bg-info'; }
        else if (percentage >= 70) { grade = 'C'; badgeClass = 'bg-warning'; }
        else if (percentage >= 60) { grade = 'D'; badgeClass = 'bg-warning'; }
        
        summaryDiv.innerHTML = `
            <div class="row">
                <div class="col-md-3">
                    <div class="display-4 text-primary">${results.score}/${results.total}</div>
                    <p class="text-muted">Score</p>
                </div>
                <div class="col-md-3">
                    <div class="display-4 text-success">${percentage}%</div>
                    <p class="text-muted">Percentage</p>
                </div>
                <div class="col-md-3">
                    <div class="display-4">
                        <span class="badge ${badgeClass} fs-1">${grade}</span>
                    </div>
                    <p class="text-muted">Grade</p>
                </div>
                <div class="col-md-3">
                    <div class="display-4 text-info">${results.results.filter(r => r.isCorrect).length}</div>
                    <p class="text-muted">Correct</p>
                </div>
            </div>
        `;
        
        const detailsDiv = document.getElementById('results-details');
        let detailsHtml = '<h5 class="mb-3">Detailed Results</h5>';
        
        results.results.forEach((result, i) => {
            detailsHtml += `
                <div class="card mb-3 ${result.isCorrect ? 'border-success' : 'border-danger'}">
                    <div class="card-body">
                        <h6 class="card-title d-flex justify-content-between align-items-center">
                            Question ${i + 1}
                            <span class="badge ${result.isCorrect ? 'bg-success' : 'bg-danger'}">
                                ${result.isCorrect ? 'Correct' : 'Incorrect'}
                            </span>
                        </h6>
                        <p class="card-text">${escapeHtml(result.question)}</p>
                        <div class="row">
                            <div class="col-md-6">
                                <small class="text-muted">Your Answer:</small>
                                <p class="mb-1 ${result.isCorrect ? 'text-success' : 'text-danger'}">${escapeHtml(result.userAnswer || 'Not answered')}</p>
                            </div>
                            <div class="col-md-6">
                                <small class="text-muted">Correct Answer:</small>
                                <p class="mb-1 text-success">${escapeHtml(result.correctAnswer)}</p>
                            </div>
                        </div>
                        ${result.explanation ? `<div class="mt-2"><small class="text-muted">Explanation:</small><p class="small">${escapeHtml(result.explanation)}</p></div>` : ''}
                    </div>
                </div>
            `;
        });
        
        detailsDiv.innerHTML = detailsHtml;
    }
    
    function resetQuiz() {
        currentQuiz = null;
        currentQuestion = 0;
        userAnswers = [];
        
        quizContainer.classList.add('d-none');
        resultsContainer.classList.add('d-none');
        quizGenerator.classList.remove('d-none');
        
        quizForm.reset();
    }
});
</script>

<%- include('partials/footer') %>
