/**
 * SSE Event Bus — Simplified (no page singleton, no VLClaw)
 * Multiple browser tabs can connect freely.
 */

export function setupSSE(app, server) {
  app.get('/api/events', (req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'X-Accel-Buffering': 'no',
    });
    res.write('\n');

    // Assign window number
    server._windowCounter = (server._windowCounter || 0) + 1;
    const windowId = server._windowCounter;
    res.write(`data: ${JSON.stringify({ type: 'window_id', windowId })}\n\n`);

    server.sseClients.add(res);

    // Send current run state so newly opened windows can sync
    if (server._currentRunState) {
      res.write(`data: ${JSON.stringify({ type: 'current_run_state', ...server._currentRunState })}\n\n`);
    }
    if (server._uiState) {
      res.write(`data: ${JSON.stringify({ type: 'ui_state', ...server._uiState })}\n\n`);
    }
    // Send current workspace tabs so new windows show the correct tab bar
    if (server._openTabs) {
      res.write(`data: ${JSON.stringify({ type: 'ws_tabs_changed', tabs: server._openTabs, activeDir: server.config?.workDir })}\n\n`);
    }

    req.on('close', () => {
      server.sseClients.delete(res);
    });
  });
}
