/** Ports CI `whatsapp_invite.php` section-name helpers */

export function formatSectionName(section: string): string {
  const raw = section.trim()
  if (raw === '') return 'Class'

  if (/^\s*grade\s+/i.test(raw)) {
    return 'Grade ' + raw.replace(/^\s*grade\s+/i, '').trim()
  }

  const up = raw.toUpperCase()
  if (up === 'KG') return 'KG'
  if (up === 'YOUTH') return 'Youth'

  const m = raw.match(/^\s*(\d{1,2})(?:\s*-\s*([A-Za-z]))?\s*$/)
  if (m) {
    const grade = Number(m[1])
    const sec = m[2] ? String(m[2]).toUpperCase() : ''
    return 'Grade ' + grade + (sec ? '-' + sec : '')
  }

  return 'Grade ' + raw.charAt(0).toUpperCase() + raw.slice(1)
}

export function joinWithAnd(items: Array<string | null | undefined>): string {
  const arr = items.filter((v): v is string => Boolean(v && String(v).trim()))
  const n = arr.length
  if (n === 0) return ''
  if (n === 1) return arr[0]!
  if (n === 2) return `${arr[0]} and ${arr[1]}`
  return `${arr.slice(0, -1).join(', ')} and ${arr[n - 1]}`
}
