document.addEventListener('DOMContentLoaded', () => { // ---------------------------------------------------- // Elements // ---------------------------------------------------- const categoryFilterPills = document.getElementById('categoryFilterPills'); const examCardsStrip = document.getElementById('examCardsStrip'); const btnSyncExams = document.getElementById('btnSyncExams'); const btnEmptySync = document.getElementById('btnEmptySync'); const examsAlert = document.getElementById('examsAlert'); // Subtabs const subtabBreakdown = document.getElementById('subtabBreakdown'); const subtabWeakness = document.getElementById('subtabWeakness'); const breakdownView = document.getElementById('breakdownView'); const weaknessView = document.getElementById('weaknessView'); const weaknessContainer = document.getElementById('weaknessContainer'); const weaknessLoading = document.getElementById('weaknessLoading'); // Mistake Review Modal const btnReviewMistakes = document.getElementById('btnReviewMistakes'); const mistakeModal = document.getElementById('mistakeModal'); const btnMistakeModalClose = document.getElementById('btnMistakeModalClose'); const modalLessonPills = document.getElementById('modalLessonPills'); const modalTypeBtns = document.querySelectorAll('.modal-type-btn'); const questionsGrid = document.getElementById('questionsGrid'); const mistakeLoading = document.getElementById('mistakeLoading'); const mistakeModalTitle = document.getElementById('mistakeModalTitle'); const mistakeModalSubtitle = document.getElementById('mistakeModalSubtitle'); // Lightbox const imageLightbox = document.getElementById('imageLightbox'); const lightboxImg = document.getElementById('lightboxImg'); const btnLightboxClose = document.getElementById('btnLightboxClose'); // State let currentExamId = btnReviewMistakes ? btnReviewMistakes.getAttribute('data-exam-id') : null; let cachedQuestions = null; // raw fetched questions by subject let activeLessonFilter = 'ALL'; let activeTypeFilter = 'all'; // 'all' | 'wrong' | 'empty' let cachedWeaknesses = null; // ---------------------------------------------------- // Helper: Show Alert // ---------------------------------------------------- function showAlert(msg, type = 'info') { if (!examsAlert) return; examsAlert.className = `alert alert-${type}`; examsAlert.textContent = msg; examsAlert.classList.remove('hidden'); setTimeout(() => { examsAlert.classList.add('hidden'); }, 4000); } // ---------------------------------------------------- // Category Filter (All / TYT / AYT) // ---------------------------------------------------- if (categoryFilterPills && examCardsStrip) { categoryFilterPills.addEventListener('click', (e) => { const btn = e.target.closest('.filter-pill'); if (!btn) return; categoryFilterPills.querySelectorAll('.filter-pill').forEach(b => b.classList.remove('active')); btn.classList.add('active'); const category = btn.getAttribute('data-category'); const cards = examCardsStrip.querySelectorAll('.exam-pill-card'); cards.forEach(card => { const cardCat = card.getAttribute('data-category'); if (category === 'ALL' || cardCat === category) { card.style.display = ''; } else { card.style.display = 'none'; } }); }); } // ---------------------------------------------------- // Exam Card Switching // ---------------------------------------------------- if (examCardsStrip) { examCardsStrip.addEventListener('click', (e) => { const card = e.target.closest('.exam-pill-card'); if (!card) return; const examId = card.getAttribute('data-id'); if (examId && examId !== currentExamId) { window.location.href = `/exams?id=${encodeURIComponent(examId)}`; } }); } // ---------------------------------------------------- // Sync Exams Action // ---------------------------------------------------- async function handleSync() { if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { showAlert('Çevrimdışı moddasınız. Sınav senkronizasyonu için internet bağlantısı gereklidir.', 'danger'); return; } const triggerBtn = btnSyncExams || btnEmptySync; if (triggerBtn) { triggerBtn.disabled = true; triggerBtn.textContent = 'Syncing...'; } try { const res = await fetch('/api/exams/sync', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); const data = await res.json(); if (data.success) { window.location.reload(); } else { showAlert(data.error || 'Failed to sync exams', 'danger'); if (triggerBtn) { triggerBtn.disabled = false; triggerBtn.textContent = 'Sync Exams'; } } } catch (err) { showAlert('Connection error while syncing exams.', 'danger'); if (triggerBtn) { triggerBtn.disabled = false; triggerBtn.textContent = 'Sync Exams'; } } } if (btnSyncExams) btnSyncExams.addEventListener('click', handleSync); if (btnEmptySync) btnEmptySync.addEventListener('click', handleSync); // ---------------------------------------------------- // Subtabs Toggle (Breakdown vs Weaknesses) // ---------------------------------------------------- if (subtabBreakdown && subtabWeakness) { subtabBreakdown.addEventListener('click', () => { subtabBreakdown.classList.add('active'); subtabWeakness.classList.remove('active'); breakdownView.classList.remove('hidden'); weaknessView.classList.add('hidden'); }); subtabWeakness.addEventListener('click', async () => { subtabWeakness.classList.add('active'); subtabBreakdown.classList.remove('active'); weaknessView.classList.remove('hidden'); breakdownView.classList.add('hidden'); if (!cachedWeaknesses && currentExamId) { await loadTopicWeaknesses(currentExamId); } }); } async function loadTopicWeaknesses(examId) { weaknessLoading.classList.remove('hidden'); weaknessContainer.innerHTML = ''; try { const res = await fetch(`/api/exams/${encodeURIComponent(examId)}/weaknesses`); const data = await res.json(); weaknessLoading.classList.add('hidden'); if (data.success && data.weaknesses && data.weaknesses.length > 0) { cachedWeaknesses = data.weaknesses; renderTopicWeaknesses(data.weaknesses); } else { weaknessContainer.innerHTML = `

Bu sınav için henüz zayıf konu kaydı bulunamadı veya tüm konularda tam başarı sağlandı.

`; } } catch (err) { weaknessLoading.classList.add('hidden'); weaknessContainer.innerHTML = `
Zayıf konu raporu yüklenirken bir hata oluştu.
`; } } function renderTopicWeaknesses(weaknesses) { // Sort weaknesses by most wrong answers, then lowest success rate const sorted = [...weaknesses].sort((a, b) => { if (b.wrongCount !== a.wrongCount) return b.wrongCount - a.wrongCount; return a.successRate - b.successRate; }); let html = '
'; sorted.forEach(item => { const fillClass = item.successRate >= 70 ? 'fill-high' : item.successRate >= 40 ? 'fill-mid' : 'fill-low'; html += `
${escapeHtml(item.subjectName)} ${item.successRate}%
${escapeHtml(item.topicName)}
Toplam: ${item.totalCount} Doğru: ${item.correctCount} Yanlış: ${item.wrongCount} Boş: ${item.emptyCount}
`; }); html += '
'; weaknessContainer.innerHTML = html; } // ---------------------------------------------------- // Inline Mistake Review Modal // ---------------------------------------------------- function openReviewModal(targetSubjectName = null) { if (!mistakeModal || !currentExamId) return; mistakeModal.classList.remove('hidden'); document.body.style.overflow = 'hidden'; if (!cachedQuestions) { loadExamQuestions(targetSubjectName); } else { if (targetSubjectName) { activeLessonFilter = targetSubjectName; } updateModalLessonPills(); renderQuestions(); } } function closeReviewModal() { if (!mistakeModal) return; mistakeModal.classList.add('hidden'); document.body.style.overflow = ''; } if (btnReviewMistakes) { btnReviewMistakes.addEventListener('click', () => openReviewModal()); } if (btnMistakeModalClose) { btnMistakeModalClose.addEventListener('click', closeReviewModal); } // Clicking clickable mistake badge in table document.querySelectorAll('.clickable-mistake-btn').forEach(btn => { btn.addEventListener('click', (e) => { e.stopPropagation(); const subjectName = btn.getAttribute('data-subject-name'); openReviewModal(subjectName); }); }); // Close modal when clicking outside dialog if (mistakeModal) { mistakeModal.addEventListener('click', (e) => { if (e.target === mistakeModal) { closeReviewModal(); } }); } // Escape key closes modal & lightbox document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { if (imageLightbox && !imageLightbox.classList.contains('hidden')) { closeLightbox(); } else if (mistakeModal && !mistakeModal.classList.contains('hidden')) { closeReviewModal(); } } }); async function loadExamQuestions(initialSubjectFilter = null) { mistakeLoading.classList.remove('hidden'); questionsGrid.innerHTML = ''; modalLessonPills.innerHTML = ''; try { // Fetch both Wrong (Y) and Empty (B) questions const [wrongRes, emptyRes] = await Promise.all([ fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=Y`).then(r => r.json()), fetch(`/api/exams/${encodeURIComponent(currentExamId)}/questions?tip=B`).then(r => r.json()) ]); mistakeLoading.classList.add('hidden'); const subjectsMap = {}; if (wrongRes.success && wrongRes.subjects) { wrongRes.subjects.forEach(s => { if (!subjectsMap[s.subjectName]) { subjectsMap[s.subjectName] = { subjectName: s.subjectName, subjectId: s.subjectId, questions: [] }; } s.questions.forEach(q => { q.subjectName = s.subjectName; subjectsMap[s.subjectName].questions.push(q); }); }); } if (emptyRes.success && emptyRes.subjects) { emptyRes.subjects.forEach(s => { if (!subjectsMap[s.subjectName]) { subjectsMap[s.subjectName] = { subjectName: s.subjectName, subjectId: s.subjectId, questions: [] }; } s.questions.forEach(q => { q.subjectName = s.subjectName; subjectsMap[s.subjectName].questions.push(q); }); }); } cachedQuestions = Object.values(subjectsMap); if (initialSubjectFilter && subjectsMap[initialSubjectFilter]) { activeLessonFilter = initialSubjectFilter; } else { activeLessonFilter = 'ALL'; } updateModalLessonPills(); renderQuestions(); } catch (err) { mistakeLoading.classList.add('hidden'); questionsGrid.innerHTML = `
Sorular yüklenirken bir hata oluştu.
`; } } function updateModalLessonPills() { if (!modalLessonPills || !cachedQuestions) return; let totalAll = 0; cachedQuestions.forEach(s => { totalAll += s.questions.length; }); let html = ` `; cachedQuestions.forEach(s => { const count = s.questions.length; html += ` `; }); modalLessonPills.innerHTML = html; } if (modalLessonPills) { modalLessonPills.addEventListener('click', (e) => { const btn = e.target.closest('.modal-lesson-btn'); if (!btn) return; modalLessonPills.querySelectorAll('.modal-lesson-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); activeLessonFilter = btn.getAttribute('data-lesson'); renderQuestions(); }); } // Type filter inside modal (all / wrong / empty) modalTypeBtns.forEach(btn => { btn.addEventListener('click', () => { modalTypeBtns.forEach(b => b.classList.remove('active')); btn.classList.add('active'); activeTypeFilter = btn.getAttribute('data-type'); renderQuestions(); }); }); function renderQuestions() { if (!questionsGrid || !cachedQuestions) return; let filteredList = []; cachedQuestions.forEach(s => { if (activeLessonFilter === 'ALL' || activeLessonFilter === s.subjectName) { s.questions.forEach(q => { if (activeTypeFilter === 'all') { filteredList.push(q); } else if (activeTypeFilter === 'wrong' && q.status === 'wrong') { filteredList.push(q); } else if (activeTypeFilter === 'empty' && q.status === 'empty') { filteredList.push(q); } }); } }); // Sort by question number ascending filteredList.sort((a, b) => a.questionNumber - b.questionNumber); if (filteredList.length === 0) { questionsGrid.innerHTML = `

Seçili filtrelere uygun soru bulunamadı.

`; return; } let html = ''; filteredList.forEach(q => { const isWrong = q.status === 'wrong'; const studentClass = isWrong ? 'answer-student-wrong' : 'answer-student-empty'; const studentText = isWrong ? q.studentAnswer : 'Boş'; html += `
Soru #${q.questionNumber} ${escapeHtml(q.subjectName || '')}
Doğru: ${escapeHtml(q.correctAnswer)} Öğrenci: ${escapeHtml(studentText)}
${ q.imageUrl ? `
Soru ${q.questionNumber}
` : `
Soru görseli bulunamadı.
` }
`; }); questionsGrid.innerHTML = html; // Attach click-to-zoom on images questionsGrid.querySelectorAll('.question-img').forEach(img => { img.addEventListener('click', () => { openLightbox(img.src); }); }); } // ---------------------------------------------------- // Lightbox Zoom // ---------------------------------------------------- function openLightbox(src) { if (!imageLightbox || !lightboxImg) return; lightboxImg.src = src; imageLightbox.classList.remove('hidden'); } function closeLightbox() { if (!imageLightbox) return; imageLightbox.classList.add('hidden'); if (lightboxImg) lightboxImg.src = ''; } if (btnLightboxClose) { btnLightboxClose.addEventListener('click', closeLightbox); } if (imageLightbox) { imageLightbox.addEventListener('click', (e) => { if (e.target === imageLightbox || e.target === btnLightboxClose) { closeLightbox(); } }); } // ---------------------------------------------------- // Utility: Escape HTML // ---------------------------------------------------- function escapeHtml(str) { if (!str) return ''; return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } });