import { onMounted, onUnmounted } from 'vue'
import { usePlayerStore } from '../stores/playerStore.js'
import { useQueueStore } from '../stores/queueStore.js'

export function useKeyboard() {
  const playerStore = usePlayerStore()
  const queueStore = useQueueStore()

  function handler(e) {
    if (['INPUT', 'TEXTAREA'].includes(e.target.tagName)) return

    switch (e.code) {
      case 'Space':
        e.preventDefault()
        playerStore.togglePlay()
        break
      case 'ArrowLeft':
        playerStore.seek(Math.max(0, playerStore.progress - 5))
        break
      case 'ArrowRight':
        playerStore.seek(Math.min(playerStore.duration, playerStore.progress + 5))
        break
      case 'ArrowUp':
        playerStore.setVolume(Math.min(100, playerStore.volume + 5))
        break
      case 'ArrowDown':
        playerStore.setVolume(Math.max(0, playerStore.volume - 5))
        break
    }
  }

  onMounted(() => window.addEventListener('keydown', handler))
  onUnmounted(() => window.removeEventListener('keydown', handler))
}
