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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
const API_BASE = 'https://zyx2026-mistake-master-api.hf.space/api';
let currentPaperId = null;
let currentStudentId = null;
let questions = [];
let currentPracticeId = null;

function formatMathText(text) {
    let s = String(text ?? '');
    s = s
        .replace(/&/g, '&')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    s = s.replace(/(\w)\^(\d+)/g, '$1<sup>$2</sup>');
    s = s.replace(/sqrt\(([^)]+)\)/gi, '&radic;($1)');
    s = s.replace(/\\sqrt\{([^}]+)\}/gi, '&radic;($1)');
    return s;
}

// DOM Elements
const loginView = document.getElementById('login-view');
const testView = document.getElementById('test-view');
const resultsView = document.getElementById('results-view');
const studentIdInput = document.getElementById('student-id');
const testModeSelect = document.getElementById('test-mode');
const equivalentOptions = document.getElementById('equivalent-options');
const startBtn = document.getElementById('start-btn');
const questionsContainer = document.getElementById('questions-container');
const submitBtn = document.getElementById('submit-btn');
const scoreSummary = document.getElementById('score-summary');
const feedbackContainer = document.getElementById('feedback-container');
const alertsContainer = document.getElementById('alerts-container');
const restartBtn = document.getElementById('restart-btn');

const practiceModal = document.getElementById('practice-modal');
const practiceContainer = document.getElementById('practice-question-container');
const practiceFeedback = document.getElementById('practice-feedback');
const submitPracticeBtn = document.getElementById('submit-practice-btn');
const closeModalBtn = document.querySelector('.close-btn');

// Event Listeners
startBtn.addEventListener('click', startTest);
submitBtn.addEventListener('click', submitTest);
restartBtn.addEventListener('click', () => location.reload());
testModeSelect.addEventListener('change', (e) => {
    if (e.target.value === 'equivalent') {
        equivalentOptions.classList.remove('hidden');
    } else {
        equivalentOptions.classList.add('hidden');
    }
});

closeModalBtn.addEventListener('click', () => practiceModal.classList.add('hidden'));
submitPracticeBtn.addEventListener('click', submitPractice);

async function startTest() {
    const studentId = studentIdInput.value.trim();
    if (!studentId) {
        alert('Please enter a Student ID');
        return;
    }
    currentStudentId = studentId;

    const mode = testModeSelect.value;
    const seed = document.getElementById('random-seed').value;
    
    const payload = {
        student_id: studentId,
        mode: mode,
        params: {}
    };
    
    if (mode === 'equivalent') {
        payload.seed = seed ? parseInt(seed) : null;
    }

    try {
        const response = await fetch(`${API_BASE}/paper/create`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        if (!response.ok) throw new Error('Failed to create paper. Ensure Question Bank is frozen.');
        
        const data = await response.json();
        currentPaperId = data.paper_id;
        questions = data.questions;
        
        renderQuestions(questionsContainer, questions);
        switchView('test');
    } catch (err) {
        console.error(err);
        alert('Error starting test. ' + err.message);
    }
}

function renderQuestions(container, qs) {
    container.innerHTML = '';
    qs.forEach((q, index) => {
        const card = document.createElement('div');
        card.className = 'question-card';
        card.dataset.id = q.id;

        const stem = document.createElement('div');
        stem.className = 'question-stem';
        stem.innerHTML = `${index + 1}. ${formatMathText(q.stem)}`;
        card.appendChild(stem);

        const inputContainer = document.createElement('div');
        
        if (q.type === 'multiple_choice') {
            const optionsList = document.createElement('ul');
            optionsList.className = 'options-list';
            q.options.forEach(opt => {
                const li = document.createElement('li');
                li.innerHTML = `
                    <label>
                        <input type="radio" name="q-${q.id}" value="${opt.id}">
                        ${opt.id}. ${formatMathText(opt.text)}
                    </label>
                `;
                optionsList.appendChild(li);
            });
            inputContainer.appendChild(optionsList);
        } else {
            inputContainer.innerHTML = `
                <input type="text" name="q-${q.id}" placeholder="Your answer...">
            `;
        }

        card.appendChild(inputContainer);
        container.appendChild(card);
    });
    if (window.MathJax && MathJax.typesetPromise) {
        MathJax.typesetPromise();
    }
}

async function submitTest() {
    const answers = {};
    let allAnswered = true;
    let answeredCount = 0;

    questions.forEach(q => {
        let val = '';
        if (q.type === 'multiple_choice') {
            const selected = document.querySelector(`input[name="q-${q.id}"]:checked`);
            if (selected) val = selected.value;
        } else {
            const input = document.querySelector(`input[name="q-${q.id}"]`);
            if (input) val = input.value.trim();
        }
        
        if (!val) allAnswered = false;
        if (val) answeredCount += 1;
        answers[q.id] = val;
    });

    if (answeredCount === 0) {
        alert("You must answer at least one question before submitting.");
        return;
    }

    if (!allAnswered && !confirm("Some questions are unanswered. Submit anyway?")) {
        return;
    }

    // Show loading
    submitBtn.textContent = "Grading...";
    submitBtn.disabled = true;

    try {
        const response = await fetch(`${API_BASE}/paper/${currentPaperId}/submit`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                student_id: currentStudentId,
                answers: answers
            })
        });

        if (!response.ok) throw new Error('Failed to submit');
        
        const result = await response.json();
        renderResults(result);
        switchView('results');
    } catch (err) {
        console.error(err);
        alert('Error submitting test.');
        submitBtn.textContent = "Submit Answers";
        submitBtn.disabled = false;
    }
}

function renderResults(data) {
    scoreSummary.innerHTML = `
        <h3>Total Score: ${data.total_score} / ${data.total_questions}</h3>
    `;
    
    alertsContainer.innerHTML = '';
    if (data.repeated_errors && data.repeated_errors.length > 0) {
        data.repeated_errors.forEach(msg => {
            const alert = document.createElement('div');
            alert.className = 'alert-box';
            alert.textContent = msg;
            alertsContainer.appendChild(alert);
        });
    }

    feedbackContainer.innerHTML = '';
    
    data.results.forEach((item, index) => {
        const card = document.createElement('div');
        card.className = `result-card ${item.is_correct ? 'correct' : 'incorrect'}`;
        
        // Find question text
        const originalQ = questions.find(q => q.id === item.question_id);
        const stemText = originalQ ? originalQ.stem : item.question_id;

        let content = `
            <div class="question-stem">Q${index + 1}: ${formatMathText(stemText)}</div>
            <div>Your Answer: <strong>${item.student_answer || '(No Answer)'}</strong></div>
            <div>Status: ${item.is_correct ? 'Correct' : 'Wrong'}</div>
        `;

        if (!item.is_correct && item.error_analysis) {
            const analysis = item.error_analysis;
            content += `
                <div class="ai-feedback" id="analysis-${item.id}" data-level="${analysis.hint_level}">
                    <div><span class="feedback-label">Error Type:</span> ${analysis.primary_error_type}</div>
                    <div><span class="feedback-label">Explanation:</span> ${analysis.error_explanation}</div>
                    <div><span class="feedback-label">Hint (Level ${analysis.hint_level}):</span> ${analysis.hint}</div>
                    ${
                        analysis.recommended_knowledge_points && analysis.recommended_knowledge_points.length
                            ? `<div><span class="feedback-label">Knowledge Points:</span> ${analysis.recommended_knowledge_points.join(', ')}</div>`
                            : ''
                    }
                </div>
            `;

            if (analysis.hint_level < 3) {
                content += `<button class="secondary-btn" id="hint-btn-${item.id}" onclick="upgradeHint(${item.id})">Get Stronger Hint</button>`;
            }
            
            if (item.can_practice) {
                content += `<button class="practice-btn secondary-btn" onclick="startPractice(${item.id})">Practice Similar Question</button>`;
            }
        }

        card.innerHTML = content;
        feedbackContainer.appendChild(card);
    });
    if (window.MathJax && MathJax.typesetPromise) {
        MathJax.typesetPromise();
    }
}

function switchView(viewName) {
    loginView.classList.add('hidden');
    testView.classList.add('hidden');
    resultsView.classList.add('hidden');

    if (viewName === 'login') loginView.classList.remove('hidden');
    if (viewName === 'test') testView.classList.remove('hidden');
    if (viewName === 'results') resultsView.classList.remove('hidden');
}

// Practice Logic

async function startPractice(submissionItemId) {
    try {
        const response = await fetch(`${API_BASE}/practice/create`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                student_id: currentStudentId,
                original_submission_item_id: submissionItemId
            })
        });

        if (!response.ok) throw new Error('Failed to start practice');
        
        const data = await response.json();
        currentPracticeId = data.practice_id;
        const q = data.question;
        
        // Render Practice Question in Modal
        practiceContainer.innerHTML = '';
        practiceFeedback.classList.add('hidden');
        submitPracticeBtn.classList.remove('hidden');
        
        const card = document.createElement('div');
        card.className = 'question-card';
        card.innerHTML = `<div class="question-stem">${formatMathText(q.stem)}</div>`;
        
        const inputContainer = document.createElement('div');
        if (q.type === 'multiple_choice') {
            q.options.forEach(opt => {
                inputContainer.innerHTML += `
                    <div>
                        <label>
                            <input type="radio" name="practice-q" value="${opt.id}">
                            ${opt.id}. ${formatMathText(opt.text)}
                        </label>
                    </div>
                `;
            });
        } else {
            inputContainer.innerHTML = `<input type="text" name="practice-q" placeholder="Answer...">`;
        }
        
        card.appendChild(inputContainer);
        practiceContainer.appendChild(card);
        
        practiceModal.classList.remove('hidden');
        if (window.MathJax && MathJax.typesetPromise) {
            MathJax.typesetPromise();
        }
        
    } catch (err) {
        console.error(err);
        alert('Could not start practice session.');
    }
}

async function submitPractice() {
    let val = '';
    const radio = document.querySelector('input[name="practice-q"]:checked');
    const text = document.querySelector('input[name="practice-q"][type="text"]');
    
    if (radio) val = radio.value;
    if (text) val = text.value.trim();
    
    if (!val) {
        alert("Please answer.");
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/practice/${currentPracticeId}/submit`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                student_id: currentStudentId,
                answer: val
            })
        });
        
        if (!response.ok) throw new Error('Failed to submit practice');
        
        const result = await response.json();
        
        practiceFeedback.innerHTML = `
            <div class="${result.is_correct ? 'correct' : 'incorrect'}" style="padding:10px; margin-top:10px;">
                <strong>${result.is_correct ? 'Correct!' : 'Incorrect'}</strong>
                <p>${result.feedback}</p>
            </div>
        `;
        practiceFeedback.classList.remove('hidden');
        submitPracticeBtn.classList.add('hidden');
        
    } catch (err) {
        console.error(err);
        alert('Error submitting practice.');
    }
}

async function upgradeHint(submissionItemId) {
    const analysisBox = document.getElementById(`analysis-${submissionItemId}`);
    const btn = document.getElementById(`hint-btn-${submissionItemId}`);
    if (!analysisBox || !btn) return;

    const currentLevel = parseInt(analysisBox.dataset.level || '1', 10);
    const nextLevel = Math.min(3, currentLevel + 1);
    if (nextLevel === currentLevel) return;

    btn.disabled = true;
    const prevText = btn.textContent;
    btn.textContent = 'Loading...';

    try {
        const response = await fetch(`${API_BASE}/submission/items/${submissionItemId}/hint`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                student_id: currentStudentId,
                hint_level: nextLevel
            })
        });
        if (!response.ok) throw new Error('Failed to upgrade hint');

        const analysis = await response.json();
        analysisBox.dataset.level = analysis.hint_level;
        analysisBox.innerHTML = `
            <div><span class="feedback-label">Error Type:</span> ${analysis.primary_error_type}</div>
            <div><span class="feedback-label">Explanation:</span> ${analysis.error_explanation}</div>
            <div><span class="feedback-label">Hint (Level ${analysis.hint_level}):</span> ${analysis.hint}</div>
            ${
                analysis.recommended_knowledge_points && analysis.recommended_knowledge_points.length
                    ? `<div><span class="feedback-label">Knowledge Points:</span> ${analysis.recommended_knowledge_points.join(', ')}</div>`
                    : ''
            }
        `;

        if (analysis.hint_level >= 3) {
            btn.classList.add('hidden');
        } else {
            btn.disabled = false;
            btn.textContent = prevText;
        }
    } catch (err) {
        console.error(err);
        btn.disabled = false;
        btn.textContent = prevText;
        alert('Could not upgrade hint.');
    }
}