let audioCtx = null

function getCtx() {
  if (!audioCtx) audioCtx = new AudioContext()
  return audioCtx
}

function _beep(freq, duration, gain) {
  try {
    const ctx = getCtx()
    if (ctx.state === 'suspended') ctx.resume()
    const osc = ctx.createOscillator()
    const gainNode = ctx.createGain()
    osc.connect(gainNode)
    gainNode.connect(ctx.destination)
    osc.frequency.value = freq
    gainNode.gain.value = gain
    osc.start()
    osc.stop(ctx.currentTime + duration)
  } catch (_e) {
    // Ignore audio errors — beep is best-effort
  }
}

export function useAudioCues() {
  function playBip(volume = 1.0) {
    _beep(440, 0.1, 0.6 * volume)
  }
  function playBIP(volume = 1.0) {
    _beep(880, 0.3, 1.0 * volume)
  }
  return { playBip, playBIP }
}
