import { useEffect } from "react";
import { notificationPlayer } from "@/lib/notification-sounds";

/**
 * Browsers require a user gesture before audio can play. Listen for the
 * first interaction anywhere on the page and unlock the shared audio
 * context so subsequent socket-driven sounds work.
 */
export function useAudioUnlock(): void {
  useEffect(() => {
    if (typeof window === "undefined") return;
    // #441: We used to detach after the very first gesture, but on
    // iPad Safari the AudioContext can slip back into `suspended`
    // when the tab is backgrounded or after a Bluetooth/AirPlay route
    // change. Calling `unlock()` is cheap and idempotent, so we keep
    // listening and re-resume on every interaction. The detach happens
    // only when the host component unmounts.
    const unlock = () => {
      notificationPlayer.unlock();
    };
    window.addEventListener("pointerdown", unlock);
    window.addEventListener("keydown", unlock);
    window.addEventListener("touchstart", unlock, { passive: true });
    return () => {
      window.removeEventListener("pointerdown", unlock);
      window.removeEventListener("keydown", unlock);
      window.removeEventListener("touchstart", unlock);
    };
  }, []);
}
