window.CockpitLive = (function () {
  var ws = null;
  var reconnectTimer = null;

  function startPolling(fn, intervalMs) {
    intervalMs = intervalMs || 30000;
    fn();
    var id = setInterval(fn, intervalMs);
    return function () { clearInterval(id); };
  }

  function connectFeed(onMessage) {
    if (typeof WebSocket === 'undefined') return function () {};
    var proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
    function connect() {
      try {
        ws = new WebSocket(proto + '//' + location.host + '/ws/feed');
        ws.onmessage = function (ev) {
          try {
            var data = JSON.parse(ev.data);
            if (onMessage) onMessage(data);
          } catch (e) {}
        };
        ws.onclose = function () {
          reconnectTimer = setTimeout(connect, 5000);
        };
      } catch (e) {
        reconnectTimer = setTimeout(connect, 5000);
      }
    }
    connect();
    return function () {
      if (reconnectTimer) clearTimeout(reconnectTimer);
      if (ws) { try { ws.close(); } catch (e) {} ws = null; }
    };
  }

  function updateLiveBadge(el, at) {
    if (!el) return;
    el.textContent = 'Live · ' + (at || new Date().toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' }));
  }

  function renderAgentFeed(container, events) {
    if (!container || !events) return;
    container.innerHTML = events.slice(0, 12).map(function (ev) {
      var t = (ev.created_at || '').substring(11, 16);
      return '<div class="hub-feed-item"><span>' + t + '</span>' +
        '<span class="badge badge-agent-' + String(ev.agent_name || '').toLowerCase() + '">' + (ev.agent_name || '') + '</span> ' +
        (ev.title || ev.event_type || '') + '</div>';
    }).join('') || '<p class="empty-state">Nog geen events.</p>';
  }

  return { startPolling: startPolling, connectFeed: connectFeed, updateLiveBadge: updateLiveBadge, renderAgentFeed: renderAgentFeed };
})();
