/**
 * Annotation time helpers — shared between AnnotationsPage and CanvasEditor.
 * Annotation `time` is the backend's "HH:MM:SS.mmm" tick representation; this
 * module owns the conversion to/from seconds + display formatting.
 */

export function parseAnnotationTime(t: string | null | undefined): number | null {
  if (!t) return null
  const parts = t.split(':').map(Number)
  if (parts.length !== 3) return null
  if (parts.some(p => !Number.isFinite(p))) return null
  return (parts[0] || 0) * 3600 + (parts[1] || 0) * 60 + (parts[2] || 0)
}

export function formatTime(seconds: number, withMs = false): string {
  if (!Number.isFinite(seconds) || seconds < 0) seconds = 0
  const m = Math.floor(seconds / 60)
  const s = Math.floor(seconds % 60)
  const base = `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
  if (!withMs) return base
  const ms = Math.floor((seconds - Math.floor(seconds)) * 1000)
  return `${base}.${String(ms).padStart(3, '0')}`
}

export function formatTicks(seconds: number): string {
  if (!Number.isFinite(seconds) || seconds < 0) seconds = 0
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  const ms = Math.floor((seconds - Math.floor(seconds)) * 1000)
  return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}.${String(ms).padStart(3, '0')}`
}
