type EventHandler<T = any> = (payload: T) => void

export const EVENTS = {
  ORDERCOMPLETE: 'orderComplete',
} as const

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

  /**
   * 订阅事件
   * @returns 取消订阅的函数
   */
  on<T = any>(event: string, handler: EventHandler<T>): () => void {
    if (!this.events.has(event)) {
      this.events.set(event, new Set())
    }
    const handlers = this.events.get(event)!
    handlers.add(handler as EventHandler)

    // 返回取消订阅函数
    return () => {
      handlers.delete(handler as EventHandler)
      if (handlers.size === 0) {
        this.events.delete(event)
      }
    }
  }

  /**
   * 订阅一次（触发后自动移除）
   */
  once<T = any>(event: string, handler: EventHandler<T>): () => void {
    const unsubscribe = this.on<T>(event, (payload: T) => {
      handler(payload)
      unsubscribe()
    })
    return unsubscribe
  }

  /**
   * 发布事件
   */
  emit<T = any>(event: string, payload?: T): void {
    const handlers = this.events.get(event)
    if (handlers) {
      handlers.forEach((handler) => {
        handler(payload)
      })
    }
  }

  /**
   * 移除所有指定事件的监听器
   */
  off(event: string): void {
    this.events.delete(event)
  }

  /**
   * 清空所有事件（谨慎使用）
   */
  clear(): void {
    this.events.clear()
  }
}

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