/**
 * Navigation sound effects for TV remote / keyboard navigation.
 * Plays subtle audio feedback when navigating between focusable elements.
 */

// Single nav sound — only nav-select.mp3 is used. nav-move.mp3 was
// removed per user request so there is exactly ONE sound, never a
// double-noise on tap / navigation.
let navSound: HTMLAudioElement | null = null;

// Suppress sounds that come from PROGRAMMATIC focus (initial page mount,
// focus-restore, watchdog). Those fire `onFocus` without any real user
// gesture and caused the "auto-selected 3 times on page change" noise.
// We only play when a genuine key / pointer input happened recently.
let lastUserInputAt = 0;
const USER_INPUT_WINDOW_MS = 800;
// Debounce so the hover→focus (move) + click (select) pair a single tap
// produces collapses into ONE sound instead of two.
let lastPlayedAt = 0;
const PLAY_DEBOUNCE_MS = 150;

if (typeof window !== "undefined") {
  const mark = () => {
    lastUserInputAt = Date.now();
  };
  window.addEventListener("keydown", mark, { capture: true, passive: true });
  window.addEventListener("pointerdown", mark, { capture: true, passive: true });
}

// User preference stored in localStorage
const SOUNDS_ENABLED_KEY = "nadiplay_nav_sounds";

/**
 * Check if navigation sounds are enabled.
 * Defaults to true for TV platforms, false for mobile/web.
 */
export function areSoundsEnabled(): boolean {
  if (typeof window === "undefined") return false;
  const stored = localStorage.getItem(SOUNDS_ENABLED_KEY);
  if (stored !== null) return stored === "1";
  // Default: enabled
  return true;
}

/**
 * Enable or disable navigation sounds.
 */
export function setSoundsEnabled(enabled: boolean): void {
  localStorage.setItem(SOUNDS_ENABLED_KEY, enabled ? "1" : "0");
}

/**
 * Toggle navigation sounds on/off.
 */
export function toggleSounds(): boolean {
  const next = !areSoundsEnabled();
  setSoundsEnabled(next);
  return next;
}

/**
 * Preload sound files for instant playback.
 * Call this early in app initialization.
 */
export function preloadSounds(): void {
  if (typeof window === "undefined") return;
  try {
    navSound = new Audio("/audio/nav-select.mp3");
    navSound.preload = "auto";
    navSound.volume = 0.5;
  } catch (e) {
    console.warn("Failed to preload nav sound:", e);
  }
}

/**
 * Play the single navigation sound (nav-select.mp3).
 * Gated so programmatic focus (page load / restore) stays silent and
 * the move+select pair from one tap collapses into a single play.
 */
function playNavSound(): void {
  if (!areSoundsEnabled()) return;
  const now = Date.now();
  // Ignore programmatic focus — only real user navigation has a recent
  // key / pointer event. Fixes "auto-selected 3 times on page change".
  if (now - lastUserInputAt > USER_INPUT_WINDOW_MS) return;
  // Collapse the move+select double that a single tap produces.
  if (now - lastPlayedAt < PLAY_DEBOUNCE_MS) return;
  lastPlayedAt = now;
  try {
    if (!navSound) {
      navSound = new Audio("/audio/nav-select.mp3");
      navSound.volume = 0.5;
    }
    // Clone to allow rapid successive plays.
    const sound = navSound.cloneNode() as HTMLAudioElement;
    sound.volume = 0.5;
    sound.play().catch(() => {});
  } catch (e) {
    // Ignore audio errors
  }
}

/**
 * Play the navigation/move sound (when focus changes between items).
 * Now routes through the single gated nav sound.
 */
export function playMoveSound(): void {
  playNavSound();
}

/**
 * Play the select/confirm sound (when Enter/OK is pressed).
 * Now routes through the single gated nav sound.
 */
export function playSelectSound(): void {
  playNavSound();
}
