type Listener = () => void;

const listeners = new Map<string, Set<Listener>>();

export function subscribe(roomId: string, listener: Listener): () => void {
  if (!listeners.has(roomId)) {
    listeners.set(roomId, new Set());
  }
  const set = listeners.get(roomId)!;
  set.add(listener);

  return () => {
    set.delete(listener);
    if (set.size === 0) listeners.delete(roomId);
  };
}

export function notify(roomId: string) {
  const set = listeners.get(roomId);
  if (set) {
    for (const fn of set) fn();
  }
}
