"use client";
import { useEffect } from "react";

// Keep the screen awake while the calling component is mounted. No-ops when
// the Wake Lock API is unavailable, the device isn't touch-primary, or the
// request is denied.
export default function useWakeLock(enabled: boolean) {
  useEffect(() => {
    if (!enabled) return;
    if (typeof navigator === "undefined" || !("wakeLock" in navigator)) return;

    const isTouchDevice =
      window.matchMedia("(hover: none) and (pointer: coarse)").matches ||
      window.innerWidth < 768;
    if (!isTouchDevice) return;

    let sentinel: WakeLockSentinel | null = null;
    let cancelled = false;

    const request = async () => {
      try {
        const lock = await navigator.wakeLock.request("screen");
        if (cancelled) {
          await lock.release();
          return;
        }
        sentinel = lock;
      } catch {
        // Permission denied, page hidden, or unsupported — silently ignore.
      }
    };

    const handleVisibility = () => {
      if (document.visibilityState === "visible" && sentinel === null) {
        request();
      }
    };

    request();
    document.addEventListener("visibilitychange", handleVisibility);

    return () => {
      cancelled = true;
      document.removeEventListener("visibilitychange", handleVisibility);
      if (sentinel) {
        sentinel.release().catch(() => {});
        sentinel = null;
      }
    };
  }, [enabled]);
}
