<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cortexa Quiz Generator</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link
        href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Inter:wght@300;400;500;600&display=swap"
        rel="stylesheet">
    <style>
        :root {
            --primary: #4facfe;
            --secondary: #00f2fe;
            --dark: #2c3e50;
            --light: #f8fafc;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--light);
            color: var(--dark);
        }

        .premium-header {
            background: linear-gradient(135deg, var(--dark) 0%, #34495e 100%);
            padding: 1.5rem 0;
            color: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .main-container {
            max-width: 900px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
            background: white;
            margin-bottom: 30px;
            padding: 30px;
        }

        .btn-premium {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            border: none;
            border-radius: 12px;
            color: white;
            padding: 12px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-premium:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
            color: white;
        }

        .option-card {
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .option-card:hover {
            border-color: var(--primary);
            background: #f0f9ff;
        }

        .option-card.selected {
            border-color: var(--primary);
            background: #e0f2fe;
            font-weight: 600;
        }

        .option-card.correct {
            border-color: #28a745;
            background: #d4edda;
            color: #155724;
        }

        .option-card.incorrect {
            border-color: #dc3545;
            background: #f8d7da;
            color: #721c24;
        }

        .loader {
            border: 4px solid #f3f3f3;
            border-top: 4px solid var(--primary);
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        #questions-container {
            display: none;
        }

        .result-section {
            display: none;
            text-align: center;
        }
    </style>
</head>

<body>

    <header class="premium-header text-center">
        <div class="container d-flex justify-content-between align-items-center">
            <a href="/home" class="btn text-white"><i class="fas fa-arrow-left"></i> Back</a>
            <h1 class="h3 mb-0 fw-bold">🧠 Cortexa Quiz Generator</h1>
            <div style="width: 80px;"></div>
        </div>
    </header>

    <div class="main-container">

        <!-- Input Section -->
        <div id="input-section" class="card">
            <h4 class="fw-bold mb-3">Create New Quiz</h4>
            <p class="text-muted">Upload content and let AI generate a quiz for you.</p>

            <div class="mb-4">
                <label class="form-label">Content Type</label>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-primary flex-fill active"
                        onclick="setContentType('text')">Text</button>
                    <button class="btn btn-outline-primary flex-fill" onclick="setContentType('file')">PDF /
                        Image</button>
                </div>
            </div>

            <div id="text-input-area">
                <textarea id="raw-text" class="form-control" rows="6"
                    placeholder="Paste your content here..."></textarea>
            </div>

            <div id="file-input-area" style="display:none;">
                <input type="file" id="content-file" class="form-control" accept="image/*,.pdf">
                <small class="text-muted">Upload a PDF document or an image containing text.</small>
            </div>

            <div class="mt-4">
                <button id="generate-btn" class="btn btn-premium w-100" onclick="generateQuiz()">
                    Generate Quiz <i class="fas fa-magic"></i>
                </button>
            </div>
        </div>

        <!-- Questions Section -->
        <div id="questions-container">
            <!-- Questions will be injected here -->
        </div>

        <!-- Result Section -->
        <div id="result-section" class="card result-section">
            <i class="fas fa-trophy text-warning mb-3" style="font-size: 60px;"></i>
            <h2 class="fw-bold">Quiz Completed!</h2>
            <p class="lead">You scored <span id="score-display" class="fw-bold text-primary">0</span> out of <span
                    id="total-display">0</span></p>

            <button class="btn btn-premium mt-3" onclick="location.reload()">Create New Quiz</button>
        </div>

    </div>

    <script>
        let contentType = 'text';
        let questions = [];
        let userAnswers = {};

        function setContentType(type) {
            contentType = type;
            const textBtn = document.querySelectorAll('.btn-outline-primary')[0];
            const fileBtn = document.querySelectorAll('.btn-outline-primary')[1];

            if (type === 'text') {
                textBtn.classList.add('active');
                fileBtn.classList.remove('active');
                document.getElementById('text-input-area').style.display = 'block';
                document.getElementById('file-input-area').style.display = 'none';
            } else {
                textBtn.classList.remove('active');
                fileBtn.classList.add('active');
                document.getElementById('text-input-area').style.display = 'none';
                document.getElementById('file-input-area').style.display = 'block';
            }
        }

        async function generateQuiz() {
            const btn = document.getElementById('generate-btn');
            const originalContent = btn.innerHTML;
            btn.innerHTML = '<span class="loader"></span> Generating...';
            btn.disabled = true;

            const formData = new FormData();
            formData.append('content_type', contentType);

            if (contentType === 'text') {
                const text = document.getElementById('raw-text').value;
                if (!text) {
                    alert('Please enter some text.');
                    btn.innerHTML = originalContent;
                    btn.disabled = false;
                    return;
                }
                formData.append('text', text);
            } else {
                const file = document.getElementById('content-file').files[0];
                if (!file) {
                    alert('Please select a file.');
                    btn.innerHTML = originalContent;
                    btn.disabled = false;
                    return;
                }
                formData.append('file', file);
            }

            try {
                const response = await fetch('/quiz/generate', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Authorization': 'Bearer ' + '{{access_token}}'
                    }
                });

                const data = await response.json();
                if (response.ok) {
                    questions = data.questions;
                    renderQuestions();
                    document.getElementById('input-section').style.display = 'none';
                    document.getElementById('questions-container').style.display = 'block';
                } else {
                    alert('Error: ' + data.detail);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Failed to connect to server.');
            } finally {
                btn.innerHTML = originalContent;
                btn.disabled = false;
            }
        }

        function renderQuestions() {
            const container = document.getElementById('questions-container');
            container.innerHTML = '';

            questions.forEach((q, index) => {
                const qCard = document.createElement('div');
                qCard.className = 'card';

                let optionsHtml = '';
                q.options.forEach((opt, optIndex) => {
                    optionsHtml += `
                        <div class="option-card" id="q${index}-opt${optIndex}" onclick="selectOption(${index}, ${optIndex}, ${opt.is_correct})">
                            ${opt.text}
                        </div>
                    `;
                });

                qCard.innerHTML = `
                    <h5 class="fw-bold mb-3">${index + 1}. ${q.question}</h5>
                    <div class="options-list">
                        ${optionsHtml}
                    </div>
                    <div id="feedback-${index}" class="mt-2 fw-bold" style="display:none;"></div>
                `;
                container.appendChild(qCard);
            });

            // Add finish button
            const finishBtn = document.createElement('button');
            finishBtn.className = 'btn btn-success w-100 mt-3 p-3 fw-bold';
            finishBtn.innerHTML = 'Finish Quiz';
            finishBtn.onclick = showResults;
            container.appendChild(finishBtn);
        }

        function selectOption(qIndex, optIndex, isCorrect) {
            // Check if already answered
            if (userAnswers[qIndex] !== undefined) return;

            userAnswers[qIndex] = isCorrect;

            const selectedDiv = document.getElementById(`q${qIndex}-opt${optIndex}`);
            const feedbackDiv = document.getElementById(`feedback-${qIndex}`);

            if (isCorrect) {
                selectedDiv.classList.add('correct');
                feedbackDiv.innerHTML = '<span class="text-success"><i class="fas fa-check"></i> Correct!</span>';
            } else {
                selectedDiv.classList.add('incorrect');
                feedbackDiv.innerHTML = '<span class="text-danger"><i class="fas fa-times"></i> Incorrect</span>';

                // Highlight the correct answer
                questions[qIndex].options.forEach((opt, i) => {
                    if (opt.is_correct) {
                        document.getElementById(`q${qIndex}-opt${i}`).classList.add('correct');
                    }
                });
            }
            feedbackDiv.style.display = 'block';
        }

        function showResults() {
            let score = 0;
            const total = questions.length;

            for (let i = 0; i < total; i++) {
                if (userAnswers[i] === true) {
                    score++;
                }
            }

            document.getElementById('questions-container').style.display = 'none';
            document.getElementById('result-section').style.display = 'block';
            document.getElementById('score-display').innerText = score;
            document.getElementById('total-display').innerText = total;
        }
    </script>
</body>

</html>