(function () {
    const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
    const wsUrl = `${wsProtocol}://${window.location.host}/ws`;
    const pulseLog = document.getElementById('pulse-log');

    function logPulse(message) {
        if (!pulseLog) return;
        const line = document.createElement('div');
        line.className = 'log-line';
        line.textContent = message;
        pulseLog.prepend(line);
        while (pulseLog.children.length > 6) {
            pulseLog.removeChild(pulseLog.lastChild);
        }
    }

    function updatePulse(servers) {
        const avgTps = servers.reduce((acc, s) => acc + s.tps, 0) / servers.length;
        const avgMspt = servers.reduce((acc, s) => acc + s.mspt, 0) / servers.length;
        const totalOnline = servers.reduce((acc, s) => acc + s.online, 0);

        const tpsEl = document.getElementById('pulse-tps');
        const msptEl = document.getElementById('pulse-mspt');
        const onlineEl = document.getElementById('pulse-online');

        if (tpsEl) tpsEl.textContent = avgTps.toFixed(2);
        if (msptEl) msptEl.textContent = avgMspt.toFixed(1);
        if (onlineEl) onlineEl.textContent = totalOnline;
    }

    function updateServerCards(servers) {
        servers.forEach(server => {
            const card = document.querySelector(`[data-server-id="${server.id}"]`);
            if (!card) return;

            const onlineEl = card.querySelector('.metric-online');
            const maxEl = card.querySelector('.metric-max');
            const tpsEl = card.querySelector('.metric-tps');
            const msptEl = card.querySelector('.metric-mspt');
            const progress = card.querySelector('.progress-fill');
            const statusPill = card.querySelector('.status-pill');
            const statusText = card.querySelector('.status-text');

            if (onlineEl) onlineEl.textContent = server.online;
            if (maxEl) maxEl.textContent = server.max_players;
            if (tpsEl) tpsEl.textContent = server.tps.toFixed(1);
            if (msptEl) msptEl.textContent = server.mspt.toFixed(1);
            if (progress) {
                const percent = Math.round((server.online / server.max_players) * 100);
                progress.style.width = `${percent}%`;
            }
            if (statusPill && statusText) {
                if (server.status === 'stopped') {
                    statusPill.classList.remove('status-online', 'status-connecting', 'status-restarting');
                    statusPill.classList.add('status-stopped');
                    statusText.textContent = 'Остановлен';
                } else if (server.status === 'restarting') {
                    statusPill.classList.remove('status-online', 'status-connecting', 'status-stopped');
                    statusPill.classList.add('status-restarting');
                    statusText.textContent = 'Перезапуск';
                } else {
                    statusPill.classList.remove('status-stopped', 'status-connecting', 'status-restarting');
                    statusPill.classList.add('status-online');
                    statusText.textContent = 'Онлайн';
                }
            }
        });
    }

    function setCardStatus(text, className) {
        document.querySelectorAll('.server-card').forEach((card) => {
            const pill = card.querySelector('.status-pill');
            const label = card.querySelector('.status-text');
            if (!pill || !label) return;
            pill.classList.remove('status-online', 'status-stopped', 'status-restarting', 'status-connecting');
            pill.classList.add(className);
            label.textContent = text;
        });
    }

    const socket = new WebSocket(wsUrl);
    socket.addEventListener('open', () => {
        logPulse('Подключение к телеметрии...');
        setCardStatus('Подключение...', 'status-connecting');
    });

    socket.addEventListener('message', (event) => {
        try {
            const data = JSON.parse(event.data);
            if (data.servers) {
                updateServerCards(data.servers);
                updatePulse(data.servers);
                const sample = data.servers[Math.floor(Math.random() * data.servers.length)];
                logPulse(`${sample.name}: ${sample.online} игроков, TPS ${sample.tps.toFixed(2)}`);
            }
        } catch (err) {
            logPulse('Ошибка телеметрии.');
        }
    });

    socket.addEventListener('close', () => {
        logPulse('Телеметрия отключена.');
        setCardStatus('Нет связи', 'status-stopped');
    });
})();
