type Callback = (payload: any) => void

class EventBus {
  private listeners: Map<string, Callback[]> = new Map()

  on(event: string, callback: Callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, [])
    }
    this.listeners.get(event)!.push(callback)
  }

  off(event: string, callback: Callback) {
    const list = this.listeners.get(event)
    if (!list) return

    const index = list.indexOf(callback)
    if (index !== -1) list.splice(index, 1)
  }

  emit(event: string, payload?: any) {
    const list = this.listeners.get(event)
    if (!list) return

    list.forEach((callback) => callback(payload))
  }
}

export const eventBus = new EventBus()
