"use client"

import { useCallback, useEffect, useRef } from "react"

let isSupported = false

if ("wakeLock" in navigator) {
  isSupported = true
}

interface Options {
  reacquireOnPageVisible?: boolean
  onRequest?: () => void
  onRelease?: () => void
}

/**
 * Uses the Wake Lock API to keep the screen from dimming or locking.
 * https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API
 */
export default function useWakeLock({
  reacquireOnPageVisible = false,
  onRequest = () => undefined,
  onRelease = () => undefined,
}: Options = {}) {
  const wakeLock = useRef<WakeLockSentinel | null>(null)

  const request = useCallback(async () => {
    if (!isSupported) {
      return
    }

    try {
      wakeLock.current = await navigator.wakeLock.request("screen")

      onRequest()

      wakeLock.current.onrelease = () => {
        onRelease()
      }
    } catch (_err) {
      // ignore
    }
  }, [onRelease, onRequest])

  const release = useCallback(() => {
    if (!isSupported) {
      return
    }
    wakeLock.current?.release().then(() => {
      wakeLock.current = null
    })
  }, [])

  useEffect(() => {
    const handleVisibilityChange = () => {
      if (wakeLock.current !== null && document.visibilityState === "visible") {
        request()
      }
    }

    if (reacquireOnPageVisible) {
      document.addEventListener("visibilitychange", handleVisibilityChange)
    }

    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange)
    }
  }, [reacquireOnPageVisible, request])

  return { isSupported, request, release }
}
