// ===== Main SPA Router ===== const App = { topicsCache: null, _hashListenerAttached: false, async init(skipValidation) { if (!Auth.getToken()) { this.showLogin(); return; } // Skip server validation when called right after login (token is fresh) if (!skipValidation) { try { const res = await fetch('/api/auth/me', { headers: Auth.headers() }); if (!res.ok) throw new Error('Token invalid'); } catch (e) { Auth.clearSession(); this.showLogin(); return; } } // Protection.init() must never break the app try { Protection.init(); } catch(e) { console.warn('[App] Protection.init error:', e); } try { Heartbeat.init(); } catch(e) { console.warn('[App] Heartbeat.init error:', e); } this.renderHeader(); this.handleRoute(); if (!this._hashListenerAttached) { this._hashListenerAttached = true; window.addEventListener('hashchange', () => this.handleRoute()); } }, showLogin() { document.getElementById('app').innerHTML = `

MedMembers OFT 2026

Banco de Questoes - Acesso Restrito

`; }, async handleLogin(e) { e.preventDefault(); const email = document.getElementById('login-email').value; const password = document.getElementById('login-password').value; const btn = document.getElementById('login-btn'); const errorEl = document.getElementById('login-error'); btn.disabled = true; btn.textContent = 'Entrando...'; errorEl.style.display = 'none'; try { await Auth.login(email, password); // Use replaceState to avoid hashchange firing history.replaceState(null, '', '#/'); await this.init(true); // skip re-validation, token is fresh } catch (err) { errorEl.textContent = err.message; errorEl.style.display = 'block'; btn.disabled = false; btn.textContent = 'Entrar'; } }, renderHeader() { const user = Auth.getUser(); const header = document.getElementById('app-header'); if (!header) { const h = document.createElement('header'); h.className = 'app-header'; h.id = 'app-header'; h.innerHTML = `
${user.role === 'admin' ? '' : ''} ${this.escapeHtml(user.email)}
`; document.body.insertBefore(h, document.getElementById('app')); } }, async handleRoute() { const hash = window.location.hash.slice(1) || '/'; const app = document.getElementById('app'); app.innerHTML = '
Carregando...
'; try { // Clean up simulado timer when navigating away if (!hash.startsWith('/simulado')) { Simulado.cleanup(); } if (hash === '/' || hash === '') { await this.showTopics(); } else if (hash.startsWith('/topic/')) { const parts = hash.split('?'); const slug = parts[0].replace('/topic/', ''); const params = new URLSearchParams(parts[1] || ''); const page = parseInt(params.get('page')) || 1; const year = params.get('year') || ''; await this.showQuestions(slug, page, year); } else if (hash === '/simulado') { await this.showSimuladoConfig(); } else if (hash === '/simulado/exam') { this.showSimuladoExam(); } else if (hash === '/stats') { await this.showStats(); } else if (hash === '/admin') { await this.showAdmin(); } else { app.innerHTML = '

Pagina nao encontrada

'; } } catch (e) { console.error('[App] handleRoute error:', e); // Only clear session on explicit 401 HTTP status, not on generic errors if (e.message === 'HTTP 401') { Auth.clearSession(); this.showLogin(); return; } app.innerHTML = `

Erro

${this.escapeHtml(e.message)}

`; } try { Protection.updateWatermark(); } catch(e) {} window.scrollTo(0, 0); }, async showTopics() { if (!this.topicsCache) { this.topicsCache = await Questions.loadTopics(); } document.getElementById('app').innerHTML = Questions.renderTopicsPage(this.topicsCache); }, async showQuestions(slug, page, year) { if (!this.topicsCache) { this.topicsCache = await Questions.loadTopics(); } const topic = this.topicsCache.find(t => t.slug === slug); const topicName = topic ? topic.name : slug; const [data, years] = await Promise.all([ Questions.loadQuestions(slug, page, year), Questions.loadYears() ]); document.getElementById('app').innerHTML = Questions.renderQuestionsPage(data, topicName, slug, year, years); }, async showSimuladoConfig() { document.getElementById('app').innerHTML = await Simulado.renderConfig(); }, showSimuladoExam() { document.getElementById('app').innerHTML = Simulado.renderExam(); }, async showAdmin() { document.getElementById('app').innerHTML = await Admin.render(); }, async showStats() { const app = document.getElementById('app'); try { const [statsRes, historyRes] = await Promise.all([ fetch('/api/user/stats', { headers: Auth.headers() }), fetch('/api/user/history?page=1&per_page=15', { headers: Auth.headers() }) ]); if (!statsRes.ok || !historyRes.ok) throw new Error('Erro ao carregar estatisticas'); const stats = await statsRes.json(); const history = await historyRes.json(); let html = `
← Voltar

Suas Estatisticas

${stats.accuracy}%
Aproveitamento Geral
${stats.total_answered}
Respondidas
${stats.total_correct}
Corretas
${stats.total_answered - stats.total_correct}
Erradas
`; // Per-track bar chart if (stats.tracks && stats.tracks.length > 0) { html += '

Desempenho por Topico

'; html += '
'; for (const t of stats.tracks) { const barColor = t.percentage >= 70 ? 'var(--correct)' : t.percentage >= 50 ? 'var(--accent)' : 'var(--wrong)'; html += `
${this.escapeHtml(t.track)}
${t.percentage}%
${t.correct}/${t.total}
`; } html += '
'; } // Recent history if (history.history && history.history.length > 0) { html += '

Historico Recente

'; html += '
'; for (const h of history.history) { const icon = h.is_correct ? '✓' : '✗'; const date = h.answered_at ? new Date(h.answered_at + 'Z').toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : ''; html += `
${icon}
${this.escapeHtml(h.track)} - Q${h.numero}
${this.escapeHtml(h.snippet)}
Resp: ${h.selected_answer} | Gab: ${h.correct_answer} ${date}
`; } html += '
'; } else { html += '

Nenhuma questao respondida ainda. Comece respondendo questoes para ver suas estatisticas!

'; } html += '
'; app.innerHTML = html; } catch (e) { app.innerHTML = `

Erro

${this.escapeHtml(e.message)}

`; } }, navigate(path) { window.location.hash = '#' + path; }, escapeHtml(str) { if (!str) return ''; const div = document.createElement('div'); div.textContent = str; return div.innerHTML; }, // ===== Forgot Password Flow ===== _forgotEmail: '', showForgotPassword() { document.getElementById('app').innerHTML = `

Recuperar Senha

Informe seu email para receber o codigo de verificacao.

Digite o codigo de 6 digitos enviado para seu email.

Escolha sua nova senha.

`; }, _forgotShowError(msg) { const el = document.getElementById('forgot-error'); el.textContent = msg; el.style.display = 'block'; const s = document.getElementById('forgot-success'); if (s) s.style.display = 'none'; }, _forgotShowSuccess(msg) { const el = document.getElementById('forgot-success'); el.textContent = msg; el.style.display = 'block'; const e = document.getElementById('forgot-error'); if (e) e.style.display = 'none'; }, _forgotGoToStep(step) { document.querySelectorAll('.forgot-step').forEach(el => el.classList.remove('active')); document.getElementById(`forgot-step-${step}`).classList.add('active'); for (let i = 1; i <= 3; i++) { const dot = document.getElementById(`dot-${i}`); dot.classList.remove('active', 'done'); if (i < step) dot.classList.add('done'); else if (i === step) dot.classList.add('active'); } const err = document.getElementById('forgot-error'); const suc = document.getElementById('forgot-success'); if (err) err.style.display = 'none'; if (suc) suc.style.display = 'none'; }, async forgotSendCode(e) { e.preventDefault(); const email = document.getElementById('forgot-email').value.trim(); const btn = document.getElementById('forgot-send-btn'); btn.disabled = true; btn.textContent = 'Enviando...'; try { const res = await fetch('/api/auth/forgot-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) }); const data = await res.json(); if (!res.ok) { this._forgotShowError(data.error || 'Erro ao enviar codigo'); btn.disabled = false; btn.textContent = 'Enviar codigo'; return; } this._forgotEmail = email; this._forgotGoToStep(2); this._forgotShowSuccess('Se o email estiver cadastrado, voce recebera um codigo de verificacao.'); } catch (err) { this._forgotShowError('Erro de conexao.'); btn.disabled = false; btn.textContent = 'Enviar codigo'; } }, async forgotVerifyCode(e) { e.preventDefault(); const code = document.getElementById('forgot-code').value.trim(); if (code.length !== 6 || !/^\d{6}$/.test(code)) { this._forgotShowError('O codigo deve ter 6 digitos numericos.'); return; } this._forgotCode = code; this._forgotGoToStep(3); }, async forgotResetPassword(e) { e.preventDefault(); const newPass = document.getElementById('forgot-new-pass').value; const confirmPass = document.getElementById('forgot-confirm-pass').value; const btn = document.getElementById('forgot-reset-btn'); if (newPass !== confirmPass) { this._forgotShowError('As senhas nao coincidem.'); return; } if (newPass.length < 6) { this._forgotShowError('A senha deve ter no minimo 6 caracteres.'); return; } btn.disabled = true; btn.textContent = 'Redefinindo...'; try { const res = await fetch('/api/auth/reset-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: this._forgotEmail, code: this._forgotCode, new_password: newPass }) }); const data = await res.json(); if (!res.ok) { this._forgotShowError(data.error || 'Erro ao redefinir senha'); btn.disabled = false; btn.textContent = 'Redefinir senha'; return; } document.querySelectorAll('.forgot-step').forEach(el => el.classList.remove('active')); for (let i = 1; i <= 3; i++) { document.getElementById(`dot-${i}`).classList.remove('active'); document.getElementById(`dot-${i}`).classList.add('done'); } this._forgotShowSuccess('Senha redefinida com sucesso! Redirecionando para o login...'); setTimeout(() => this.showLogin(), 2500); } catch (err) { this._forgotShowError('Erro de conexao.'); btn.disabled = false; btn.textContent = 'Redefinir senha'; } } }; // Boot document.addEventListener('DOMContentLoaded', () => App.init());