/**
 * Format an array of sets into a compact grouped summary.
 *
 * Consecutive sets with the same weight are collapsed:
 *   "135 x 5, 185 x 5, 205 x 5, 225 x 3, 245 x 3/3/3"
 *
 * When weightUnit is provided (per-set or as a default), it is appended:
 *   "16kg x 5/5/5" or "245 x 3/3/3" (lbs omitted since it's the common default)
 *
 * Sets without weight show just reps; sets without reps are skipped.
 */
export function formatSetsSummary(
  sets: Array<{ weight?: number | null; reps?: number | null; weightUnit?: string | null }>,
  defaultUnit?: string
): string {
  const valid = sets.filter((s) => s.reps);
  if (valid.length === 0) return "";

  // Group consecutive sets by weight
  const groups: Array<{ weight: number | null | undefined; weightUnit: string | null | undefined; reps: number[] }> =
    [];

  for (const s of valid) {
    const unit = s.weightUnit || defaultUnit || null;
    const last = groups[groups.length - 1];
    if (last && last.weight === s.weight && last.weightUnit === unit) {
      last.reps.push(s.reps!);
    } else {
      groups.push({ weight: s.weight, weightUnit: unit, reps: [s.reps!] });
    }
  }

  return groups
    .map((g) => {
      const repsStr = g.reps.join("/");
      if (g.weight) {
        const unit = g.weightUnit === "kg" ? "kg" : "";
        return `${g.weight}${unit} x ${repsStr}`;
      }
      return repsStr;
    })
    .join(", ");
}
