document.addEventListener('DOMContentLoaded', () => { const assignmentList = document.getElementById('assignmentList'); const searchInput = document.getElementById('searchInput'); const searchClear = document.getElementById('searchClear'); const subjectSelect = document.getElementById('subjectSelect'); const filterTabs = document.getElementById('filterTabs'); const filteredCountText = document.getElementById('filteredCountText'); const noResults = document.getElementById('noResults'); const btnResetFilters = document.getElementById('btnResetFilters'); const syncAlert = document.getElementById('syncAlert'); const btnSyncRecent = document.getElementById('btnSyncRecent'); const btnSyncAll = document.getElementById('btnSyncAll'); const subjectToggleHeader = document.getElementById('subjectToggleHeader'); const subjectBreakdownBody = document.getElementById('subjectBreakdownBody'); const subjectToggleIcon = document.getElementById('subjectToggleIcon'); let currentTab = 'all'; let currentSearch = ''; let currentSubject = ''; function t(key, params) { if (typeof window.BeKulturT === 'function') { return window.BeKulturT(key, params); } return key; } // Checkbox toggle if (assignmentList) { assignmentList.addEventListener('click', async (e) => { const target = e.target; // Exclude / Restore button if (target.classList.contains('btn-exclude') || target.classList.contains('btn-disinclude')) { if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { alert(t('dashboard.offlineExcludeAlert')); return; } const assignmentId = target.dataset.id; const card = target.closest('.assignment-card'); if (!card) return; const currentExcluded = card.dataset.excluded === 'true'; const newExcluded = !currentExcluded; target.disabled = true; try { const res = await fetch('/api/exclude', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ assignmentId, excluded: newExcluded }) }); const data = await res.json(); if (data.success && data.stats) { card.dataset.excluded = newExcluded ? 'true' : 'false'; card.classList.toggle('is-excluded', newExcluded); target.textContent = newExcluded ? t('dashboard.btnRestore') : t('dashboard.btnExclude'); target.title = newExcluded ? t('dashboard.btnRestoreTitle') : t('dashboard.btnExcludeTitle'); const checkbox = card.querySelector('.assignment-toggle'); if (checkbox) checkbox.disabled = newExcluded; let badgeExcluded = card.querySelector('.badge-excluded'); if (newExcluded && !badgeExcluded) { const badgesContainer = card.querySelector('.card-badges'); if (badgesContainer) { const b = document.createElement('span'); b.className = 'badge badge-excluded'; b.textContent = t('dashboard.badgeExcluded'); badgesContainer.insertBefore(b, target); } } else if (!newExcluded && badgeExcluded) { badgeExcluded.remove(); } updateStatsUI(data.stats); applyFilters(); } } catch (err) { console.error('Failed to toggle exclude:', err); } finally { target.disabled = false; } return; } }); assignmentList.addEventListener('change', async (e) => { const target = e.target; if (!target.classList.contains('assignment-toggle')) return; if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { target.checked = !target.checked; alert(t('dashboard.offlineToggleAlert')); return; } const assignmentId = target.dataset.id; const isChecked = target.checked; const card = target.closest('.assignment-card'); if (!card) return; if (isChecked) { card.classList.add('is-completed'); card.dataset.completed = 'true'; updateCardBadge(card, 'completed'); } else { card.classList.remove('is-completed'); card.dataset.completed = 'false'; updateCardBadge(card, card.dataset.status); } try { const res = await fetch('/api/toggle', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ assignmentId, completed: isChecked }) }); const data = await res.json(); if (data.success && data.stats) { updateStatsUI(data.stats); applyFilters(); } } catch (err) { console.error('Failed to toggle assignment:', err); } }); } function updateCardBadge(card, status) { const badgesContainer = card.querySelector('.card-badges'); if (!badgesContainer) return; let existingStatusBadge = badgesContainer.querySelector( '.badge-completed, .badge-next-week, .badge-due-soon, .badge-overdue, .badge-active' ); if (existingStatusBadge) { if (status === 'completed') { existingStatusBadge.className = 'badge badge-completed'; existingStatusBadge.textContent = t('dashboard.badgeCompleted'); } else { const orig = card.dataset.status; if (orig === 'next-week') { existingStatusBadge.className = 'badge badge-next-week'; existingStatusBadge.textContent = t('dashboard.badgeNextWeek'); } else if (orig === 'due-soon') { existingStatusBadge.className = 'badge badge-due-soon'; existingStatusBadge.textContent = t('dashboard.badgeDueSoon'); } else if (orig === 'overdue') { existingStatusBadge.className = 'badge badge-overdue'; existingStatusBadge.textContent = t('dashboard.badgeOverdue'); } else { existingStatusBadge.className = 'badge badge-active'; existingStatusBadge.textContent = t('dashboard.badgeActive'); } } } } function updateStatsUI(stats) { const statCompRate = document.getElementById('statCompletionRate'); const statCompFrac = document.getElementById('statCompletionFraction'); const progressBar = document.getElementById('progressBarFill'); const statActive = document.getElementById('statActiveCount'); const statNextWeek = document.getElementById('statNextWeekCount'); const statDueSoon = document.getElementById('statDueSoonCount'); const statOverdue = document.getElementById('statOverdueCount'); const statTotal = document.getElementById('statTotalCount'); if (statCompRate) statCompRate.textContent = `${stats.completionRate}%`; if (statCompFrac) statCompFrac.textContent = `${stats.completed} / ${stats.total} ${t('dashboard.statDoneUnit')}`; if (progressBar) progressBar.style.width = `${stats.completionRate}%`; if (statActive) statActive.textContent = stats.active; if (statNextWeek) statNextWeek.textContent = stats.checkedNextWeek; if (statDueSoon) statDueSoon.textContent = stats.dueSoon; if (statOverdue) statOverdue.textContent = stats.overdue; if (statTotal) statTotal.textContent = stats.total; const tabAll = document.getElementById('tabAllCount'); const tabNext = document.getElementById('tabNextWeekCount'); const tabAct = document.getElementById('tabActiveCount'); const tabDue = document.getElementById('tabDueSoonCount'); const tabComp = document.getElementById('tabCompletedCount'); const tabOver = document.getElementById('tabOverdueCount'); const tabExcluded = document.getElementById('tabExcludedCount'); if (tabAll) tabAll.textContent = stats.total; if (tabNext) tabNext.textContent = stats.checkedNextWeek; if (tabAct) tabAct.textContent = stats.active; if (tabDue) tabDue.textContent = stats.dueSoon; if (tabComp) tabComp.textContent = stats.completed; if (tabOver) tabOver.textContent = stats.overdue; if (tabExcluded) tabExcluded.textContent = stats.excludedCount || 0; if (stats.bySubject) { Object.values(stats.bySubject).forEach(s => { const item = document.querySelector(`.subject-item[data-subject="${CSS.escape(s.subject)}"]`); if (item) { const frac = item.querySelector('.subject-fraction'); const fill = item.querySelector('.subject-bar-fill'); if (frac) frac.textContent = `${s.completed}/${s.total} (${s.percentage}%)`; if (fill) fill.style.width = `${s.percentage}%`; } }); } } // Filter tabs if (filterTabs) { filterTabs.addEventListener('click', (e) => { const btn = e.target.closest('.tab-btn'); if (!btn) return; filterTabs.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); btn.classList.add('active'); currentTab = btn.dataset.filter || 'all'; applyFilters(); }); } function normalizeTurkish(str) { if (!str) return ''; return str .replace(/İ/g, 'i') .replace(/I/g, 'ı') .toLowerCase(); } if (searchInput) { searchInput.addEventListener('input', (e) => { currentSearch = normalizeTurkish(e.target.value.trim()); if (searchClear) searchClear.classList.toggle('hidden', currentSearch.length === 0); applyFilters(); }); } if (searchClear) { searchClear.addEventListener('click', () => { searchInput.value = ''; currentSearch = ''; searchClear.classList.add('hidden'); applyFilters(); }); } if (subjectSelect) { subjectSelect.addEventListener('change', (e) => { currentSubject = e.target.value; applyFilters(); }); } if (btnResetFilters) { btnResetFilters.addEventListener('click', () => { currentTab = 'all'; currentSearch = ''; currentSubject = ''; if (searchInput) searchInput.value = ''; if (searchClear) searchClear.classList.add('hidden'); if (subjectSelect) subjectSelect.value = ''; if (filterTabs) { filterTabs.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); const allTab = filterTabs.querySelector('[data-filter="all"]'); if (allTab) allTab.classList.add('active'); } applyFilters(); }); } function applyFilters() { if (!assignmentList) return; const cards = assignmentList.querySelectorAll('.assignment-card'); let visibleCount = 0; cards.forEach(card => { const status = card.dataset.status; const isCompleted = card.dataset.completed === 'true'; const isExcluded = card.dataset.excluded === 'true'; const subject = card.dataset.subject; const searchText = card.dataset.search || ''; let matchesTab = true; if (currentTab === 'excluded') { matchesTab = isExcluded; } else { if (isExcluded) { matchesTab = false; } else if (currentTab === 'completed') { matchesTab = isCompleted; } else if (currentTab === 'active') { matchesTab = !isCompleted && (status === 'active' || status === 'next-week' || status === 'due-soon'); } else if (currentTab === 'next-week') { matchesTab = !isCompleted && status === 'next-week'; } else if (currentTab === 'due-soon') { matchesTab = !isCompleted && status === 'due-soon'; } else if (currentTab === 'overdue') { matchesTab = !isCompleted && status === 'overdue'; } } let matchesSubject = true; if (currentSubject) { matchesSubject = (subject === currentSubject); } let matchesSearch = true; if (currentSearch) { matchesSearch = normalizeTurkish(searchText).includes(currentSearch); } if (matchesTab && matchesSubject && matchesSearch) { card.style.display = 'flex'; visibleCount++; } else { card.style.display = 'none'; } }); if (filteredCountText) { filteredCountText.textContent = t('dashboard.showingCount', { count: visibleCount }); } if (noResults) { noResults.classList.toggle('hidden', visibleCount > 0); } } // Sync actions if (btnSyncRecent) { btnSyncRecent.addEventListener('click', async () => { if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { showAlert(t('dashboard.offlineSyncAlert'), 'danger'); return; } btnSyncRecent.disabled = true; btnSyncRecent.textContent = t('dashboard.syncing'); showAlert(t('dashboard.fetchingRecent'), 'info'); try { const res = await fetch('/api/sync', { method: 'POST' }); if (res.status === 401) { window.location.href = '/'; return; } const data = await res.json(); if (data.success) { window.location.reload(); } else { showAlert(`${t('dashboard.syncFailed')} ${data.error}`, 'danger'); btnSyncRecent.disabled = false; btnSyncRecent.textContent = t('dashboard.syncRecent'); } } catch (err) { showAlert(t('dashboard.networkError'), 'danger'); btnSyncRecent.disabled = false; btnSyncRecent.textContent = t('dashboard.syncRecent'); } }); } if (btnSyncAll) { btnSyncAll.addEventListener('click', async () => { if (window.BeKulturPWA && window.BeKulturPWA.isOffline()) { showAlert(t('dashboard.offlineSyncAlert'), 'danger'); return; } btnSyncAll.disabled = true; btnSyncAll.textContent = t('dashboard.syncingAll'); showAlert(t('dashboard.fetchingAll'), 'info'); try { const res = await fetch('/api/sync-all', { method: 'POST' }); if (res.status === 401) { window.location.href = '/'; return; } const data = await res.json(); if (data.success) { window.location.reload(); } else { showAlert(`${t('dashboard.syncFailed')} ${data.error}`, 'danger'); btnSyncAll.disabled = false; btnSyncAll.textContent = t('dashboard.syncAll'); } } catch (err) { showAlert(t('dashboard.networkError'), 'danger'); btnSyncAll.disabled = false; btnSyncAll.textContent = t('dashboard.syncAll'); } }); } function showAlert(msg, type = 'info') { if (!syncAlert) return; syncAlert.className = `alert alert-${type}`; syncAlert.textContent = msg; syncAlert.classList.remove('hidden'); } // Subject collapse if (subjectToggleHeader && subjectBreakdownBody && subjectToggleIcon) { subjectToggleHeader.addEventListener('click', () => { const isHidden = subjectBreakdownBody.classList.toggle('collapsed'); subjectToggleIcon.textContent = isHidden ? '▶' : '▼'; }); } });