// Rendu commun des compteurs d'un job (progression comme rapport final). Purement
// présentationnel et sans dépendance à un module : le module appelant choisit les clés
// qu'il veut montrer et leur libellé, ce composant ne fait que les aligner.

export type JobCounter = { key: string; label: string; value: number | null };

/** Extrait les compteurs demandés d'un jsonb libre ; une clé absente rend `null`. */
export function pickCounters(
  source: Record<string, unknown> | null | undefined,
  fields: { key: string; label: string }[],
): JobCounter[] {
  return fields.map((field) => {
    const value = source?.[field.key];
    return {
      ...field,
      value: typeof value === "number" && Number.isFinite(value) ? value : null,
    };
  });
}

const numberFormat = new Intl.NumberFormat("fr-FR");

export function JobCounters({ counters }: { counters: JobCounter[] }) {
  const shown = counters.filter((counter) => counter.value !== null);
  if (shown.length === 0) return null;
  return (
    <dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-sm sm:grid-cols-3">
      {shown.map((counter) => (
        <div key={counter.key} className="flex flex-col">
          <dt className="text-muted-foreground text-xs">{counter.label}</dt>
          <dd className="font-medium tabular-nums">{numberFormat.format(counter.value ?? 0)}</dd>
        </div>
      ))}
    </dl>
  );
}
