import type { ReactNode } from 'react';

export interface TableColumn<T> {
  key: string;
  header: string;
  render: (row: T) => ReactNode;
}

export interface TableProps<T> {
  /** Titre du tableau, lu par les lecteurs d'écran (élément caption). */
  caption: string;
  /** Nom de la zone défilable, par exemple « Tableau défilable : Notaires ». */
  scrollLabel: string;
  columns: readonly TableColumn<T>[];
  rows: readonly T[];
  rowKey: (row: T) => string;
}

export function Table<T>({ caption, scrollLabel, columns, rows, rowKey }: TableProps<T>) {
  return (
    // Zone défilable atteignable au clavier sur petit écran (WCAG 2.1.1, règle axe scrollable-region-focusable).
    // eslint-disable-next-line jsx-a11y-x/no-noninteractive-tabindex
    <div role="region" aria-label={scrollLabel} tabIndex={0} className="overflow-x-auto rounded-lg">
      <table className="w-full border-collapse text-left">
        <caption className="mb-2 text-left font-titre text-lg font-semibold text-titre">
          {caption}
        </caption>
        <thead>
          <tr className="border-b-2 border-accent">
            {columns.map((colonne) => (
              <th key={colonne.key} scope="col" className="px-3 py-2 font-semibold">
                {colonne.header}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((ligne) => (
            <tr key={rowKey(ligne)} className="border-b border-bordure">
              {columns.map((colonne) => (
                <td key={colonne.key} className="px-3 py-2 align-top">
                  {colonne.render(ligne)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
