"use client";
// Singleton EventSource shared across all <AgentRunButton> rows and the
// page-level live-refresh component on /agents. One TCP/SSE connection per
// browser tab, regardless of how many agents are on screen — important
// because the server caps subscribers per process.

const EVENT_TYPES = ['agent_created', 'agent_run_start', 'agent_run_complete'];

let source = null;
const subscribers = new Set();

function ensureSource() {
  if (source) return source;
  if (typeof window === 'undefined' || !window.EventSource) return null;
  source = new EventSource('/api/events/stream');
  for (const type of EVENT_TYPES) {
    source.addEventListener(type, (e) => {
      let payload = {};
      try { payload = JSON.parse(e.data); } catch { /* keep empty */ }
      const event = { ...payload, type };
      for (const handler of subscribers) {
        try { handler(event); } catch { /* one bad handler shouldn't kill the bus */ }
      }
    });
  }
  return source;
}

export function subscribeAgentEvents(handler) {
  ensureSource();
  subscribers.add(handler);
  return () => {
    subscribers.delete(handler);
    if (subscribers.size === 0 && source) {
      try { source.close(); } catch { /* already closed */ }
      source = null;
    }
  };
}
