<template>
  <section class="text-white flex flex-col sticky">
    <div class="player top-0 w-full bg-gray-500 p-10">
      <nuxt-link to="/" class="flex flex-col items-center">
        <img src="/logo.svg" class="w-44">
      </nuxt-link>
      <h1 class="text-4xl">{{ route.params.id }}</h1>
      <h2 class="text-2xl p-4 text-esyellow">{{ currentTrack }}</h2>
      <audio ref="playlistPlayer" :src="currentTrackUrl" @ended="onTrackEnd" controls></audio>
    </div>
    <button v-for="(track, index) in tracks.files"
      class="text-white p-4 inline-flex hover:bg-esyellow hover:text-black w-full" :index="index" @click="play(index)"
      :class="{ 'playing': index === currentTrackId }">
      {{ index }}
      {{ track }}
    </button>
  </section>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useRoute } from 'vue-router'
const playlistPlayer = ref()
const currentTrackId = ref(0)
const route = useRoute()
const { data: tracks } = await useFetch('/api/playlists/' + route.params.id)

const currentTrack = computed(() => tracks.value.files[currentTrackId.value])
const currentTrackUrl = computed(() => 'https://files.erudi.fr/music/' + route.params.id + '/' + currentTrack.value)

const play = async (trackId) => {
  if (trackId != currentTrackId.value) {
    currentTrackId.value = trackId
    await playlistPlayer.value.load()
  }
  if (playlistPlayer.value.currentTime > 0 && !playlistPlayer.value.paused && !playlistPlayer.value.ended && playlistPlayer.value.readyState > 2) {
    playlistPlayer.value.pause()
  } else {
    playlistPlayer.value.play()
  }
}

const onTrackEnd = () => {
  play(currentTrackId.value + 1)
}
</script>

<style>
.playing {
  @apply bg-esyellow text-black;
}
</style>