import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useQueueStore = defineStore('queue', () => {
  const queue = ref([])
  const currentIndex = ref(-1)
  const shuffle = ref(false)
  const repeat = ref('off')

  const currentTrack = computed(() => {
    if (currentIndex.value < 0 || currentIndex.value >= queue.value.length) return null
    return queue.value[currentIndex.value]
  })

  function setQueue(tracks, startIndex = 0) {
    queue.value = tracks
    currentIndex.value = startIndex
  }

  function nextTrack() {
    if (queue.value.length === 0) return null
    if (repeat.value === 'one') return queue.value[currentIndex.value]

    let idx
    if (shuffle.value) {
      idx = Math.floor(Math.random() * queue.value.length)
    } else {
      idx = currentIndex.value + 1
    }

    if (idx >= queue.value.length) {
      if (repeat.value === 'all') {
        idx = 0
      } else {
        return null
      }
    }
    currentIndex.value = idx
    return queue.value[idx]
  }

  function prevTrack() {
    if (queue.value.length === 0) return null
    if (repeat.value === 'one') return queue.value[currentIndex.value]

    let idx
    if (shuffle.value) {
      idx = Math.floor(Math.random() * queue.value.length)
    } else {
      idx = currentIndex.value - 1
    }

    if (idx < 0) {
      if (repeat.value === 'all') {
        idx = queue.value.length - 1
      } else {
        return null
      }
    }
    currentIndex.value = idx
    return queue.value[idx]
  }

  function toggleShuffle() {
    shuffle.value = !shuffle.value
  }

  function cycleRepeat() {
    const modes = ['off', 'all', 'one']
    const i = modes.indexOf(repeat.value)
    repeat.value = modes[(i + 1) % modes.length]
  }

  function $reset() {
    queue.value = []
    currentIndex.value = -1
    shuffle.value = false
    repeat.value = 'off'
  }

  return {
    queue, currentIndex, shuffle, repeat, currentTrack,
    setQueue, nextTrack, prevTrack,
    toggleShuffle, cycleRepeat, $reset,
  }
})
