import type { StudentScoreCardRow } from '../../api/types'

/** Numeric value for sorting displayed semester scores (`—` / non-numeric → NaN). */
export function parseScoreSortLabel(label: string): number {
  const s = label.trim()
  if (s === '' || s === '—' || s === 'N/A') return Number.NaN
  const n = Number.parseFloat(s)
  return Number.isFinite(n) ? n : Number.NaN
}

export function formatSemesterScore(val: unknown): string {
  if (val === null || val === undefined || val === '') return '—'
  if (typeof val === 'number' && Number.isFinite(val)) {
    let out = val.toFixed(1)
    if (out.endsWith('.0')) out = out.slice(0, -2)
    return out
  }
  if (typeof val === 'string' && val.trim() !== '' && !Number.isNaN(Number(val))) {
    const n = Number(val)
    let out = n.toFixed(1)
    if (out.endsWith('.0')) out = out.slice(0, -2)
    return out
  }
  return String(val)
}

const SEM_SORT = ['fall', 'spring', 'summer']

export function sortSemesterKeys(a: string, b: string): number {
  const la = a.toLowerCase()
  const lb = b.toLowerCase()
  const ia = SEM_SORT.indexOf(la)
  const ib = SEM_SORT.indexOf(lb)
  if (ia >= 0 && ib >= 0) return ia - ib
  if (ia >= 0) return -1
  if (ib >= 0) return 1
  return la.localeCompare(lb)
}

export function semesterHeaderLabel(key: string): string {
  const k = key.trim()
  if (!k) return '—'
  return k.charAt(0).toUpperCase() + k.slice(1).toLowerCase()
}

/** Rows for a school year (all rows if `year` empty). */
export function rowsForYear(rows: StudentScoreCardRow[], year: string | null): StudentScoreCardRow[] {
  const y = year?.trim() ?? ''
  if (!y) return rows
  return rows.filter((r) => String(r.school_year ?? '').trim() === y)
}

export function scoreForSemester(
  rows: StudentScoreCardRow[],
  year: string | null,
  semesterKey: string,
): string {
  const y = year?.trim() ?? ''
  const sk = semesterKey.toLowerCase()
  const row = rows.find((r) => {
    const ry = String(r.school_year ?? '').trim()
    const rs = String(r.semester ?? '').trim().toLowerCase()
    if (rs !== sk) return false
    if (!y) return true
    return ry === y
  })
  if (!row) return '—'
  return formatSemesterScore(row.semester_score ?? null)
}
