<template>
  <audio ref="audioRef" class="fixed z-50 bottom-0 left-1/2 -translate-x-1/2 w-1/2"
    :src="playerStore.currentTrack ? playerStore.getCompilationUrlFromTrack(playerStore.currentTrack) : ''" controls
    @timeupdate="updatePosition" @ended="onEnded" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { usePlayerStore } from '~/store/player'

const playerStore = usePlayerStore()
const audioRef = ref<HTMLAudioElement | null>(null)

onMounted(() => {
  if (audioRef.value) playerStore.audio = audioRef.value
})

// Mettre à jour la position
function updatePosition() {
  if (audioRef.value) playerStore.position = audioRef.value.currentTime
}

function onEnded() {
  playerStore.isPlaying = false
}

// Si la track change, mettre à jour le src et le start
watch(
  () => playerStore.currentTrack,
  (newTrack) => {
    if (newTrack && audioRef.value) {
      audioRef.value.src = newTrack.url
      audioRef.value.currentTime = newTrack.start || 0
      if (playerStore.isPlaying) audioRef.value.play()
    }
  }
)
</script>
