/*
 * Copyright 2025 Palantir Technologies, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { useVirtualizer } from "@tanstack/react-virtual";
import React, { useLayoutEffect } from "react";
import { LoadingRow } from "./LoadingRow.js";
import { TableRow } from "./TableRow.js";
import { DEFAULT_ROW_HEIGHT, VIRTUALIZER_OVERSCAN } from "./utils/constants.js";
import styles from "./TableBody.module.css.js";
export function TableBody({
  rows,
  tableContainerRef,
  onRowClick,
  renderCellContextMenu,
  rowHeight = DEFAULT_ROW_HEIGHT,
  isLoadingMore = false,
  headerGroups = [],
  focusedRowId,
  setFocusedRowId,
  isInEditMode,
  getRowAttributes
}) {
  // Important: Keep the row virtualizer in the lowest component possible to avoid unnecessary re-renders.
  const rowVirtualizer = useVirtualizer({
    count: rows.length,
    estimateSize: () => rowHeight,
    getScrollElement: () => tableContainerRef.current,
    overscan: VIRTUALIZER_OVERSCAN
  });

  // Measure the virtualizer after the DOM has been laid out to ensure proper dimensions
  useLayoutEffect(() => {
    rowVirtualizer.measure();
  }, [rowVirtualizer, rows.length]);
  const totalSize = rowVirtualizer.getTotalSize();
  const bodyHeight = isLoadingMore ? totalSize + rowHeight : totalSize;
  const headers = headerGroups[0]?.headers ?? [];
  return /*#__PURE__*/React.createElement("tbody", {
    className: styles.osdkTableBody,
    style: {
      height: `${bodyHeight}px`
    }
  }, rowVirtualizer.getVirtualItems().map(virtualRow => {
    const row = rows[virtualRow.index];
    return /*#__PURE__*/React.createElement(TableRow, {
      key: row.id,
      row: row,
      virtualRow: virtualRow,
      onRowClick: onRowClick,
      renderCellContextMenu: renderCellContextMenu,
      isFocused: focusedRowId === row.id,
      setFocusedRowId: setFocusedRowId,
      isInEditMode: isInEditMode,
      getRowAttributes: getRowAttributes
    });
  }), isLoadingMore && /*#__PURE__*/React.createElement(LoadingRow, {
    headers: headers,
    translateY: totalSize,
    rowHeight: rowHeight,
    columnCount: headers.length
  }));
}
//# sourceMappingURL=TableBody.js.map