import { usePlayerStore } from '../stores/playerStore.js'
import { useQueueStore } from '../stores/queueStore.js'

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

  playerStore.onEnd(() => {
    const next = queueStore.nextTrack()
    if (next) {
      playerStore.setTrack(next)
      playerStore.play()
    }
  })

  function playTrack(tracks, index) {
    queueStore.setQueue(tracks, index)
    playerStore.setTrack(tracks[index])
    playerStore.play()
  }

  function playNext() {
    const next = queueStore.nextTrack()
    if (next) {
      playerStore.setTrack(next)
      playerStore.play()
    }
  }

  function playPrev() {
    const prev = queueStore.prevTrack()
    if (prev) {
      playerStore.setTrack(prev)
      playerStore.play()
    }
  }

  return { playTrack, playNext, playPrev }
}
