/* ===================================================
   JAESWIFT.XYZ — Server Clock + Uptime
   eDEX-UI inspired digital clock with live uptime
   =================================================== */

(function () {
    'use strict';

    var clockEl = document.getElementById('serverClock');
    var dateEl = document.getElementById('serverDate');
    var uptimeEl = document.getElementById('serverUptime');
    if (!clockEl) return;

    // Update clock every second
    function updateClock() {
        var now = new Date();
        var h = String(now.getHours()).padStart(2, '0');
        var m = String(now.getMinutes()).padStart(2, '0');
        var s = String(now.getSeconds()).padStart(2, '0');
        clockEl.textContent = h + ':' + m + ':' + s;

        var year = now.getFullYear();
        var month = String(now.getMonth() + 1).padStart(2, '0');
        var day = String(now.getDate()).padStart(2, '0');
        var days = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
        dateEl.textContent = year + '/' + month + '/' + day + ' // ' + days[now.getDay()];
    }

    // Format uptime from seconds
    function formatUptime(secs) {
        var d = Math.floor(secs / 86400);
        var h = Math.floor((secs % 86400) / 3600);
        var m = Math.floor((secs % 3600) / 60);
        var parts = [];
        if (d > 0) parts.push(d + 'd');
        parts.push(h + 'h');
        parts.push(m + 'm');
        return parts.join(' ');
    }

    // Fetch uptime from stats API
    function fetchUptime() {
        fetch('/api/stats')
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data && data.uptime_seconds) {
                    uptimeEl.textContent = formatUptime(data.uptime_seconds);
                } else if (data && data.uptime) {
                    uptimeEl.textContent = data.uptime;
                }
            })
            .catch(function () {});
    }

    // Init
    updateClock();
    setInterval(updateClock, 1000);

    // Fetch uptime every 30s
    fetchUptime();
    setInterval(fetchUptime, 30000);

})();
