import { ref } from 'vue'

const startedAt = ref<number | null>(null)

export function useQuizTimer() {
  function startQuestionTimer() {
    startedAt.value = Date.now()
  }

  function consumeDurationSeconds(): number {
    if (startedAt.value == null) return 0
    const sec = Math.round((Date.now() - startedAt.value) / 1000)
    startedAt.value = null
    if (sec <= 0) return 1
    return Math.min(sec, 3600)
  }

  return { startQuestionTimer, consumeDurationSeconds }
}

export function formatTrainSeconds(total: number): string {
  if (total < 60) return `${total} 秒`
  const m = Math.floor(total / 60)
  const s = total % 60
  return s ? `${m} 分 ${s} 秒` : `${m} 分钟`
}
