<template>
  <button
    v-if="song"
    class="inline-flex items-center gap-2 rounded-full bg-primary/10 px-4 py-1.5 text-sm font-medium text-primary transition-all hover:bg-primary/20 hover:scale-105 active:scale-95 my-2"
    @click="handlePlay"
  >
    <div
      :class="isCurrentAndPlaying ? 'i-lucide-pause' : 'i-lucide-play'"
      class="h-4 w-4"
    />
    <span>{{ song.title }}</span>
    <span class="font-mono text-xs text-primary/60">
      {{ formatDuration(song.duration) }}
    </span>
  </button>
</template>

<script setup lang="ts">
const props = defineProps<{
  song: string
}>()

const store = usePlayerStore()
const bookData = useBookData()
const { loadAndPlay, togglePlayPause } = useAudioPlayer()

await bookData.init()

const song = computed(() => bookData.getSongById(props.song))

const isCurrentAndPlaying = computed(() =>
  store.currentSong?.id === props.song && store.isPlaying,
)

function handlePlay() {
  if (store.currentSong?.id === props.song) {
    togglePlayPause()
  }
  else if (song.value) {
    loadAndPlay(song.value)
  }
}

function formatDuration(seconds: number): string {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}
</script>
