// Hardware media keys (headset buttons, OS media keys, lock-screen controls)
// are only routed to a page actively playing audio through a media element —
// Web Audio beeps do not qualify. A silent looping <audio> element (started
// from the user's ▶ click, satisfying the autoplay policy) is what makes the
// Media Session API actionable here.
const SILENT_LOOP_WAV =
  'data:audio/wav;base64,UklGRrQBAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YZABAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA'

export function useMediaSession() {
  const isSupported = typeof navigator !== 'undefined' && 'mediaSession' in navigator
  let audioEl = null

  function start({ onPlayPause, onNext, onPrevious, onStop } = {}) {
    if (!isSupported) return

    if (!audioEl) {
      audioEl = new Audio(SILENT_LOOP_WAV)
      audioEl.loop = true
    }
    audioEl.play().catch(() => {
      // Autoplay may be rejected outside a user gesture — best effort.
    })

    const ms = navigator.mediaSession
    ms.setActionHandler('play', () => onPlayPause?.())
    ms.setActionHandler('pause', () => onPlayPause?.())
    ms.setActionHandler('nexttrack', () => onNext?.())
    ms.setActionHandler('previoustrack', () => onPrevious?.())
    ms.setActionHandler('stop', () => onStop?.())
  }

  function updateMetadata(step, sessionTitle) {
    if (!isSupported || !step) return
    navigator.mediaSession.metadata = new MediaMetadata({
      title: step.exerciseTitle,
      artist: step.comboTitle || sessionTitle || '',
      album: sessionTitle || '',
    })
  }

  function setPlaybackState(state) {
    if (!isSupported) return
    navigator.mediaSession.playbackState = state
  }

  function stop() {
    if (!isSupported) return
    const ms = navigator.mediaSession
    for (const action of ['play', 'pause', 'nexttrack', 'previoustrack', 'stop']) {
      ms.setActionHandler(action, null)
    }
    ms.playbackState = 'none'
    ms.metadata = null
    if (audioEl) {
      audioEl.pause()
      audioEl.currentTime = 0
    }
  }

  return { isSupported, start, updateMetadata, setPlaybackState, stop }
}
