import { ref, onMounted, onUnmounted } from 'vue'

export function useFullscreen() {
  const isFullscreen = ref(false)

  function sync() {
    isFullscreen.value = !!document.fullscreenElement
  }

  async function toggle() {
    if (!document.fullscreenElement) {
      await document.documentElement.requestFullscreen().catch(() => {})
    } else {
      await document.exitFullscreen()
    }
  }

  onMounted(() => {
    document.addEventListener('fullscreenchange', sync)
    sync()
  })

  onUnmounted(() => {
    document.removeEventListener('fullscreenchange', sync)
  })

  return { isFullscreen, toggle }
}
