"use client";

import { useEffect, useRef } from "react";

/** Keeps the screen awake while the component is mounted and the tab is visible. */
export function useWakeLock(enabled = true) {
  const wakeLockRef = useRef<WakeLockSentinel | null>(null);

  useEffect(() => {
    if (!enabled) return;

    let cancelled = false;

    async function acquire() {
      try {
        const lock = await navigator.wakeLock?.request("screen");
        if (cancelled) {
          void lock?.release();
          return;
        }
        wakeLockRef.current = lock ?? null;
      } catch {
        // Wake Lock unsupported or denied — silently degrade.
      }
    }

    function handleVisibilityChange() {
      if (document.visibilityState === "visible" && !wakeLockRef.current) {
        void acquire();
      }
    }

    void acquire();
    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      cancelled = true;
      document.removeEventListener("visibilitychange", handleVisibilityChange);
      void wakeLockRef.current?.release().catch(() => {});
      wakeLockRef.current = null;
    };
  }, [enabled]);
}
