/**
 * SET 24b — shared metrics grid table, extracted from AdminView's InstallGrid
 * so the lifetime Admin grid and the per-run grid (App.tsx Tier1View) render
 * from one component. Columns are a subset of FacetCell keys with overridable
 * header labels (e.g. Admin uses "Latest", the run view uses "This run").
 */
import React from 'react';
import { formatCell, type FacetCell, type MetricsGridRow } from '../../src/tier1/statsAggregate';

export type MetricsGridColumn = keyof FacetCell;

const DEFAULT_LABELS: Record<MetricsGridColumn, string> = {
  latest: 'Latest',
  avg: 'Avg',
  min: 'Min',
  max: 'Max',
  lifetime: 'Lifetime',
};

function toneClass(tone: 'ok' | 'warn' | 'bad' | null | undefined): string {
  if (tone === 'ok') return 'ok';
  if (tone === 'warn') return 'warn';
  if (tone === 'bad') return 'bad';
  return '';
}

export function MetricsGridTable({
  rows,
  columns,
  labels,
}: {
  rows: MetricsGridRow[];
  columns: MetricsGridColumn[];
  /** Per-column header overrides (falls back to DEFAULT_LABELS). */
  labels?: Partial<Record<MetricsGridColumn, string>>;
}) {
  const colCount = columns.length + 1;
  return (
    <div className="admin-grid-wrap">
      <table className="authtable admin-grid">
        <thead>
          <tr>
            <th>Facet</th>
            {columns.map(c => <th key={c}>{labels?.[c] ?? DEFAULT_LABELS[c]}</th>)}
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => {
            if (row.kind === 'header') {
              return (
                <tr key={`h-${row.category}`} className="admin-cat">
                  <td colSpan={colCount}><b>{row.category}</b></td>
                </tr>
              );
            }
            const tc = toneClass(row.tone);
            return (
              <tr key={row.key}>
                <td>{row.label}</td>
                {columns.map(c => (
                  <td key={c} className={tc || undefined}>{formatCell(row.cells[c], row.format)}</td>
                ))}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
