// Generate or retrieve user ID function getOrCreateUserId() { let userId = localStorage.getItem('timeSyncUserId'); if (!userId) { userId = 'user_' + Math.random().toString(36).substr(2, 9); localStorage.setItem('timeSyncUserId', userId); } return userId; } // Connect to Socket.IO server const socket = io(); const userId = getOrCreateUserId(); // Update current time function updateCurrentTime() { const now = new Date(); const timeString = now.toLocaleTimeString(); const dateString = now.toLocaleDateString(); document.querySelectorAll('#current-time, #current-time-mobile').forEach(el => { el.textContent = timeString; }); document.querySelectorAll('#current-date, #current-date-mobile').forEach(el => { el.textContent = dateString; }); } // Heartbeat function function sendHeartbeat() { socket.emit('userHeartbeat', { userId }); } setInterval(sendHeartbeat, 10000); // Update timer UI function updateTemporizadorUI(data) { // Update all relevant elements document.querySelectorAll('#PROGRAMA-TITULO, #PROGRAMA-TITULO-mobile').forEach(el => { el.textContent = data.PROGRAMA || 'Título do Evento'; }); document.querySelectorAll('#TEMA, #TEMA-mobile').forEach(el => { el.textContent = data.TEMA || 'Tema Atual'; }); document.querySelectorAll('#MOMENTO, #MOMENTO-mobile').forEach(el => { el.textContent = data.MOMENTO || 'TEMPO RESTANTE'; }); document.querySelectorAll('#FALTA, #FALTA-mobile').forEach(el => { el.textContent = data.FALTA || '00:00:00'; }); // Handle status colors const momentoFaltaElements = document.querySelectorAll('#MOMENTO-FALTA, #MOMENTO-FALTA-mobile'); momentoFaltaElements.forEach(el => { el.classList.remove('alerta-vermelho', 'alerta-amarelo', 'alerta-verde'); if (data.MOMENTO === 'ATRASADO EM' || (parseInt(data.FALTA.split(':').join('')) < 0)) { el.classList.add('alerta-vermelho'); } else if (data.MOMENTO === 'RESTA' && (parseInt(data.FALTA.split(':')[2]) < 900)) { el.classList.add('alerta-amarelo'); } else { el.classList.add('alerta-verde'); } }); // Handle activation state if (data.ATIVACAO === 'INATIVO' || data.ATIVACAO === 'PAUSADO') { showTemporizadorInativoState(data.ATIVACAO === 'PAUSADO' ? 'Temporizador Pausado' : 'Temporizador Inativo'); } else { showTemporizadorAtivoState(); } } // Show inactive state function showTemporizadorInativoState(message = 'Timer Inactive') { document.getElementById('msg-inativo-card-wrapper').style.display = 'flex'; document.getElementById('inactive-message').textContent = message; // Hide elements in desktop view const desktopElements = [ '#card-status-tema-container', '#cronograma-header', '#cronograma-table' ].forEach(selector => { const el = document.querySelector(selector); if (el) el.style.display = 'none'; }); // Hide elements in mobile view const mobileElements = [ '#card-status-tema-container-mobile', '#cronograma-header-mobile', '#cronograma-table-mobile' ].forEach(selector => { const el = document.querySelector(selector); if (el) el.style.display = 'none'; }); } // Show active state function showTemporizadorAtivoState() { document.getElementById('msg-inativo-card-wrapper').style.display = 'none'; // Show elements in desktop view const desktopElements = [ '#card-status-tema-container', '#cronograma-header', '#cronograma-table' ].forEach(selector => { const el = document.querySelector(selector); if (el) el.style.display = 'block'; }); // Show elements in mobile view const mobileElements = [ '#card-status-tema-container-mobile', '#cronograma-header-mobile', '#cronograma-table-mobile' ].forEach(selector => { const el = document.querySelector(selector); if (el) el.style.display = 'block'; }); } // Handle warning message function handleAviso(message) { if (!message) return; const containers = [ '#card-aviso-container', '#card-aviso-container-mobile' ]; containers.forEach(selector => { const container = document.querySelector(selector); if (container) { const avisoEl = container.querySelector('span'); avisoEl.textContent = message; container.classList.remove('hidden'); container.classList.add('show'); setTimeout(() => { container.classList.remove('show'); container.classList.add('hidden'); }, 10000); } }); } // Update schedule table function updateTabelaCronogramaUI(data) { const tableBodies = [ '#tabela-cronograma-body', '#tabela-cronograma-body-mobile' ]; tableBodies.forEach(selector => { const tbody = document.querySelector(selector); if (!tbody) return; tbody.innerHTML = ''; if (data && data.ITENS && data.ITENS.length > 0) { data.ITENS.forEach(item => { const row = document.createElement('tr'); row.dataset.momento = item.MOMENTO; row.innerHTML = ` ${item.INICIO || '--:--'} ${item.DURACAO || '--:--'} ${item.MOMENTO || 'Untitled'} `; tbody.appendChild(row); }); marcarLinhaAtivaNaTabela(); } else { const row = document.createElement('tr'); row.innerHTML = 'Nenhum cronograma disponível'; tbody.appendChild(row); } }); } // Mark active row in schedule table function marcarLinhaAtivaNaTabela() { const currentTema = document.getElementById('TEMA')?.textContent; if (!currentTema) return; const rows = document.querySelectorAll('#tabela-cronograma-body tr, #tabela-cronograma-body-mobile tr'); rows.forEach(row => { row.classList.remove('item-ativo'); if (row.dataset.momento === currentTema) { row.classList.add('item-ativo'); } }); } // Fullscreen toggle document.getElementById('fullscreen-button').addEventListener('click', () => { if (!document.fullscreenElement) { document.documentElement.requestFullscreen().catch(err => { console.error('Error attempting to enable fullscreen:', err); }); } else { if (document.exitFullscreen) { document.exitFullscreen(); } } }); // PWA installation prompt let deferredPrompt; window.addEventListener('beforeinstallprompt', (e) => { e.preventDefault(); deferredPrompt = e; document.getElementById('install-app-btn').classList.remove('hidden'); }); document.getElementById('install-app-btn').addEventListener('click', async () => { if (deferredPrompt) { deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; if (outcome === 'accepted') { document.getElementById('install-app-btn').classList.add('hidden'); } deferredPrompt = null; } }); // Socket.IO event listeners socket.on('dadosAtualizados', updateTemporizadorUI); socket.on('cronogramaAtualizado', updateTabelaCronogramaUI); socket.on('onlineUsersCountUpdated', (count) => { document.querySelectorAll('#online-users-count, #online-users-count-mobile').forEach(el => { el.textContent = count; }); }); socket.on('encerrarTemporizador', () => { showTemporizadorInativoState('Temporizador Finalizado'); }); // Initialize updateCurrentTime(); setInterval(updateCurrentTime, 1000); sendHeartbeat(); // Error logging window.onerror = function(message, source, lineno, colno, error) { fetch('/api/log-error', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message, source, lineno, colno, error: error ? error.stack : null, userId }) }).catch(err => console.error('Error logging failed:', err)); };