<template>
  <div class="fixed left-0 bottom-0 opacity-1 z-50 w-full bg-white transition-all"
    :class="{ '-bottom-20 opacity-0': !playerStore.currentTrack }">
    <!-- <p>
      {{ Math.round(currentTime) }}
      {{ Math.round(currentProgression) }}%
    </p> -->
    {{ playerStore.currentTrack?.url }}
    <audio ref="audioRef" class="w-full" :src="playerStore.currentTrack?.url || ''" controls />
  </div>
</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)
const currentTime = ref(0)
const lastValidProgression = ref(0)

const currentProgression = computed(() => {
  if (!audioRef.value) return 0
  const progression = (currentTime.value / audioRef.value.duration) * 100

  if (!isNaN(progression)) {
    lastValidProgression.value = progression
  }

  return lastValidProgression.value
})

function updateTime() {
  if (audioRef.value) {
    currentTime.value = audioRef.value.currentTime
  }
}

onMounted(() => {
  if (audioRef.value) {
    playerStore.audio = audioRef.value
    audioRef.value.addEventListener("timeupdate", updateTime)
  }
})

onUnmounted(() => {
  if (audioRef.value) {
    audioRef.value.removeEventListener("timeupdate", updateTime)
  }
})
</script>
