import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import audioEngine from '../lib/audioEngine.js'
import { formatUrl } from '../lib/utils.js'

export const usePlayerStore = defineStore('player', () => {
  const currentTrack = ref(null)
  const isPlaying = ref(false)
  const progress = ref(0)
  const duration = ref(0)
  const volume = ref(80)
  const seekInterval = ref(null)
  const onEndCallback = ref(null)

  const formattedProgress = computed(() => audioEngine.formatTime(progress.value))
  const formattedDuration = computed(() => audioEngine.formatTime(duration.value))

  function setTrack(track) {
    if (!track) return
    currentTrack.value = track
    progress.value = 0
    duration.value = 0
    isPlaying.value = false
    stopSeekInterval()

    const audioUrl = formatUrl(track.audioUrl)

    audioEngine.load(audioUrl)
    audioEngine.on('play', () => { isPlaying.value = true })
    audioEngine.on('pause', () => { isPlaying.value = false })
    audioEngine.on('end', () => {
      isPlaying.value = false
      stopSeekInterval()
      if (onEndCallback.value) onEndCallback.value()
    })
    audioEngine.on('error', () => { isPlaying.value = false })
  }

  function onEnd(cb) {
    onEndCallback.value = cb
  }

  function togglePlay() {
    if (!currentTrack.value) return
    if (audioEngine.playing()) {
      audioEngine.pause()
      stopSeekInterval()
    } else {
      audioEngine.play()
      startSeekInterval()
    }
  }

  function play() {
    if (!currentTrack.value) return
    audioEngine.play()
    startSeekInterval()
  }

  function seek(time) {
    audioEngine.seek(time)
    progress.value = time
  }

  function setVolume(val) {
    volume.value = val
    audioEngine.volume(val)
  }

  function startSeekInterval() {
    stopSeekInterval()
    seekInterval.value = setInterval(() => {
      if (audioEngine.playing()) {
        progress.value = audioEngine.getSeek()
        duration.value = audioEngine.duration()
      }
    }, 500)
  }

  function stopSeekInterval() {
    if (seekInterval.value) {
      clearInterval(seekInterval.value)
      seekInterval.value = null
    }
  }

  function $reset() {
    stopSeekInterval()
    audioEngine.destroy()
    currentTrack.value = null
    isPlaying.value = false
    progress.value = 0
    duration.value = 0
    onEndCallback.value = null
  }

  return {
    currentTrack, isPlaying, progress, duration, volume,
    formattedProgress, formattedDuration,
    setTrack, onEnd, togglePlay, play, seek, setVolume, $reset,
  }
})
