type EventCallback = (...args: any[]) => void

class EventBus {
  private events: Map<string, EventCallback> = new Map()

  /**
   * 订阅事件（后续订阅会覆盖之前的）
   */
  on(event: string, callback: EventCallback) {
    this.events.set(event, callback)
  }

  /**
   * 取消订阅
   */
  off(event: string) {
    this.events.delete(event)
  }

  /**
   * 发送事件
   */
  emit(event: string, ...args: any[]) {
    const callback = this.events.get(event)
    if (callback) {
      callback(...args)
    }
  }

  /**
   * 只订阅一次
   */
  once(event: string, callback: EventCallback) {
    const onceCallback = (...args: any[]) => {
      callback(...args)
      this.off(event)
    }
    this.on(event, onceCallback)
  }
}

// 导出单例
export const eventBus = new EventBus()

// 事件名称常量
export const EventNames = {
  SWITCH_TAB: 'switch_tab',
  SHOW_TOAST: 'show_toast',
  SHOW_MESSAGE: 'show_message',
  AUTH: 'auth'
} as const
