// sMeterRST turns an S-meter reading into the RST report you SEND to the other
// station (RST tx / rst_sent) — because your S-meter is how strong THEY are.
//
//   s      : S-unit 0-9 (used when below S9)
//   overDb : dB over S9 (0 when at/below S9)
//   mode   : operating mode — CW/digital get a 3-digit RST, phone a 2-digit RS
//
// For S9+ the dB is rounded UP to the nearest 5 (a 9+3 reading reports 59+5,
// 9+12 reports 59+15, …), matching how operators give strong-signal reports.
export function sMeterRST(s: number, overDb: number, mode?: string): string {
  const cw = /CW|RTTY|PSK|FT[0-9]|JT|JS8|MFSK|OLIVIA|DATA|DIG/i.test(mode || '');
  const strength = Math.max(1, Math.min(9, Math.round(s)));
  if (cw) return overDb > 0 ? '599' : `5${strength}9`;
  if (overDb > 0) return `59+${Math.ceil(overDb / 5) * 5}`;
  return `5${strength}`;
}

// RST dropdown lists, shared by the entry form and the QSO editor so both offer
// the same per-mode choices (Settings → Modes → RST report lists).
export type RSTLists = { phone: string[]; cw: string[]; digital: string[] };

// rstCategory maps an ADIF mode to its RST family (phone / cw / digital).
export function rstCategory(mode: string): keyof RSTLists {
  const m = (mode || '').toUpperCase();
  const digital = ['FT8', 'FT4', 'JT65', 'JT9', 'JS8', 'Q65', 'MSK144', 'FST4', 'FST4W', 'MFSK', 'OLIVIA', 'JT4', 'WSPR'];
  if (digital.includes(m)) return 'digital';
  if (['CW', 'RTTY', 'PSK31', 'PSK63', 'PSK', 'PSK125'].includes(m)) return 'cw';
  return 'phone';
}

// rstOptions returns the valid report choices for a mode from the user's
// editable lists, with a tiny fallback before they load.
export function rstOptions(mode: string, lists: RSTLists): string[] {
  const cat = rstCategory(mode);
  const l = lists[cat];
  if (l && l.length) return l;
  return cat === 'phone' ? ['59', '58', '57'] : cat === 'cw' ? ['599', '589', '579'] : ['+00', '-10', '-20'];
}
