<template>
    <div class="ui-audio" @click="clickHandler">
        <audio ref="audio" autoplay loop @play="rotation">
            <source :src="src" />
        </audio>
        <span v-for="random in randoms" :key="random" :style="{ '--percent': random }" />
    </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, watchEffect } from 'vue'
defineOptions({
    name: 'UIAudio',
})
defineProps({
    src: String,
})
const audio = ref()
const randoms = ref([1, 0.5, 1, 0.5])
const playIng = ref(false)

let timeout: ReturnType<typeof setTimeout>
const rotation = () => {
    if (!playIng.value) return
    for (let i = 0; i < randoms.value.length; i++) {
        randoms.value[i] = Math.random()
    }
    timeout = setTimeout(rotation, 200)
}

watchEffect(() => {
    if (audio.value) {
        if (playIng.value) {
            audio.value.play()
        } else {
            audio.value.pause()
        }
        clearTimeout(timeout)
        rotation()
    }
})

const clickHandler = () => {
    playIng.value = !playIng.value
}

defineExpose({
    play() {
        playIng.value = true
    },
    pause() {
        playIng.value = false
    },
})
</script>
