<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'
import { audioProps } from './audio'

defineOptions({
    name: 'UIAudio',
})
defineProps(audioProps)

const audio = ref()
const randoms = ref([1, 0.5, 1, 0.5])
const playIng = ref(false)

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

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

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

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