import { ref, onMounted, onUnmounted } from 'vue'
import { state } from './useOverlayState'

export function useTime() {
  const timeStr = ref('00:00')
  const dateStr = ref('1月1日 周一')
  const holidayStr = ref('')
  let timer: number | null = null
  let lastTime = ''
  let lastDate = ''

  const holidays = [
    { m: 1, d: 1, name: '元旦' },
    { m: 2, d: 14, name: '情人节' },
    { m: 3, d: 8, name: '妇女节' },
    { m: 4, d: 5, name: '清明节' },
    { m: 5, d: 1, name: '劳动节' },
    { m: 5, d: 4, name: '青年节' },
    { m: 6, d: 1, name: '儿童节' },
    { m: 7, d: 1, name: '建党节' },
    { m: 8, d: 1, name: '建军节' },
    { m: 9, d: 10, name: '教师节' },
    { m: 10, d: 1, name: '国庆节' },
    { m: 10, d: 31, name: '万圣节' },
    { m: 12, d: 25, name: '圣诞节' },
  ]

  function getNextHoliday(now: Date) {
    const y = now.getFullYear()
    const results: { diff: number; name: string }[] = []
    for (const h of holidays) {
      const target = new Date(y, h.m - 1, h.d)
      let diff = Math.ceil((target.getTime() - now.getTime()) / 86400000)
      if (diff > 0 && diff <= 60) results.push({ diff, name: h.name })
      if (diff < 0) {
        const next = new Date(y + 1, h.m - 1, h.d)
        diff = Math.ceil((next.getTime() - now.getTime()) / 86400000)
        if (diff > 0 && diff <= 60) results.push({ diff, name: h.name })
      }
    }
    results.sort((a, b) => a.diff - b.diff)
    return results.length > 0 ? `距${results[0].name}还有${results[0].diff}天` : ''
  }

  function update() {
    const now = new Date()
    const hh = String(now.getHours()).padStart(2, '0')
    const mm = String(now.getMinutes()).padStart(2, '0')
    const ss = String(now.getSeconds()).padStart(2, '0')
    const t = state.showSeconds ? `${hh}:${mm}:${ss}` : `${hh}:${mm}`
    const month = now.getMonth() + 1
    const day = now.getDate()
    const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][now.getDay()]
    const d = `${month}月${day}日 ${week}`

    if (t !== lastTime) {
      timeStr.value = t
      lastTime = t
    }
    if (d !== lastDate) {
      const h = getNextHoliday(now)
      dateStr.value = d
      holidayStr.value = h
      lastDate = d
    }
  }

  onMounted(() => {
    update()
    timer = window.setInterval(update, 1000)
  })
  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })

  return { timeStr, dateStr, holidayStr }
}
