/**
 * DataTable — a read-only, scrollable table of rows, the shared shape behind the
 * data inspector (input/resolved rows) and the Chart Builder's source-row preview.
 *
 * Columns and any per-column header adornment are the caller's: the builder passes
 * its declared column list with a type chip in each header; the inspector passes the
 * row keys with plain names. This owns the table structure, the "first N of M" note,
 * and the styling, so the two surfaces never drift. Capping is the caller's policy —
 * it passes the rows to show plus the true `total`.
 */

import type { ReactNode } from 'react';
import { cellText } from '@core/dataset';
import styles from './DataTable.module.css';

interface DataTableProps {
  /** Column names, in display order. Cells read each row by these keys. */
  columns: readonly string[];
  /** The rows to render — already limited to what should be shown. */
  rows: readonly Record<string, unknown>[];
  /** The true row count; when it exceeds `rows`, a "first N of M" note is shown. */
  total?: number;
  /** Custom header content per column (e.g. a type chip); defaults to the name. */
  renderHeader?: (column: string) => ReactNode;
  /** Accessible name for the scroll region. */
  ariaLabel: string;
  /** Fill the available height instead of the default capped height (resizable panes). */
  fill?: boolean;
}

export function DataTable({ columns, rows, total, renderHeader, ariaLabel, fill }: DataTableProps) {
  return (
    <>
      <div
        className={`${styles.wrap} ${fill ? styles.wrapFill : ''}`}
        tabIndex={0}
        role="group"
        aria-label={ariaLabel}
      >
        <table className={styles.table}>
          <thead>
            <tr>
              {columns.map((col) => (
                <th key={col} scope="col">
                  {renderHeader ? renderHeader(col) : col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((row, ri) => (
              <tr key={ri}>
                {columns.map((col) => (
                  <td key={col}>{cellText(row[col])}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {total != null && total > rows.length && (
        <p className={styles.note}>
          Showing the first {rows.length} of {total.toLocaleString()} rows.
        </p>
      )}
    </>
  );
}
