// ===== Simulado (Simulated Exam) Module ===== const Simulado = { // State simuladoId: null, questions: [], answers: {}, // { questionId: 'A' } currentIndex: 0, viewMode: 'single', // 'single' or 'all' timeLimit: 0, // seconds timeRemaining: 0, // seconds timerInterval: null, startTime: null, submitted: false, topicsCache: null, yearsCache: null, // ===== API ===== async loadTopics() { if (this.topicsCache) return this.topicsCache; const res = await fetch('/api/topics', { headers: Auth.headers() }); if (!res.ok) throw new Error('Erro ao carregar topicos'); const data = await res.json(); this.topicsCache = data.topics; return this.topicsCache; }, async loadYears() { if (this.yearsCache) return this.yearsCache; const res = await fetch('/api/years', { headers: Auth.headers() }); if (!res.ok) throw new Error('Erro ao carregar anos'); const data = await res.json(); this.yearsCache = data.years; return this.yearsCache; }, async generateExam(count, tracks, year) { const params = new URLSearchParams({ count, tracks, year }); const res = await fetch(`/api/simulado/generate?${params}`, { headers: Auth.headers() }); if (!res.ok) { const err = await res.json(); throw new Error(err.error || 'Erro ao gerar simulado'); } return await res.json(); }, async submitExam() { const timeSpent = Math.floor((Date.now() - this.startTime) / 1000); const res = await fetch('/api/simulado/submit', { method: 'POST', headers: Auth.headers(), body: JSON.stringify({ simulado_id: this.simuladoId, answers: this.answers, time_spent_seconds: timeSpent }) }); if (!res.ok) throw new Error('Erro ao enviar simulado'); return await res.json(); }, // ===== CONFIG SCREEN ===== async renderConfig() { const [topics, years] = await Promise.all([this.loadTopics(), this.loadYears()]); const topicChecks = topics.map(t => ` `).join(''); const yearOpts = years.map(y => ``).join(''); return `
← Voltar

Simulado

Numero de questoes

Ano (opcional)

Topicos

${topicChecks}
`; }, selectCount(btn) { document.querySelectorAll('.simulado-count-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); }, toggleAllTracks(checked) { document.querySelectorAll('#simulado-tracks input[type="checkbox"]').forEach(cb => { cb.checked = checked; }); }, async startExam() { const btn = document.getElementById('simulado-start-btn'); const errorEl = document.getElementById('simulado-config-error'); errorEl.style.display = 'none'; const countBtn = document.querySelector('.simulado-count-btn.active'); const count = countBtn ? parseInt(countBtn.dataset.count) : 50; const year = document.getElementById('simulado-year').value; const checkedBoxes = document.querySelectorAll('#simulado-tracks input:checked'); if (checkedBoxes.length === 0) { errorEl.textContent = 'Selecione pelo menos um topico.'; errorEl.style.display = 'block'; return; } const allBoxes = document.querySelectorAll('#simulado-tracks input[type="checkbox"]'); let tracks = 'all'; if (checkedBoxes.length < allBoxes.length) { tracks = Array.from(checkedBoxes).map(cb => cb.value).join(','); } btn.disabled = true; btn.textContent = 'Gerando simulado...'; try { const data = await this.generateExam(count, tracks, year); this.simuladoId = data.simulado_id; this.questions = data.questions; this.answers = {}; this.currentIndex = 0; this.viewMode = 'single'; this.timeLimit = data.time_limit_minutes * 60; this.timeRemaining = this.timeLimit; this.startTime = Date.now(); this.submitted = false; window.location.hash = '#/simulado/exam'; } catch (e) { errorEl.textContent = e.message; errorEl.style.display = 'block'; btn.disabled = false; btn.textContent = 'Iniciar Simulado'; } }, // ===== EXAM SCREEN ===== renderExam() { if (!this.questions.length) { return '

Nenhum simulado ativo. Configurar novo simulado

'; } this.startTimer(); const navButtons = this.questions.map((q, i) => { const answered = this.answers[q.id] ? 'answered' : ''; const current = i === this.currentIndex ? 'current' : ''; return ``; }).join(''); const answeredCount = Object.keys(this.answers).length; const totalCount = this.questions.length; let questionsHtml; if (this.viewMode === 'single') { questionsHtml = this.renderSingleQuestion(this.currentIndex); } else { questionsHtml = this.questions.map((q, i) => this.renderExamQuestion(q, i)).join(''); } return `
⏰ ${this.formatTime(this.timeRemaining)}
${answeredCount}/${totalCount} respondidas
Questoes
${navButtons}
Respondida Atual Pendente
${questionsHtml} ${this.viewMode === 'single' ? this.renderNavArrows() : ''}
`; }, renderSingleQuestion(index) { const q = this.questions[index]; if (!q) return ''; return this.renderExamQuestion(q, index); }, renderExamQuestion(q, index) { const token = Auth.getToken(); let enunciadoHtml = q.enunciado || ''; enunciadoHtml = enunciadoHtml.replace( /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi, (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"` ); enunciadoHtml = enunciadoHtml.replace( /https?:\/\/r2\.seudominio\.com\/([^"'?\s]+)/gi, (match, path) => `/api/images/${encodeURIComponent(path)}?token=${token}` ); const selectedAnswer = this.answers[q.id] || null; const alts = (q.alternativas || []).map(alt => { let altTexto = alt.texto || ''; const hasHtml = / `src="/api/images/${encodeURIComponent(filename)}?token=${token}"` ); altTexto = altTexto.replace( /https?:\/\/r2\.seudominio\.com\/([^"'?\s]+)/gi, (match, path) => `/api/images/${encodeURIComponent(path)}?token=${token}` ); } else { altTexto = this.escapeHtml(altTexto); } const selected = selectedAnswer === alt.letra ? 'selected' : ''; return `
${alt.letra}
${altTexto}
`; }).join(''); const yearBadge = q.year ? ` (${this.escapeHtml(q.year)})` : ''; const trackBadge = `${this.escapeHtml(q.track)}`; return `
${index + 1}

Questao ${index + 1} de ${this.questions.length}${yearBadge}

${trackBadge}
${enunciadoHtml}
${alts}
`; }, renderNavArrows() { const hasPrev = this.currentIndex > 0; const hasNext = this.currentIndex < this.questions.length - 1; return `
`; }, selectAnswer(qid, letra, el) { if (this.submitted) return; this.answers[qid] = letra; // Update UI const container = el.closest('.alternativas'); container.querySelectorAll('.alternativa').forEach(a => a.classList.remove('selected')); el.classList.add('selected'); // Update nav button this.updateNavButton(qid); this.updateProgress(); }, updateNavButton(qid) { const idx = this.questions.findIndex(q => q.id === qid); if (idx === -1) return; const navBtns = document.querySelectorAll('.simulado-nav-btn'); if (navBtns[idx]) { navBtns[idx].classList.add('answered'); } }, updateProgress() { const answeredCount = Object.keys(this.answers).length; const totalCount = this.questions.length; const center = document.querySelector('.simulado-timer-center span'); if (center) center.textContent = `${answeredCount}/${totalCount} respondidas`; }, goToQuestion(index) { if (index < 0 || index >= this.questions.length) return; this.currentIndex = index; if (this.viewMode === 'single') { const content = document.getElementById('simulado-content'); if (content) { content.innerHTML = this.renderSingleQuestion(index) + this.renderNavArrows(); } // Update nav highlights document.querySelectorAll('.simulado-nav-btn').forEach((btn, i) => { btn.classList.toggle('current', i === index); }); } else { // Scroll to question const el = document.querySelector(`.simulado-question[data-index="${index}"]`); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' }); document.querySelectorAll('.simulado-nav-btn').forEach((btn, i) => { btn.classList.toggle('current', i === index); }); } }, toggleViewMode() { this.viewMode = this.viewMode === 'single' ? 'all' : 'single'; // Re-render the exam page content document.getElementById('app').innerHTML = this.renderExam(); }, // ===== TIMER ===== startTimer() { this.stopTimer(); this.timerInterval = setInterval(() => { this.timeRemaining--; const timerText = document.getElementById('simulado-timer-text'); if (timerText) { timerText.textContent = this.formatTime(this.timeRemaining); } // Warning colors const timerBar = document.getElementById('simulado-timer'); if (timerBar) { if (this.timeRemaining <= 60) { timerBar.classList.add('danger'); timerBar.classList.remove('warning'); } else if (this.timeRemaining <= 300) { timerBar.classList.add('warning'); timerBar.classList.remove('danger'); } } if (this.timeRemaining <= 0) { this.stopTimer(); this.finishExam(); } }, 1000); }, stopTimer() { if (this.timerInterval) { clearInterval(this.timerInterval); this.timerInterval = null; } }, formatTime(seconds) { if (seconds < 0) seconds = 0; const h = Math.floor(seconds / 3600); const m = Math.floor((seconds % 3600) / 60); const s = seconds % 60; if (h > 0) { return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`; } return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`; }, // ===== FINISH ===== confirmFinish() { const answered = Object.keys(this.answers).length; const total = this.questions.length; const unanswered = total - answered; let msg = 'Deseja finalizar o simulado?'; if (unanswered > 0) { msg = `Voce ainda tem ${unanswered} questao(oes) sem resposta. Deseja finalizar mesmo assim?`; } if (confirm(msg)) { this.finishExam(); } }, async finishExam() { this.stopTimer(); this.submitted = true; const app = document.getElementById('app'); app.innerHTML = '
Calculando resultado...
'; try { const result = await this.submitExam(); app.innerHTML = this.renderResults(result); } catch (e) { app.innerHTML = `

Erro

${this.escapeHtml(e.message)}

`; } }, // ===== RESULTS SCREEN ===== renderResults(result) { const { score, total, percentage, time_spent_seconds, details } = result; let colorClass = 'results-red'; if (percentage >= 70) colorClass = 'results-green'; else if (percentage >= 50) colorClass = 'results-yellow'; const timeStr = this.formatTime(time_spent_seconds); // Separate wrong answers for review const wrongAnswers = details.filter(d => !d.is_correct); let wrongHtml = ''; if (wrongAnswers.length > 0) { const wrongCards = wrongAnswers.map(d => { const q = this.questions.find(q => q.id === d.question_id); if (!q) return ''; const token = Auth.getToken(); let snippet = (q.enunciado || '').replace(/<[^>]+>/g, ''); snippet = snippet.length > 200 ? snippet.substring(0, 200) + '...' : snippet; // Process explanation let explanationHtml = ''; if (d.explanation && !d.explanation.includes('Carregando gabarito') && d.explanation.trim().length > 20) { let expText = d.explanation; expText = expText.replace( /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi, (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"` ); expText = expText.replace(/color:\s*white/gi, 'color: #1a1a1a'); expText = expText.replace(/color:\s*#fff(fff)?/gi, 'color: #1a1a1a'); explanationHtml = `
${expText}
`; } return `
${this.escapeHtml(q.track)}

${this.escapeHtml(snippet)}

Sua resposta: ${this.escapeHtml(d.selected)} Correta: ${this.escapeHtml(d.correct)}
${explanationHtml}
`; }).join(''); wrongHtml = `

Revisao de erros (${wrongAnswers.length})

${wrongCards}
`; } return `

Resultado do Simulado

${percentage}%
${score}/${total}
${score}
Acertos
${total - score}
Erros
${timeStr}
Tempo
${wrongHtml}
`; }, // ===== CLEANUP ===== cleanup() { this.stopTimer(); }, escapeHtml(str) { if (!str) return ''; const div = document.createElement('div'); div.textContent = str; return div.innerHTML; } };