/** Date / school-year formatting aligned with CI slips views. */

export function formatSchoolYearShort(raw: string): string {
  const schoolYearRaw = String(raw ?? '').trim()
  const m = /^(\d{2,4})\D+(\d{2,4})/.exec(schoolYearRaw)
  if (m) {
    const a = m[1].slice(-2)
    const b = m[2].slice(-2)
    return `${a}-${b}`
  }
  if (/^\d{4}$/.test(schoolYearRaw)) {
    const y = parseInt(schoolYearRaw, 10)
    if (y > 0) return `${schoolYearRaw.slice(-2)}-${String(y + 1).slice(-2)}`
  }
  return schoolYearRaw
}

export function formatSlipDate(raw: string): string {
  const r = String(raw ?? '').trim()
  if (!r) return ''
  if (/^\d{4}-\d{2}-\d{2}$/.test(r)) {
    const [, y, mo, d] = /^(\d{4})-(\d{2})-(\d{2})$/.exec(r) ?? []
    if (y && mo && d) return `${mo}-${d}-${y}`
    return r
  }
  if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(r)) {
    const p = r.split('/')
    if (p.length === 3) {
      const mm = p[0].padStart(2, '0')
      const dd = p[1].padStart(2, '0')
      return `${mm}-${dd}-${p[2]}`
    }
  }
  if (/^\d{1,2}-\d{1,2}-\d{4}$/.test(r)) {
    return r
  }
  return r
}

export function formatPreviewDateKey(value: string): string {
  if (!value || value === 'Unknown Date') return value
  const slash = /^(\d{1,2})\/(\d{1,2})\/(\d{4})(?:\s.*)?$/.exec(value)
  if (slash) {
    const mm = slash[1].padStart(2, '0')
    const dd = slash[2].padStart(2, '0')
    return `${mm}-${dd}-${slash[3]}`
  }
  const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(value)
  if (iso) return `${iso[2]}-${iso[3]}-${iso[1]}`
  return value
}

export function displaySemester(sem: unknown): string {
  const s = String(sem ?? '').trim().toLowerCase()
  if (s === '1' || s === 'fall') return 'Fall'
  if (s === '2' || s === 'spring') return 'Spring'
  if (s === '') return '-'
  return s.charAt(0).toUpperCase() + s.slice(1)
}
