document.addEventListener('DOMContentLoaded', async function() { async function fetchLastBeat() { const heartbeatElement = document.getElementById('heartbeat-time'); try { const response = await fetch('https://quinten0508.com/api/heartbeat'); const data = await response.json(); // Find device with the latest heartbeat let latestDevice = null; let latestTimestamp = 0; data.forEach(device => { const timestamp = device.last_beat.timestamp; if (timestamp > latestTimestamp) { latestTimestamp = timestamp; latestDevice = device; } }); if (latestDevice) { const timestampMilliseconds = latestTimestamp * 1000; const currentTime = Date.now(); const difference = currentTime - timestampMilliseconds; const isDead = difference > (1000 * 60 * 60 * 48); const online = difference < (1000 * 60 * 5); if (online) { heartbeatElement.textContent = 'Online!'; heartbeatElement.style = 'color: #00b400'; } else if (isDead) { heartbeatElement.textContent = 'Dead'; heartbeatElement.style = 'color: #b30000'; } else { heartbeatElement.textContent = 'Alive'; heartbeatElement.style = 'color: #00b400'; } } else { console.error('No devices found.'); } } catch (error) { console.error('Error fetching last beat:', error); } } // Fetch the last beat immediately and then every 10 seconds fetchLastBeat(); setInterval(fetchLastBeat, 10000); });