
<template>
  <div class="voice-container" @click="togglePlay">
    <div class="voice-btn" :class="{ playing: isPlaying }">
      <span class="duration">{{ formattedDuration }}"</span>
      <div class="wave">
        <span v-for="n in 3" :key="n" 
              :style="{ height: isPlaying ? getRandomHeight() : '0px' }"></span>
      </div>
    </div>
    <audio ref="audioEl" 
            :src="url"
           @play="handlePlay" 
           @pause="handlePause" 
           @ended="handleEnd"
           @loadedmetadata="updateDuration"></audio>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const props = defineProps({
  url: { type: String, required: true },
  recordingTime: { type: Number },
})

const audioEl = ref(null)
const isPlaying = ref(false)
const duration = ref(0)
let animationFrame

const formattedDuration = computed(() => Math.ceil(duration.value))

const getRandomHeight = () => `${Math.random() * 12 + 4}px`

const togglePlay = () => {
  isPlaying.value ? audioEl.value.pause() : audioEl.value.play()
}

const handlePlay = () => {
  isPlaying.value = true
  animateWave()
}

const handlePause = () => {
  isPlaying.value = false
  cancelAnimationFrame(animationFrame)
}

const handleEnd = () => {
  isPlaying.value = false
  cancelAnimationFrame(animationFrame)
}

const updateDuration = () => {
  duration.value = audioEl.value.duration === Infinity ? props.recordingTime : audioEl.value.duration
}

const animateWave = () => {
  if (!isPlaying.value) return
  animationFrame = requestAnimationFrame(animateWave)
}

// onMounted(() => {
//   audioEl.value.src = props.src
// })

onUnmounted(() => {
  cancelAnimationFrame(animationFrame)
})
</script>

<style scoped>
.voice-container {
  display: inline-block;
  cursor: pointer;
  width: 100px;
}
.voice-btn {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #e6e6e6;
  border-radius: 18px;
  transition: all 0.3s;
}
.voice-btn.playing {
  background: #d3e3fd;
}
.duration {
  margin: 0 12px;
  font-size: 18px;
  color: #666;
}
.wave {
  display: flex;
  align-items: flex-end;
  height: 20px;
  gap: 3px;
}
.wave span {
  display: inline-block;
  width: 4px;
  background: #07C160;
  transition: height 0.3s ease;
}
</style>
