// src/services/eventBus.ts

/**
 * A simple, generic event bus for cross-component communication without direct coupling.
 * This is particularly useful for broadcasting application-wide events, such as session expiry.
 */

type EventCallback = (data?: any) => void;

export class EventBus {
  private listeners: { [key: string]: EventCallback[] } = {};

  on(event: string, callback: EventCallback): void {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
  }

  off(event: string, callback: EventCallback): void {
    if (!this.listeners[event]) return;
    this.listeners[event] = this.listeners[event].filter((l) => l !== callback);
  }

  dispatch(event: string, data?: any): void {
    if (!this.listeners[event]) return;
    this.listeners[event].forEach((callback) => callback(data));
  }
}

export const eventBus = new EventBus();