export function useKeyboardShortcuts() {
  const store = usePlayerStore()
  const { togglePlayPause, playNext, playPrev } = useAudioPlayer()

  function isInputFocused(): boolean {
    const el = document.activeElement
    if (!el) return false
    const tag = el.tagName.toLowerCase()
    if (tag === 'input' || tag === 'textarea' || tag === 'select') return true
    if ((el as HTMLElement).isContentEditable) return true
    return false
  }

  function onKeyDown(e: KeyboardEvent) {
    if (isInputFocused()) return
    if (!store.currentSong) return

    switch (e.code) {
      case 'Space':
        e.preventDefault()
        togglePlayPause()
        break
      case 'ArrowRight':
        e.preventDefault()
        playNext()
        break
      case 'ArrowLeft':
        e.preventDefault()
        playPrev()
        break
    }
  }

  onMounted(() => {
    window.addEventListener('keydown', onKeyDown)
  })

  onUnmounted(() => {
    window.removeEventListener('keydown', onKeyDown)
  })
}
