export const dateShortcuts = [
  { text: '今天', value: () => { const s = formatDate(new Date()); return [s, s] as [string, string] } },
  { text: '近 7 天', value: () => rangeDays(6) },
  { text: '近 30 天', value: () => rangeDays(29) }
]

export function rangeDays(n: number): [string, string] {
  const end = new Date()
  const start = new Date()
  start.setDate(end.getDate() - n)
  return [formatDate(start), formatDate(end)]
}

export function formatDate(d: Date): string {
  const p = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
}

export function parseTime(raw?: string | null): number | null {
  if (!raw) return null
  const t = Date.parse(raw)
  return Number.isFinite(t) ? t : null
}

export function formatTime(raw?: string | null): string {
  const t = parseTime(raw)
  if (t == null) return '—'
  const d = new Date(t)
  const p = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
}

export function sortByTime(a?: string | null, b?: string | null) {
  return (parseTime(a) ?? 0) - (parseTime(b) ?? 0)
}

export function isToday(raw?: string | null): boolean {
  const t = parseTime(raw)
  if (t == null) return false
  const d = new Date(t)
  const now = new Date()
  return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()
}
