import { createGlobalState, useEventListener } from '@vueuse/core'

export const useFullscreenVideo = createGlobalState(() => {
  const videoEl = shallowRef<HTMLVideoElement>()

  const visible = computed(() => !!videoEl.value)

  async function show(stream: MediaStream) {
    if (videoEl.value) {
      videoEl.value.srcObject = stream
    }
    else {
      const el = document.createElement('video')
      el.srcObject = stream
      el.autoplay = true
      el.playsInline = true
      el.controls = false
      el.muted = true
      // el.style.position = 'fixed'
      // el.style.top = '0'
      // el.style.left = '0'
      // el.style.width = '1px'
      // el.style.height = '1px'
      // el.style.opacity = '0'
      // el.style.pointerEvents = 'none'

      document.body.appendChild(el)

      videoEl.value = el
    }

    stream.getTracks().forEach(t =>
      t.addEventListener('ended', hide),
    )
    videoEl.value.addEventListener('ended', hide)

    await videoEl.value.requestFullscreen()
  }

  function hide() {
    if (!videoEl.value)
      return

    (videoEl.value.srcObject as MediaStream).getTracks().forEach(t =>
      t.removeEventListener('ended', hide),
    )
    videoEl.value.removeEventListener('ended', hide)

    videoEl.value?.remove()
    videoEl.value = undefined
  }

  useEventListener(document, 'fullscreenchange', () => {
    if (!document.fullscreenElement && videoEl.value) {
      videoEl.value?.remove()
      videoEl.value = undefined
    }
  })

  return {
    visible,
    show,
    hide,
  }
})
