<script setup lang="ts">
/**
 * 抢购倒计时
 *
 * 接收后端返回的剩余秒数，本地每秒递减，归零后触发 expire
 */
import { ref, watch, onUnmounted } from 'vue'

const props = defineProps<{
  seconds: number
}>()

const emit = defineEmits<{
  (e: 'expire'): void
}>()

const remaining = ref(Math.max(0, props.seconds))
let timer: ReturnType<typeof setInterval> | null = null

function stop() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

function restart() {
  stop()
  if (remaining.value <= 0) return
  timer = setInterval(() => {
    remaining.value = Math.max(0, remaining.value - 1)
    if (remaining.value <= 0) {
      stop()
      emit('expire')
    }
  }, 1000)
}

watch(() => props.seconds, (value) => {
  remaining.value = Math.max(0, value)
  restart()
}, { immediate: true })

onUnmounted(stop)

function format(total: number) {
  const days = Math.floor(total / 86400)
  const hours = Math.floor((total % 86400) / 3600)
  const minutes = Math.floor((total % 3600) / 60)
  const seconds = total % 60
  const hh = String(hours).padStart(2, '0')
  const mm = String(minutes).padStart(2, '0')
  const ss = String(seconds).padStart(2, '0')
  return days > 0 ? `${days}天 ${hh}:${mm}:${ss}` : `${hh}:${mm}:${ss}`
}
</script>

<template>
  <span class="countdown-text">{{ format(remaining) }}</span>
</template>

<style lang="scss" scoped>
.countdown-text {
  font-family: 'Fredoka', sans-serif;
  font-size: $font-size-lg;
  font-weight: 700;
  color: $color-primary;
  letter-spacing: 0;
  white-space: nowrap;
}
</style>
