const audioCache = {};
let scrollAudio = null; 
let mouseAudio = null;
const SCROLL_VOLUME = 0.6; 
const clampVolume = (v = 1) => Math.max(0, Math.min(1, v));

function playAudio(file, volume = 1) {
  let audio = audioCache[file];
  if (!audio) {
    audio = new Audio(chrome.runtime.getURL(file));
    audioCache[file] = audio;
  }
  audio.volume = clampVolume(volume);
  audio.currentTime = 0;
  audio.play().catch((err) => console.error("Audio play failed", err));
}

function getScrollAudio() {
  if (!scrollAudio) {
    scrollAudio = new Audio(chrome.runtime.getURL("mp3/drumroll.mp3"));
    scrollAudio.loop = true;
  }
  return scrollAudio;
}

function getMouseAudio() {
  const expectedSrc = chrome.runtime.getURL("mp3/lethergo.mp3");
  if (!mouseAudio || mouseAudio.src !== expectedSrc) {
    mouseAudio = new Audio(chrome.runtime.getURL("mp3/lethergo.mp3"));
    mouseAudio.loop = true;
  }
  return mouseAudio;
}

function startScrollAudio() {
  const audio = getScrollAudio();
  audio.volume = SCROLL_VOLUME;
  if (audio.paused) {
    audio.currentTime = 0;
    audio.play().catch((err) => console.error("Scroll audio play failed", err));
  }
}

function stopScrollAudio() {
  if (scrollAudio && !scrollAudio.paused) {
    scrollAudio.pause();
    scrollAudio.currentTime = 0;
  }
}

function startMouseAudio() {
  const audio = getMouseAudio();
  audio.volume = 1;
  if (audio.paused) {
    audio.currentTime = 0;
    audio.play().catch((err) => console.error("Mouse audio play failed", err));
  }
}

function stopMouseAudio() {
  if (mouseAudio && !mouseAudio.paused) {
    mouseAudio.pause();
    mouseAudio.currentTime = 0;
  }
}

chrome.runtime.onMessage.addListener((msg) => {
  if (msg?.type === "play" && msg.file) {
    playAudio(msg.file, msg.volume);
  } else if (msg?.type === "scroll-sound") {
    startScrollAudio();
  } else if (msg?.type === "scroll-stop") {
    stopScrollAudio();
  } else if (msg?.type === "mouse-move") {
    startMouseAudio();
  } else if (msg?.type === "mouse-stop") {
    stopMouseAudio();
  }
});
