let ctx = null;
let muted = localStorage.getItem('el3ab_muted') === '1';

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

function synth(freq, duration, type = 'sine', gain = 0.15) {
  if (muted) return;
  const c = getCtx();
  const osc = c.createOscillator();
  const g = c.createGain();
  osc.type = type;
  osc.frequency.value = freq;
  g.gain.value = gain;
  g.gain.exponentialRampToValueAtTime(0.001, c.currentTime + duration);
  osc.connect(g).connect(c.destination);
  osc.start();
  osc.stop(c.currentTime + duration);
}

export const audio = {
  tap() { synth(800, 0.05, 'sine', 0.08); },
  move() { synth(300, 0.08, 'triangle', 0.1); },
  capture() { synth(200, 0.15, 'sawtooth', 0.12); },
  coin() { synth(1200, 0.1, 'sine', 0.1); synth(1600, 0.1, 'sine', 0.08); },
  win() {
    synth(523, 0.15, 'triangle', 0.12);
    setTimeout(() => synth(659, 0.15, 'triangle', 0.12), 100);
    setTimeout(() => synth(784, 0.3, 'triangle', 0.15), 200);
  },
  lose() {
    synth(400, 0.2, 'triangle', 0.1);
    setTimeout(() => synth(350, 0.3, 'triangle', 0.08), 150);
  },
  levelUp() {
    [523, 659, 784, 1047].forEach((f, i) => {
      setTimeout(() => synth(f, 0.2, 'sine', 0.12), i * 80);
    });
  },
  error() { synth(200, 0.2, 'square', 0.08); },
  dice() { for (let i = 0; i < 5; i++) setTimeout(() => synth(100 + Math.random() * 200, 0.04, 'noise' in window ? 'noise' : 'triangle', 0.06), i * 30); },
  notify() { synth(880, 0.08, 'sine', 0.1); setTimeout(() => synth(1100, 0.12, 'sine', 0.08), 80); },

  mute() { muted = true; localStorage.setItem('el3ab_muted', '1'); },
  unmute() { muted = false; localStorage.removeItem('el3ab_muted'); },
  isMuted() { return muted; },
  toggle() { muted ? this.unmute() : this.mute(); return !muted; }
};
