// packages/core/src/components/data-table/data-table-row.tsx
import type { JSX } from "solid-js";
import { For } from "solid-js";
import { useInternalDataTableContext } from "./data-table-context";
import { DataTableCell } from "./data-table-cell";

export interface DataTableRowProps {
  row: unknown;
  originalIndex: number;
}

/**
 * Renders a single `<tr>` for one data row.
 * When row selection is enabled, clicking the row toggles its selected state.
 * Each column's cell renderer is called to produce the `<td>` content.
 */
export function DataTableRow(props: DataTableRowProps): JSX.Element {
  const ctx = useInternalDataTableContext();

  const isSelected = () => ctx.selectedIndices().has(props.originalIndex);

  function handleClick(): void {
    if (ctx.enableRowSelection()) {
      ctx.toggleRowSelection(props.originalIndex);
    }
  }

  return (
    <tr
      aria-selected={ctx.enableRowSelection() ? isSelected() : undefined}
      data-selected={isSelected() ? "" : undefined}
      onClick={handleClick}
      style={{ cursor: ctx.enableRowSelection() ? "pointer" : undefined }}
    >
      <For each={ctx.columns()}>
        {(col, colIndex) => (
          <DataTableCell>
            {col.cell(props.row, colIndex())}
          </DataTableCell>
        )}
      </For>
    </tr>
  );
}
