<template>
  <span>
    {{ minutes }}:{{ seconds }}
  </span>
</template>

<script setup type="ts">
const minutes = ref()
const seconds = ref()
const interval = ref()
const props = defineProps(['expired'])
const emits = defineEmits(['end'])
const tmp = ref()
function startCountdown() {
  let now = new Date()
  const end = new Date(props.expired)
  console.log(end)
  let diff = (end.getTime() - now.getTime()) / 1000
  minutes.value = Math.floor(diff / 60)
  seconds.value = Math.floor(diff - (minutes.value * 60))

  if (seconds.value < 10) {
    seconds.value = (seconds.value + '').padStart(2, '0')
  }

  interval.value = setInterval(() => {
    now = new Date()

    let diff = (end.getTime() - now.getTime()) / 1000
    minutes.value = Math.floor(diff / 60)
    seconds.value = Math.floor(diff - (minutes.value * 60))

    if (seconds.value < 10) {
      seconds.value = (seconds.value + '').padStart(2, '0')
    }

    if (diff <= 0) {
      clearInterval(interval.value)
      minutes.value = '0'
      seconds.value = '00'
      emits('end')
    }
  }, 1000)
}
onMounted(() => {
  startCountdown()
})

onBeforeUnmount(() => {
  clearInterval(interval.value)
})

</script>