// HUD hardware-status badges (KL-67) — DMX + Govee. Each badge hides
// when its subsystem isn't configured (Starter Govee-only users never
// see a perpetually-red DMX badge). Past 28 dots, the strip switches
// to a "battery-style" proportion bar so 50+ device rigs stay readable.
//
// Extracted from show.js per KL-109. main.js calls updateSystems() on
// the 10Hz state push.

const SYS_STALE_MS = 8000;
const SYS_DEAD_MS = 20000;
const SYS_STRIPE_THRESHOLD = 28;

const _systemsLastSig = {dmx: null, govee: null};

function _classifyDot(item) {
    const age = item.last_ack_age_ms;
    if (age == null) return 'never';
    if (age < SYS_STALE_MS) return 'ok';
    if (age < SYS_DEAD_MS) return 'stale';
    return 'dead';
}

function _renderBadge(rootSelector, label, status, itemKey) {
    const root = document.querySelector(rootSelector);
    if (!root) return false;
    const items = (status && status[itemKey]) || [];
    const configured = !!(status && status.configured);

    if (!configured || items.length === 0) {
        root.hidden = true;
        return false;
    }
    root.hidden = false;

    const states = items.map(_classifyDot);
    const okCount = states.filter(s => s === 'ok').length;
    const total = items.length;

    const sig = `${total}|${states.join('')}`;
    const lastSigKey = label === 'DMX' ? 'dmx' : 'govee';
    if (_systemsLastSig[lastSigKey] === sig) return true;
    _systemsLastSig[lastSigKey] = sig;

    let html = `<span class="sys-label">${label}</span>`;
    html += `<span class="sys-count">${okCount}/${total}</span>`;
    if (total > SYS_STRIPE_THRESHOLD) {
        const stale = states.filter(s => s === 'stale').length;
        const dead = states.filter(s => s === 'dead' || s === 'never').length;
        html += '<div class="sys-dots as-stripe">';
        html += `<div class="stripe-segment" data-state="ok" style="width: ${(okCount / total) * 100}%"></div>`;
        html += `<div class="stripe-segment" data-state="stale" style="width: ${(stale / total) * 100}%"></div>`;
        html += `<div class="stripe-segment" data-state="dead" style="width: ${(dead / total) * 100}%"></div>`;
        html += '</div>';
    } else {
        html += '<div class="sys-dots">';
        for (let i = 0; i < items.length; i++) {
            const it = items[i];
            const state = states[i];
            const ageS = it.last_ack_age_ms != null
                ? `${(it.last_ack_age_ms / 1000).toFixed(1)}s`
                : 'never';
            const tip = `${(it.name || it.ip || 'device').replace(/"/g, '')} · ${it.ip || '—'} · ${ageS}`;
            html += `<span class="sys-dot" data-state="${state}" title="${tip}"></span>`;
        }
        html += '</div>';
    }
    root.innerHTML = html;
    return true;
}

export function updateSystems(dmxStatus, goveeStatus) {
    const container = document.getElementById('hud-systems');
    if (!container) return;

    if (!container.querySelector('.sys-dmx')) {
        container.innerHTML =
            '<div class="sys-badge sys-dmx" hidden></div>'
            + '<div class="sys-badge sys-govee" hidden></div>';
    }

    const anyDmx = _renderBadge('#hud-systems .sys-dmx', 'DMX', dmxStatus, 'nodes');
    const anyGve = _renderBadge('#hud-systems .sys-govee', 'GVE', goveeStatus, 'devices');
    container.classList.toggle('visible', anyDmx || anyGve);
}
