import { ref, provide, inject } from 'vue'

const VIDEO_PLAYBACK_KEY = Symbol('videoPlayback')

// 当前正在播放的视频ID
const currentPlayingVideo = ref(null)
// 所有注册的视频暂停回调
const pauseCallbacks = ref(new Map())

export function provideVideoPlayback() {
  const setCurrentPlaying = (videoId) => {
    // 暂停其他所有视频
    pauseCallbacks.value.forEach((callback, id) => {
      if (id !== videoId) {
        callback()
      }
    })
    currentPlayingVideo.value = videoId
  }

  const registerVideo = (videoId, pauseCallback) => {
    pauseCallbacks.value.set(videoId, pauseCallback)
  }

  const unregisterVideo = (videoId) => {
    pauseCallbacks.value.delete(videoId)
    if (currentPlayingVideo.value === videoId) {
      currentPlayingVideo.value = null
    }
  }

  const context = {
    currentPlayingVideo,
    setCurrentPlaying,
    registerVideo,
    unregisterVideo
  }

  provide(VIDEO_PLAYBACK_KEY, context)
  return context
}

export function useVideoPlayback() {
  const context = inject(VIDEO_PLAYBACK_KEY, null)
  if (!context) {
    // 如果没有 provider，返回一个空实现
    return {
      currentPlayingVideo: ref(null),
      setCurrentPlaying: () => {},
      registerVideo: () => {},
      unregisterVideo: () => {}
    }
  }
  return context
}
