// sound.jsx — Web Audio synthesis (programmatic SFX, no assets)
let _ctx = null;
function ctx() {
  if (!_ctx) {
    const AC = window.AudioContext || window.webkitAudioContext;
    _ctx = new AC();
  }
  return _ctx;
}

function tone({ type = "sine", freq = 440, freqEnd, dur = 0.2, gain = 0.18 }) {
  try {
    const ac = ctx();
    const o = ac.createOscillator();
    const g = ac.createGain();
    o.type = type;
    o.frequency.setValueAtTime(freq, ac.currentTime);
    if (freqEnd !== undefined) {
      o.frequency.exponentialRampToValueAtTime(Math.max(1, freqEnd), ac.currentTime + dur);
    }
    g.gain.setValueAtTime(gain, ac.currentTime);
    g.gain.exponentialRampToValueAtTime(0.0001, ac.currentTime + dur);
    o.connect(g).connect(ac.destination);
    o.start();
    o.stop(ac.currentTime + dur + 0.02);
  } catch (e) {}
}

const SOUNDS = {
  start:    () => { tone({ freq: 440, freqEnd: 660, dur: 0.18 }); setTimeout(() => tone({ freq: 660, freqEnd: 880, dur: 0.15 }), 120); },
  pickup:   () => tone({ freq: 600, dur: 0.08, gain: 0.14 }),
  correct:  () => { tone({ freq: 880, freqEnd: 1100, dur: 0.16 }); setTimeout(() => tone({ freq: 1100, freqEnd: 1320, dur: 0.18 }), 110); },
  wrong:    () => tone({ type: "sawtooth", freq: 300, freqEnd: 150, dur: 0.3, gain: 0.12 }),
  bump:     () => tone({ freq: 200, dur: 0.08, gain: 0.10 }),
  hint:     () => tone({ freq: 800, freqEnd: 1000, dur: 0.2 }),
  gameover: () => { tone({ freq: 400, freqEnd: 250, dur: 0.4 }); setTimeout(() => tone({ freq: 250, freqEnd: 150, dur: 0.5 }), 300); },
};

window.SoundPlayer = {
  play(name) { SOUNDS[name]?.(); },
  resume() { try { ctx().resume(); } catch (e) {} },
};
