import { ref, onUnmounted } from 'vue'

/**
 * 倒计时 composable（日志自动刷新倒计时用）
 */
export function useCountdown(total: number) {
  const remaining = ref(total)
  let timer: ReturnType<typeof setInterval> | null = null

  function start() {
    stop()
    remaining.value = total
    timer = setInterval(() => {
      remaining.value--
      if (remaining.value <= 0) {
        remaining.value = total
      }
    }, 1000)
  }

  function reset() {
    remaining.value = total
  }

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

  onUnmounted(stop)

  return { remaining, start, stop, reset }
}
