File size: 8,578 Bytes
aef6574
 
 
 
 
 
 
 
 
 
 
f488d21
aef6574
 
 
 
 
 
 
 
 
f488d21
aef6574
 
 
f488d21
aef6574
 
 
 
 
f488d21
aef6574
 
 
 
 
 
 
f488d21
 
aef6574
 
f488d21
 
aef6574
 
f488d21
 
aef6574
 
f488d21
e13e924
aef6574
 
 
 
f488d21
 
 
 
 
 
 
 
aef6574
 
 
 
 
f488d21
 
aef6574
 
 
 
 
e13e924
f488d21
 
aef6574
 
f488d21
aef6574
 
 
f488d21
aef6574
 
 
 
 
f488d21
aef6574
 
 
 
 
 
 
 
 
 
 
f488d21
aef6574
 
f488d21
aef6574
 
 
f488d21
aef6574
 
 
 
 
f488d21
aef6574
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f488d21
aef6574
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f488d21
 
aef6574
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f488d21
 
 
 
 
 
 
 
aef6574
f488d21
 
aef6574
 
 
 
 
 
f488d21
aef6574
 
f488d21
 
 
 
e7be31e
f488d21
aef6574
e7be31e
 
 
aef6574
 
f488d21
 
 
 
 
b1a6392
f488d21
 
 
 
aef6574
c95ee65
 
 
 
 
aef6574
 
f488d21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// 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 = `
                    <td class="p-2">${item.INICIO || '--:--'}</td>
                    <td class="p-2">${item.DURACAO || '--:--'}</td>
                    <td class="p-2">${item.MOMENTO || 'Untitled'}</td>
                `;
                
                tbody.appendChild(row);
            });
            
            marcarLinhaAtivaNaTabela();
        } else {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="3" class="p-2 text-center text-gray-400">Nenhum cronograma disponível</td>';
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));
};