(function () {
    'use strict';

    function getJSON(url) {
        return fetch(url, {
            credentials: 'same-origin',
            headers: { 'Accept': 'application/json' },
            cache: 'no-store'
        }).then(function (response) {
            if (!response.ok) throw new Error('HTTP ' + response.status);
            return response.json();
        });
    }

    function eventSchedule(eventId, openTime, duration, offset, timeLeft) {
        var element = document.getElementById(eventId);
        if (!element) return;
        var reloading = false;
        var targetAt = Date.now() + (Math.max(0, Number(timeLeft) || 0) * 1000);

        function setMeta(data) {
            var name = document.getElementById(eventId + '_name');
            var next = document.getElementById(eventId + '_next');
            if (name && data.event != null) name.textContent = data.event;
            if (next && data.nextF != null) next.textContent = data.nextF;
        }

        function reloadEventInfo() {
            if (reloading) return;
            reloading = true;
            getJSON(baseUrl + 'api/events.php?event=' + encodeURIComponent(eventId)).then(function (data) {
                openTime = Number(data.opentime) || 0;
                duration = Number(data.duration) || 0;
                offset = Number(data.offset) || 0;
                timeLeft = Number(data.timeleft) || 0;
                targetAt = Date.now() + (Math.max(0, timeLeft) * 1000);
                setMeta(data);
            }).catch(function () {}).finally(function () {
                reloading = false;
            });
        }

        function update() {
            if (document.hidden) return;
            timeLeft = Math.max(0, Math.ceil((targetAt - Date.now()) / 1000));
            var days = 0, hours = 0, minutes = 0, seconds = 0;
            if (timeLeft >= 1) {
                var daysModule = timeLeft % 86400;
                days = (timeLeft - daysModule) / 86400;
                var hoursModule = daysModule % 3600;
                hours = (daysModule - hoursModule) / 3600;
                var minutesModule = hoursModule % 60;
                minutes = (hoursModule - minutesModule) / 60;
                seconds = minutesModule;
            } else {
                reloadEventInfo();
            }

            if (openTime > 0 && offset - timeLeft < openTime) {
                element.innerHTML = '<span class="event-schedule-open">Open</span>';
            } else if (openTime <= 0 && duration > 0 && offset - timeLeft < duration) {
                element.innerHTML = '<span class="event-schedule-inprogress">In Progress</span>';
            } else if (hours === 0 && minutes === 0) {
                element.textContent = seconds + ' sec';
            } else if (days > 0) {
                element.textContent = days + ' days ' + hours + ' hrs ' + String(minutes).padStart(2, '0') + ' min ' + String(seconds).padStart(2, '0') + ' sec';
            } else {
                element.textContent = hours + ' hrs ' + String(minutes).padStart(2, '0') + ' min ' + String(seconds).padStart(2, '0') + ' sec';
            }

        }

        update();
        window.setInterval(update, 1000);
    }

    function loadEventSchedule() {
        var knownIds = ['bloodcastle','devilsquare','chaoscastle','dragoninvasion','goldeninvasion','castlesiege'];
        if (!knownIds.some(function (id) { return !!document.getElementById(id); })) return;
        getJSON(baseUrl + 'api/events.php').then(function (data) {
            Object.keys(data || {}).forEach(function (key) {
                if (!document.getElementById(key)) return;
                var value = data[key] || {};
                eventSchedule(key, Number(value.opentime) || 0, Number(value.duration) || 0, Number(value.offset) || 0, Number(value.timeleft) || 0);
                var name = document.getElementById(key + '_name');
                var next = document.getElementById(key + '_next');
                if (name && value.event != null) name.textContent = value.event;
                if (next && value.nextF != null) next.textContent = value.nextF;
            });
        }).catch(function () {});
    }

    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', loadEventSchedule, { once: true });
    else loadEventSchedule();
}());
