(function() { 'use strict'; const token = localStorage.getItem('auth_token'); if (!token) { window.location.href = '/'; return; } function decodeJwt(token) { try { return JSON.parse(atob(token.split('.')[1])); } catch { return null; } } const decoded = decodeJwt(token); if (!decoded) { localStorage.removeItem('auth_token'); window.location.href = '/'; return; } // Check if admin and show admin tabs if (decoded.admin) { const adminTabAllPicks = document.getElementById('tab-all-picks'); if (adminTabAllPicks) adminTabAllPicks.classList.remove('d-none'); const adminTabWinners = document.getElementById('tab-winners'); if (adminTabWinners) adminTabWinners.classList.remove('d-none'); } // Logout const logOffBtn = document.getElementById('log-off'); if (logOffBtn) { logOffBtn.addEventListener('click', () => { localStorage.removeItem('auth_token'); window.location.href = '/'; }); } let categories = []; let myPicks = {}; let currentYear = null; async function fetchActiveYear() { try { const res = await fetch('/api/settings/year'); if (!res.ok) throw new Error('Failed to fetch active year'); const data = await res.json(); return Number(data.year) || new Date().getFullYear(); } catch (err) { console.error('Error fetching active year:', err); return new Date().getFullYear(); } } function showAlert(message, type = 'info') { const container = document.getElementById('alert-container'); if (!container) return; container.innerHTML = ` `; setTimeout(() => { const alert = container.querySelector('.alert'); if (alert) { const bsAlert = new bootstrap.Alert(alert); bsAlert.close(); } }, 5000); } async function fetchCategories() { try { // Use active year if not set if (!currentYear) { currentYear = await fetchActiveYear(); document.title = `Pool Oscars (${currentYear}) - Mes choix`; } const res = await fetch(`/api/picks/categories?year=${currentYear}`, { headers: { 'Authorization': `Bearer ${token}` } }); if (!res.ok) { if (res.status === 401) { localStorage.removeItem('auth_token'); window.location.href = '/'; return; } throw new Error('Failed to fetch categories'); } const data = await res.json(); categories = data.categories || []; currentYear = data.year || currentYear; document.getElementById('current-year').textContent = currentYear; if (document.getElementById('all-picks-year')) { document.getElementById('all-picks-year').textContent = currentYear; } if (categories.length === 0) { document.getElementById('categories-container').innerHTML = `
Aucune catégorie trouvée pour l'année ${currentYear}. Un administrateur doit d'abord importer les catégories.
`; return; } renderCategories(); await loadMyPicks(); } catch (err) { console.error('Error fetching categories:', err); showAlert('Erreur lors du chargement des catégories: ' + err.message, 'danger'); } } async function loadMyPicks() { try { const res = await fetch(`/api/picks/my-picks?year=${currentYear}`, { headers: { 'Authorization': `Bearer ${token}` } }); if (!res.ok && res.status !== 404) { throw new Error('Failed to load picks'); } const data = await res.json(); if (data.pick && data.pick.picks) { myPicks = {}; data.pick.picks.forEach(p => { myPicks[p.categoryNumber] = p.selectedNominee; }); renderCategories(); updateProgress(); } } catch (err) { console.error('Error loading picks:', err); } } function renderCategories() { const container = document.getElementById('categories-container'); if (!container) return; if (categories.length === 0) { container.innerHTML = '
Aucune catégorie disponible
'; return; } container.innerHTML = categories.map(cat => `
${cat.categoryNumber}. ${cat.categoryName}
${cat.nominees.map(nominee => { const isSelected = myPicks[cat.categoryNumber] === nominee.name; return `
${nominee.name}
`; }).join('')}
`).join(''); // Add click handlers container.querySelectorAll('.nominee-option').forEach(el => { el.addEventListener('click', function() { const category = parseInt(this.dataset.category); const nominee = this.dataset.nominee; // Remove selection from other options in same category container.querySelectorAll(`[data-category="${category}"]`).forEach(opt => { opt.classList.remove('selected'); }); // Select this option this.classList.add('selected'); myPicks[category] = nominee; updateProgress(); }); }); updateProgress(); } function updateProgress() { const total = categories.length; const completed = Object.keys(myPicks).length; document.getElementById('picks-progress').textContent = `${completed} / ${total}`; } async function submitPicks() { const picks = Object.keys(myPicks).map(catNum => ({ categoryNumber: parseInt(catNum), selectedNominee: myPicks[catNum] })); if (picks.length === 0) { showAlert('Veuillez sélectionner au moins un choix', 'warning'); return; } if (picks.length < categories.length) { if (!confirm(`Vous n'avez sélectionné que ${picks.length} sur ${categories.length} catégories. Voulez-vous enregistrer quand même?`)) { return; } } try { const res = await fetch('/api/picks/submit', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ year: currentYear, picks }) }); if (!res.ok) { const error = await res.json(); throw new Error(error.message || 'Failed to submit picks'); } const data = await res.json(); showAlert('Vos choix ont été enregistrés avec succès!', 'success'); } catch (err) { console.error('Error submitting picks:', err); showAlert('Erreur lors de l\'enregistrement: ' + err.message, 'danger'); } } // All picks functionality (admin only) let allPicks = []; let allPicksCategories = []; async function fetchAllPicks() { try { // Use active year if not set if (!currentYear) { currentYear = await fetchActiveYear(); } const res = await fetch(`/api/picks/all?year=${currentYear}`, { headers: { 'Authorization': `Bearer ${token}` } }); if (!res.ok) { if (res.status === 401) { localStorage.removeItem('auth_token'); window.location.href = '/'; return; } if (res.status === 403) { showAlert('Vous n\'avez pas les privilèges administrateur', 'warning'); return; } throw new Error('Failed to fetch picks'); } const data = await res.json(); allPicks = data.picks || []; allPicksCategories = data.categories || []; currentYear = data.year || currentYear; const yearEl = document.getElementById('all-picks-year'); if (yearEl) yearEl.textContent = currentYear; const countEl = document.getElementById('users-count'); if (countEl) countEl.textContent = allPicks.length; renderAllPicks(); } catch (err) { console.error('Error fetching all picks:', err); showAlert('Erreur lors du chargement des choix: ' + err.message, 'danger'); } } function renderAllPicks() { const container = document.getElementById('all-picks-container'); if (!container) return; if (allPicks.length === 0) { container.innerHTML = `
Aucun utilisateur n'a encore soumis ses choix pour l'année ${currentYear}.
`; return; } // Create a map of category info const categoryMap = new Map(); allPicksCategories.forEach(cat => { categoryMap.set(cat.categoryNumber, cat); }); container.innerHTML = allPicks.map(pick => { const userName = pick.userId?.name || 'Utilisateur inconnu'; const userEmail = pick.userId?.email || ''; const submittedDate = pick.submittedAt ? new Date(pick.submittedAt).toLocaleString('fr-FR') : '—'; // Create a map of picks by category const picksMap = new Map(); pick.picks.forEach(p => { picksMap.set(p.categoryNumber, p.selectedNominee); }); // Build picks list const picksList = allPicksCategories.map(cat => { const selected = picksMap.get(cat.categoryNumber); if (!selected) return null; // Check if it's a winner (if winners are set) const nominee = cat.nominees.find(n => n.name === selected); const isWinner = nominee?.isWinner || false; return `
${cat.categoryNumber}. ${cat.categoryName}
${selected}
${isWinner ? 'Gagnant' : ''}
`; }).filter(Boolean).join(''); return `
${userName}
${userEmail}
Soumis le: ${submittedDate}
${pick.picks.length} / ${allPicksCategories.length} catégories
${picksList || '
Aucun choix enregistré
'}
`; }).join(''); } // Event listeners document.getElementById('submit-picks')?.addEventListener('click', submitPicks); document.getElementById('load-my-picks')?.addEventListener('click', () => { loadMyPicks(); showAlert('Choix rechargés', 'info'); }); document.getElementById('refresh-all-picks')?.addEventListener('click', () => { fetchAllPicks(); showAlert('Choix rafraîchis', 'info'); }); // Load all picks when admin tab is shown const allPicksTab = document.getElementById('tab-all-picks'); if (allPicksTab) { allPicksTab.addEventListener('shown.bs.tab', () => { fetchAllPicks(); }); } // Winners & Scores functionality (admin only) let winnersCategories = []; async function fetchWinnersCategories() { try { if (!currentYear) { currentYear = await fetchActiveYear(); } const res = await fetch(`/api/picks/categories?year=${currentYear}`, { headers: { 'Authorization': `Bearer ${token}` } }); if (!res.ok) { throw new Error('Failed to fetch categories'); } const data = await res.json(); winnersCategories = data.categories || []; currentYear = data.year || currentYear; const yearEl = document.getElementById('winners-year'); if (yearEl) yearEl.textContent = currentYear; renderWinnersCategories(); await fetchScores(); } catch (err) { console.error('Error fetching winners categories:', err); showAlert('Erreur lors du chargement des catégories: ' + err.message, 'danger'); } } function renderWinnersCategories() { const container = document.getElementById('winners-container'); if (!container) return; if (winnersCategories.length === 0) { container.innerHTML = '
Aucune catégorie trouvée pour cette année.
'; return; } const winnersCount = winnersCategories.filter(cat => cat.nominees.some(n => n.isWinner) ).length; const progressEl = document.getElementById('winners-progress'); if (progressEl) progressEl.textContent = `${winnersCount} / ${winnersCategories.length}`; container.innerHTML = winnersCategories.map(cat => { const winner = cat.nominees.find(n => n.isWinner); return `
${cat.categoryNumber}. ${cat.categoryName}
${winner ? `
Gagnant actuel: ${winner.name}
` : ''}
`; }).join(''); // Add event listeners for winner selection container.querySelectorAll('.winner-select').forEach(select => { select.addEventListener('change', async function() { const categoryId = this.dataset.categoryId; const winnerName = this.value; if (!winnerName) return; try { const res = await fetch(`/api/categories/${categoryId}/winner`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ winnerName }) }); if (!res.ok) { const error = await res.json(); throw new Error(error.message || 'Failed to mark winner'); } showAlert('Gagnant marqué avec succès', 'success'); await fetchWinnersCategories(); } catch (err) { console.error('Error marking winner:', err); showAlert('Erreur: ' + err.message, 'danger'); } }); }); } async function calculateScores() { try { if (!currentYear) { currentYear = await fetchActiveYear(); } const btn = document.getElementById('calculate-scores'); if (btn) { btn.disabled = true; btn.textContent = 'Calcul en cours...'; } const res = await fetch('/api/picks/calculate-scores', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ year: currentYear }) }); if (!res.ok) { const error = await res.json(); throw new Error(error.message || 'Failed to calculate scores'); } const data = await res.json(); showAlert(`Scores calculés avec succès! ${data.scores.length} utilisateur(s) évalué(s).`, 'success'); await fetchScores(); } catch (err) { console.error('Error calculating scores:', err); showAlert('Erreur: ' + err.message, 'danger'); } finally { const btn = document.getElementById('calculate-scores'); if (btn) { btn.disabled = false; btn.textContent = 'Calculer les scores'; } } } async function fetchScores() { try { if (!currentYear) { currentYear = await fetchActiveYear(); } const res = await fetch(`/api/picks/scores?year=${currentYear}`, { headers: { 'Authorization': `Bearer ${token}` } }); if (!res.ok) { if (res.status === 403) { return; // Not admin, skip } throw new Error('Failed to fetch scores'); } const data = await res.json(); renderScores(data.scores || [], data.totalCategories || 0); } catch (err) { console.error('Error fetching scores:', err); } } function renderScores(scores, totalCategories) { const container = document.getElementById('scores-container'); if (!container) return; if (scores.length === 0) { container.innerHTML = '
Aucun score disponible. Les utilisateurs doivent d\'abord soumettre leurs choix.
'; return; } container.innerHTML = `
${scores.map((score, index) => { const percentage = totalCategories > 0 ? Math.round((score.score / totalCategories) * 100) : 0; const rank = index + 1; const medal = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : ''; return ` `; }).join('')}
# Utilisateur Score Total % Actions
${rank}${medal ? ' ' + medal : ''} ${score.userName}${score.userEmail ? ` (${score.userEmail})` : ''} ${score.score} ${totalCategories} ${percentage}%
`; // Store scores data globally for modal access window.scoresData = scores; // Add event listeners for view picks buttons container.querySelectorAll('.view-picks-btn').forEach(btn => { btn.addEventListener('click', function() { const scoreIndex = parseInt(this.dataset.scoreIndex); const score = scores[scoreIndex]; showUserPicksModal(score); }); }); } function showUserPicksModal(score) { const modal = new bootstrap.Modal(document.getElementById('userPicksModal')); const modalTitle = document.getElementById('userPicksModalLabel'); const modalContent = document.getElementById('user-picks-modal-content'); modalTitle.textContent = `Choix de ${score.userName}`; if (!score.pickDetails || score.pickDetails.length === 0) { modalContent.innerHTML = '
Aucun détail disponible.
'; modal.show(); return; } // Separate correct and incorrect picks const correctPicks = score.pickDetails.filter(p => p.isCorrect); const incorrectPicks = score.pickDetails.filter(p => !p.isCorrect); modalContent.innerHTML = `
Résumé
${correctPicks.length} correct(s) | ${incorrectPicks.length} incorrect(s) | ${score.pickDetails.length} total
${score.score} / ${score.totalCategories}
${Math.round((score.score / score.totalCategories) * 100)}%
${correctPicks.length > 0 ? `
✓ Corrects (${correctPicks.length})
${correctPicks.map(pick => `
${pick.categoryNumber}. ${pick.categoryName}
✓ ${pick.selectedNominee}
`).join('')}
` : ''} ${incorrectPicks.length > 0 ? `
✗ Incorrects (${incorrectPicks.length})
${incorrectPicks.map(pick => `
${pick.categoryNumber}. ${pick.categoryName}
✗ Choix: ${pick.selectedNominee}
${pick.correctWinner ? `
✓ Gagnant: ${pick.correctWinner}
` : '
Aucun gagnant marqué
'}
`).join('')}
` : ''} ${correctPicks.length === 0 && incorrectPicks.length === 0 ? `
Aucun choix à afficher.
` : ''} `; modal.show(); } // Event listeners for winners tab document.getElementById('calculate-scores')?.addEventListener('click', calculateScores); document.getElementById('refresh-winners')?.addEventListener('click', () => { fetchWinnersCategories(); showAlert('Données rafraîchies', 'info'); }); // Load winners when admin tab is shown const winnersTab = document.getElementById('tab-winners'); if (winnersTab) { winnersTab.addEventListener('shown.bs.tab', () => { fetchWinnersCategories(); }); } // Initial load (async () => { currentYear = await fetchActiveYear(); document.title = `Pool Oscars (${currentYear}) - Mes choix`; await fetchCategories(); })(); })();