export function formatMedicationLabel(med) {
  const name = med.drugName?.length > 12
    ? `${med.drugName.slice(0, 11)}…`
    : med.drugName
  return name ?? 'Med'
}

export function formatMedicationTooltip(med) {
  return `${med.drugName} ${med.dose}${med.doseUnit} (${med.route}) — ${new Date(med.administeredAt).toLocaleString()}`
}

export function filterMedicationsForWindow(observations, code, medications) {
  const series = (observations ?? [])
    .filter(o => o.observationCode === code)
    .sort((a, b) => new Date(a.recordedAt) - new Date(b.recordedAt))

  if (!series.length) return []

  const min = new Date(series[0].recordedAt).getTime()
  const max = new Date(series[series.length - 1].recordedAt).getTime()

  return (medications ?? []).filter(m => {
    const t = new Date(m.administeredAt).getTime()
    if (min === max) return Math.abs(t - min) <= 60_000
    return t >= min && t <= max
  })
}

export function getMedicationsNearTimestamp(medications, targetMs, windowMs = 15 * 60 * 1000) {
  return (medications ?? []).filter(m => {
    const t = new Date(m.administeredAt).getTime()
    return Math.abs(t - targetMs) <= windowMs
  })
}

export function xPixelForMedicationTime(administeredAt, timestamps, chartArea) {
  if (!timestamps?.length || !chartArea) return null

  const medTime = new Date(administeredAt).getTime()
  const times = timestamps.map(t => new Date(t).getTime())

  if (times.length === 1) {
    if (Math.abs(medTime - times[0]) > 60_000) return null
    return (chartArea.left + chartArea.right) / 2
  }

  const min = times[0]
  const max = times[times.length - 1]
  if (medTime < min || medTime > max) return null

  const ratio = (medTime - min) / (max - min)
  return chartArea.left + ratio * chartArea.width
}
