import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useMemo } from 'react';
import { cn } from '../../scalars/lib/utils.js';
import { getColumnTitle } from '../table/utils.js';
import { HeaderNumberTd } from './header/header-number-td.js';
import { useInternalTableState } from './table-provider/table-provider.js';
const TableHeader = ({ columns }) => {
    const { config, state: { selectedRowIndexes }, api, } = useInternalTableState();
    const handleSelectAllRows = useCallback(() => {
        if (!config.allowRowSelection)
            return;
        api.selection.toggleSelectAll();
    }, [config.allowRowSelection, api.selection]);
    const isAllRowsSelected = selectedRowIndexes.length === api.getTotalRowsCount();
    const columnHeaders = useMemo(() => {
        return columns.map((column, columnIndex) => {
            const cellContext = {
                rowIndex: -1, // the header row has no row
                row: undefined,
                column,
                columnIndex,
                tableConfig: config,
            };
            const style = {
                width: column.width ?? 'auto',
                minWidth: column.minWidth ?? 'auto',
                maxWidth: column.maxWidth ?? column.width ?? 'auto',
            };
            const onSort = () => {
                if (!column.sortable)
                    return;
                const tableState = api._getState();
                if (tableState.sortState?.columnIndex === columnIndex) {
                    const nextDirection = tableState.sortState.direction === 'asc' ? 'desc' : null;
                    api.sortRows(columnIndex, nextDirection);
                }
                else {
                    api.sortRows(columnIndex, 'asc');
                }
            };
            return (_jsx("th", { className: cn('group/header-cell', column.sortable ? 'cursor-pointer' : ''), style: style, onClick: onSort, children: column.renderHeader(getColumnTitle(column), cellContext) }, column.field));
        });
    }, [api, columns, config]);
    return (_jsx("thead", { children: _jsxs("tr", { className: cn('border-gray-300', !selectedRowIndexes.includes(0) && 'border-b'), children: [_jsx(HeaderNumberTd, { isAllRowsSelected: isAllRowsSelected, handleSelectAllRows: handleSelectAllRows }), columnHeaders] }) }));
};
export { TableHeader };
//# sourceMappingURL=header.js.map