<!-- // eslint-disable-next-line vue/multi-word-component-names -->
<template>
  <div class="howl-player">
    <button @click="togglePlay">
      {{ isPlaying ? 'Pause' : 'Play' }}
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Howl } from 'howler'
import tracksConfig from '~/tracks.config'

// === PROPS ===
const audioUrl = tracksConfig.debug_src

// === STATE ===
const isPlaying = ref(false)
let sound: Howl | null = null

// === LOGIK ===
const togglePlay = () => {
  if (!sound) { return }

  if (isPlaying.value) {
    sound.pause()
    isPlaying.value = false
  } else {
    sound.play()
    isPlaying.value = true
  }
}

onMounted(() => {
  sound = new Howl({
    src: [audioUrl],
    html5: true,
    onend: () => {
      isPlaying.value = false
    },
    onplayerror: (id, err) => {
      useNuxtApp().$logger.warn('Playback error:', err)
    }
  })
})

onBeforeUnmount(() => {
  sound?.unload()
})
</script>

<style scoped>
button {
  padding: 0.5rem 1rem;
  font-size: 1rem;
}
</style>
