import { useEffect } from 'react'
import { eventBus, type WSMessage } from '@/lib/event-bus'

/**
 * 订阅系统事件总线（SharedWorker/WebSocket）
 */
export function useEventBus(
  eventType: string | string[] | null,
  handler: (payload: any, type: string) => void,
) {
  useEffect(() => {
    eventBus.init()
    const onMessage = (msg: WSMessage) => {
      if (!eventType) {
        handler(msg.payload, msg.type)
        return
      }
      const types = Array.isArray(eventType) ? eventType : [eventType]
      if (types.includes(msg.type)) {
        handler(msg.payload, msg.type)
      }
    }
    const unsubscribe = eventBus.subscribe(onMessage)
    return () => {
      unsubscribe()
    }
  }, [eventType, handler])
}
