export type KbxWmsFeedbackKind = 'success' | 'warning' | 'error' | 'neutral'

function vibrate(pattern: number | number[]) {
  // Vibration is progressive enhancement: unsupported browsers simply skip it.
  if (typeof navigator !== 'undefined' && 'vibrate' in navigator) {
    navigator.vibrate(pattern)
  }
}

function beep(frequency: number, durationMs: number) {
  if (typeof window === 'undefined') return
  const AudioContextCtor = window.AudioContext ?? (window as any).webkitAudioContext
  if (!AudioContextCtor) return

  try {
    const context = new AudioContextCtor()
    const oscillator = context.createOscillator()
    const gain = context.createGain()
    oscillator.frequency.value = frequency
    gain.gain.value = 0.035
    oscillator.connect(gain)
    gain.connect(context.destination)
    oscillator.start()
    oscillator.stop(context.currentTime + durationMs / 1000)
    oscillator.addEventListener('ended', () => void context.close())
  } catch {
    // Sound is non-authoritative feedback. Never block WMS work because audio failed.
  }
}

export function playKbxWmsFeedback(kind: KbxWmsFeedbackKind) {
  switch (kind) {
    case 'success':
      beep(880, 80)
      vibrate(50)
      break
    case 'warning':
      beep(520, 120)
      vibrate([70, 40, 70])
      break
    case 'error':
      beep(220, 180)
      vibrate([120, 60, 120])
      break
    default:
      beep(660, 60)
  }
}
