const AT_RISK_MS = 30 * 60 * 1000

export function remainingMs(deadlineAt, now = Date.now()) {
  if (!deadlineAt) return 0
  return new Date(deadlineAt).getTime() - now
}

export function formatCountdown(deadlineAt, now = Date.now()) {
  const ms = Math.max(0, remainingMs(deadlineAt, now))
  const mins = Math.floor(ms / 60_000)
  const secs = Math.floor((ms % 60_000) / 1000)
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

export function bundleUrgency(bundle, now = Date.now()) {
  const status = bundle.complianceStatus
  if (status === 'NON_COMPLIANT') return 'overdue'
  if (status === 'COMPLIANT') return 'compliant'
  if (remainingMs(bundle.deadlineAt, now) <= 0) return 'overdue'
  if (remainingMs(bundle.deadlineAt, now) <= AT_RISK_MS) return 'at_risk'
  return 'on_track'
}

export function urgencyVariant(urgency) {
  if (urgency === 'overdue') return 'critical'
  if (urgency === 'at_risk') return 'warning'
  if (urgency === 'compliant') return 'success'
  return 'success'
}

export function urgencyLabel(urgency) {
  const map = {
    on_track: 'On track',
    at_risk: 'At risk',
    overdue: 'Overdue',
    compliant: 'Compliant',
  }
  return map[urgency] ?? urgency
}

export function sortBundlesByUrgency(bundles, now = Date.now()) {
  const order = { overdue: 0, at_risk: 1, on_track: 2, compliant: 3 }
  return [...bundles].sort((a, b) => {
    const ua = bundleUrgency(a, now)
    const ub = bundleUrgency(b, now)
    if (order[ua] !== order[ub]) return order[ua] - order[ub]
    return remainingMs(a.deadlineAt, now) - remainingMs(b.deadlineAt, now)
  })
}

export function completedElements(bundle) {
  return (bundle.elements ?? []).filter(e => e.status === 'Completed')
}

export function outstandingElements(bundle) {
  return (bundle.elements ?? []).filter(e => e.status !== 'Completed')
}

export function formatDepartment(department) {
  const map = {
    ICU: 'ICU',
    Icu: 'ICU',
    GENERAL_MEDICINE: 'General Medicine',
    GeneralMedicine: 'General Medicine',
    SURGERY: 'Surgery',
    Surgery: 'Surgery',
  }
  return map[department] ?? department?.replace(/_/g, ' ') ?? '—'
}

export function complianceStatusLabel(status) {
  const map = {
    IN_PROGRESS: 'In progress',
    COMPLIANT: 'Compliant',
    NON_COMPLIANT: 'Non-compliant',
  }
  return map[status] ?? status
}

export function summarizeBundles(bundles, now = Date.now()) {
  const counts = { on_track: 0, at_risk: 0, overdue: 0 }
  for (const bundle of bundles) {
    const urgency = bundleUrgency(bundle, now)
    if (urgency in counts) counts[urgency]++
  }
  return counts
}
