/*
  audio.js — Save Pet
  Wraps HTMLAudioElement playback for SFX + looping music. Uses a
  small clone-pool per effect so overlapping sounds (e.g. two bees
  popping the same frame) don't cut each other off. All playback
  is wrapped defensively since mobile autoplay policies can reject
  audio until the user has interacted with the page at least once.
*/
window.SP = window.SP || {};

SP.Audio = (function () {
  "use strict";

  const SFX_FILES = {
    click: "assets/audio/sfx_click.wav",
    pop: "assets/audio/sfx_pop.wav",
    popTank: "assets/audio/sfx_pop_tank.wav",
    hit: "assets/audio/sfx_hit.wav",
    coin: "assets/audio/sfx_coin.wav",
    star: "assets/audio/sfx_star.wav",
    win: "assets/audio/sfx_win.wav",
    lose: "assets/audio/sfx_lose.wav",
    whoosh: "assets/audio/sfx_whoosh.wav",
    achievement: "assets/audio/sfx_achievement.wav",
    tick: "assets/audio/sfx_tick.wav",
    unlock: "assets/audio/sfx_unlock.wav",
    error: "assets/audio/sfx_error.wav"
  };
  const MUSIC_FILES = {
    menu: ["assets/audio/music_menu.mp3", "assets/audio/music_menu.ogg"],
    game: ["assets/audio/music_game.mp3", "assets/audio/music_game.ogg"]
  };

  const pool = {};
  let musicEl = null;
  let currentTrack = null;
  let gestureUnlocked = false;

  function settings() {
    return (SP.Storage && SP.Storage.data && SP.Storage.data.settings) || { sfxOn: true, musicOn: true, sfxVolume: 0.85, musicVolume: 0.6 };
  }

  function preload() {
    Object.keys(SFX_FILES).forEach(function (name) {
      const a = new Audio(SFX_FILES[name]);
      a.preload = "auto";
      a.volume = settings().sfxVolume;
      pool[name] = [a];
    });
  }

  function getVoice(name) {
    const list = pool[name];
    if (!list) return null;
    let free = null;
    for (let i = 0; i < list.length; i++) {
      if (list[i].paused || list[i].ended) { free = list[i]; break; }
    }
    if (!free) {
      free = list[0].cloneNode(true);
      list.push(free);
      if (list.length > 5) list.shift();
    }
    return free;
  }

  function play(name) {
    try {
      if (!settings().sfxOn) return;
      const voice = getVoice(name);
      if (!voice) return;
      voice.currentTime = 0;
      voice.volume = settings().sfxVolume;
      const p = voice.play();
      if (p && p.catch) p.catch(function () { /* blocked until user gesture — safe no-op */ });
    } catch (e) { /* never let audio break gameplay */ }
  }

  function pickSource(list) {
    try {
      const probe = document.createElement("audio");
      for (let i = 0; i < list.length; i++) {
        const ext = list[i].split(".").pop();
        const type = ext === "mp3" ? "audio/mpeg" : (ext === "ogg" ? "audio/ogg" : "audio/wav");
        if (probe.canPlayType(type)) return list[i];
      }
    } catch (e) { /* fall through */ }
    return list[0];
  }

  function ensureMusicEl() {
    if (!musicEl) {
      musicEl = new Audio();
      musicEl.loop = true;
    }
    return musicEl;
  }

  function playMusic(track) {
    if (!MUSIC_FILES[track] || currentTrack === track) return;
    currentTrack = track;
    try {
      const el = ensureMusicEl();
      el.pause();
      el.src = pickSource(MUSIC_FILES[track]);
      el.volume = settings().musicVolume;
      if (settings().musicOn) {
        const p = el.play();
        if (p && p.catch) p.catch(function () { /* wait for gesture */ });
      }
    } catch (e) { /* ignore */ }
  }

  function stopMusic() {
    currentTrack = null;
    if (musicEl) musicEl.pause();
  }

  function setMusicEnabled(on) {
    if (!musicEl) return;
    if (on) {
      const p = musicEl.play();
      if (p && p.catch) p.catch(function () {});
    } else {
      musicEl.pause();
    }
  }

  function refreshVolumes() {
    const s = settings();
    if (musicEl) musicEl.volume = s.musicVolume;
  }

  function unlockOnGesture() {
    if (gestureUnlocked) return;
    gestureUnlocked = true;
    if (musicEl && musicEl.paused && settings().musicOn && currentTrack) {
      const p = musicEl.play();
      if (p && p.catch) p.catch(function () {});
    }
  }

  function init() {
    preload();
    const resume = function () {
      unlockOnGesture();
      document.removeEventListener("pointerdown", resume);
      document.removeEventListener("keydown", resume);
      document.removeEventListener("touchstart", resume);
    };
    document.addEventListener("pointerdown", resume, { once: true });
    document.addEventListener("keydown", resume, { once: true });
    document.addEventListener("touchstart", resume, { once: true });
  }

  return {
    init: init, play: play, playMusic: playMusic, stopMusic: stopMusic,
    setMusicEnabled: setMusicEnabled, refreshVolumes: refreshVolumes, unlockOnGesture: unlockOnGesture
  };
})();
