import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useEventBusStore = defineStore('eventBus', () => {
  const events = ref<{ [key: string]: { callback: (payload?: any) => void; once: boolean }[] }>({})

  const subscribe = (event: string, callback: (payload?: any) => void) => {
    if (!events.value[event]) {
      events.value[event] = []
    }
    events.value[event].push({ callback, once: false })
  }

  const subscribeOnce = (event: string, callback: (payload?: any) => void) => {
    if (!events.value[event]) {
      events.value[event] = []
    }
    events.value[event].push({ callback, once: true })
  }

  const unsubscribe = (event: string, callback: (payload?: any) => void) => {
    if (events.value[event]) {
      events.value[event] = events.value[event].filter((e) => e.callback !== callback)
    }
  }

  const publish = (event: string, payload?: any) => {
    if (events.value[event]) {
      events.value[event] = events.value[event].filter((e) => {
        e.callback(payload)
        return !e.once // Retain if it's not a one-time event
      })
    }
  }

  return {
    events,
    subscribe,
    subscribeOnce,
    unsubscribe,
    publish
  }
})
