import * as store from './store.js';

let ctx = null;
const buffers = {};
const volumes = { ui: 0.5, game: 0.7, reward: 0.8 };

const sounds = {
  click: { src: null, freq: 800, dur: 0.05 },
  move: { src: null, freq: 300, dur: 0.1 },
  capture: { src: null, freq: 200, dur: 0.15 },
  check: { src: null, freq: 600, dur: 0.2 },
  castle: { src: null, freq: 400, dur: 0.12 },
  gameOver: { src: null, freq: 150, dur: 0.4 },
  win: { src: null, freq: 523, dur: 0.5 },
  lose: { src: null, freq: 180, dur: 0.6 },
  coin: { src: null, freq: 1200, dur: 0.08 },
  levelUp: { src: null, freq: 880, dur: 0.6 },
  notification: { src: null, freq: 700, dur: 0.15 },
  dice: { src: null, freq: 250, dur: 0.3 },
  place: { src: null, freq: 350, dur: 0.1 }
};

function getCtx() {
  if (!ctx) {
    ctx = new (window.AudioContext || window.webkitAudioContext)();
  }
  return ctx;
}

export function init() {
  document.addEventListener('touchstart', resume, { once: true });
  document.addEventListener('click', resume, { once: true });
}

function resume() {
  const c = getCtx();
  if (c.state === 'suspended') c.resume();
}

export function play(name, category = 'ui') {
  if (!store.get('audioEnabled')) return;
  const sound = sounds[name];
  if (!sound) return;

  const c = getCtx();
  if (c.state === 'suspended') return;

  const osc = c.createOscillator();
  const gain = c.createGain();
  osc.connect(gain);
  gain.connect(c.destination);

  osc.frequency.value = sound.freq;
  osc.type = name === 'click' ? 'sine' : 'triangle';
  gain.gain.setValueAtTime(volumes[category] || 0.5, c.currentTime);
  gain.gain.exponentialRampToValueAtTime(0.001, c.currentTime + sound.dur);

  osc.start(c.currentTime);
  osc.stop(c.currentTime + sound.dur);
}

export function playSequence(notes, interval = 100) {
  notes.forEach((note, i) => {
    setTimeout(() => play(note), i * interval);
  });
}

export function setVolume(category, vol) {
  volumes[category] = Math.max(0, Math.min(1, vol));
}
