import { cn } from "@/lib/utils";

export interface TableColumn<T> {
  key: keyof T;
  header: string;
  align?: "left" | "right" | "center";
  render?: (row: T) => React.ReactNode;
}

export interface TableProps<T extends { id: string | number }> {
  columns: TableColumn<T>[];
  rows: T[];
  caption?: string;
}

/** Wide-content tables always scroll within their own container — the page body never scrolls horizontally. */
export function Table<T extends { id: string | number }>({ columns, rows, caption }: TableProps<T>) {
  return (
    <div className="overflow-x-auto rounded border border-line">
      <table className="w-full min-w-[560px] border-collapse text-left">
        {caption && <caption className="sr-only">{caption}</caption>}
        <thead>
          <tr className="border-b border-line bg-tag-bg/50">
            {columns.map((col) => (
              <th
                key={String(col.key)}
                scope="col"
                className={cn(
                  "px-4 py-3 font-mono text-[11px] uppercase tracking-wider text-slate",
                  col.align === "right" && "text-right",
                  col.align === "center" && "text-center"
                )}
              >
                {col.header}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => (
            <tr key={row.id} className="border-b border-line last:border-0 hover:bg-tag-bg/30">
              {columns.map((col) => (
                <td
                  key={String(col.key)}
                  className={cn(
                    "px-4 py-3.5 text-body-sm text-ink-soft [font-variant-numeric:tabular-nums]",
                    col.align === "right" && "text-right",
                    col.align === "center" && "text-center"
                  )}
                >
                  {col.render ? col.render(row) : String(row[col.key] ?? "")}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
