'use strict';

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var debounce = require('../../../node_modules/lodash-es/debounce.js');
var isEqual = require('../../../node_modules/lodash-es/isEqual.js');
var isEmpty = require('../../../node_modules/lodash-es/isEmpty.js');
var isNil = require('../../../node_modules/lodash-es/isNil.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.find-index.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.array.slice.js');
require('core-js/modules/es.array.sort.js');
require('core-js/modules/es.function.name.js');
require('core-js/modules/es.object.entries.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.string.includes.js');
require('core-js/modules/web.dom-collections.for-each.js');
var React = require('react');
var PropTypes = require('prop-types');
var react = require('@carbon/react');
var classnames = require('classnames');
var warning = require('warning');
var useLangDirection = require('../../../utils/useLangDirection.js');
var TablePropTypes = require('../TablePropTypes.js');
var TableCellRenderer = require('../TableCellRenderer/TableCellRenderer.js');
var componentUtilityFunctions = require('../../../utils/componentUtilityFunctions.js');
var Settings = require('../../../constants/Settings.js');
var SharedPropTypes = require('../../../constants/SharedPropTypes.js');
var index = require('../../OverflowMenu/index.js');
var usePrevious = require('../../../hooks/usePrevious.js');
var deprecate = require('../../../internal/deprecate.js');
var tableUtilities = require('../tableUtilities.js');
var ColumnHeaderRow = require('./ColumnHeaderRow/ColumnHeaderRow.js');
var FilterHeaderRow = require('./FilterHeaderRow/FilterHeaderRow.js');
var TableHeader = require('./TableHeader.js');
var ColumnResize = require('./ColumnResize.js');
var columnWidthUtilityFunctions = require('./columnWidthUtilityFunctions.js');
var ColumnGrouping = require('./ColumnGrouping/ColumnGrouping.js');
var iconsReact = require('@carbon/icons-react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);
var warning__default = /*#__PURE__*/_interopDefault(warning);

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var iotPrefix = Settings.settings.iotPrefix;
var propTypes = {
  tableId: PropTypes__default.default.string.isRequired,
  /** Important table options that the head needs to know about */
  options: PropTypes__default.default.shape({
    hasRowExpansion: PropTypes__default.default.bool,
    hasRowSelection: PropTypes__default.default.oneOf(['multi', 'single', false]),
    useRadioButtonSingleSelect: PropTypes__default.default.bool,
    hasRowActions: PropTypes__default.default.bool,
    hasResize: PropTypes__default.default.bool,
    hasSingleRowEdit: PropTypes__default.default.bool,
    hasRowNesting: PropTypes__default.default.oneOfType([PropTypes__default.default.bool, PropTypes__default.default.shape({
      /** If the hierarchy only has 1 nested level of children */
      hasSingleNestedHierarchy: PropTypes__default.default.bool
    })]),
    wrapCellText: SharedPropTypes.WrapCellTextPropTypes.isRequired,
    truncateCellText: PropTypes__default.default.bool.isRequired,
    hasMultiSort: PropTypes__default.default.bool,
    useAutoTableLayoutForResize: PropTypes__default.default.bool,
    /** Preserves the widths of existing columns when one or more columns are added, removed, hidden, shown or resized. */
    preserveColumnWidths: PropTypes__default.default.bool,
    hasFilterRowIcon: PropTypes__default.default.bool,
    hasDragAndDrop: PropTypes__default.default.bool,
    /** Freezes table header and footer */
    pinHeaderAndFooter: PropTypes__default.default.bool,
    /** column to pin in the table */
    pinColumn: TablePropTypes.PinColumnPropTypes
  }),
  /** List of columns */
  columns: TablePropTypes.TableColumnsPropTypes.isRequired,
  enablePercentageColumnWidth: PropTypes__default.default.bool,
  /** Specify the properties of each column group in the table. Defaults to empty column. */
  columnGroups: TablePropTypes.TableColumnGroupPropType,
  /** internationalized labels */
  selectAllText: PropTypes__default.default.string,
  clearFilterText: PropTypes__default.default.string,
  filterText: PropTypes__default.default.string,
  clearSelectionText: PropTypes__default.default.string,
  openMenuText: PropTypes__default.default.string,
  closeMenuText: PropTypes__default.default.string,
  /** Current state of the table */
  tableState: PropTypes__default.default.shape({
    /** is the tableHead currently disabled */
    isDisabled: PropTypes__default.default.bool,
    /** Which toolbar is currently active */
    activeBar: TablePropTypes.ActiveTableToolbarPropType,
    /** What's currently selected in the table? */
    selection: PropTypes__default.default.shape({
      isSelectAllIndeterminate: PropTypes__default.default.bool,
      isSelectAllSelected: PropTypes__default.default.bool
    }).isRequired,
    /** What sorting is currently applied */
    sort: PropTypes__default.default.oneOfType([TablePropTypes.TableSortPropType, PropTypes__default.default.arrayOf(TablePropTypes.TableSortPropType)]).isRequired,
    /** Specify the order, visibility and group belonging of the table columns */
    ordering: TablePropTypes.TableOrderingPropType.isRequired,
    /** Optional list of applied column filters */
    filters: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
      columnId: PropTypes__default.default.string.isRequired,
      value: PropTypes__default.default.oneOfType([PropTypes__default.default.string, PropTypes__default.default.number, PropTypes__default.default.bool, PropTypes__default.default.arrayOf(PropTypes__default.default.string)]).isRequired
    }))
  }).isRequired,
  actions: PropTypes__default.default.shape({
    onSelectAll: PropTypes__default.default.func,
    onChangeSort: PropTypes__default.default.func,
    onChangeOrdering: PropTypes__default.default.func,
    onColumnSelectionConfig: PropTypes__default.default.func,
    onApplyFilter: PropTypes__default.default.func,
    onColumnResize: PropTypes__default.default.func,
    onOverflowItemClicked: PropTypes__default.default.func,
    onFilterRowIconClick: PropTypes__default.default.func
  }).isRequired,
  /** lightweight  */
  lightweight: PropTypes__default.default.bool,
  i18n: TablePropTypes.I18NPropTypes,
  /** should we filter on each keypress */
  hasFastFilter: PropTypes__default.default.bool,
  // TODO: remove deprecated 'testID' in v3
  // eslint-disable-next-line react/require-default-props
  testID: deprecate(PropTypes__default.default.string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
  testId: PropTypes__default.default.string,
  /** shows an additional column that can expand/shrink as the table is resized  */
  showExpanderColumn: PropTypes__default.default.bool,
  /** Size prop from Carbon to shrink row height (and header height in some instances) */
  size: function checkProps(props, propName, componentName) {
    if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {
      warning__default.default(false, "The value `".concat(props[propName], "` has been deprecated for the ") + "`".concat(propName, "` prop on the ").concat(componentName, " component. It will be removed in the next major ") + "release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.") ;
    }
  },
  filterRowIcon: PropTypes__default.default.oneOfType([PropTypes__default.default.func, PropTypes__default.default.object]),
  filterRowIconDescription: PropTypes__default.default.string
};
var defaultProps = {
  columnGroups: [],
  options: {},
  lightweight: false,
  selectAllText: 'Select all',
  clearFilterText: 'Clear filter',
  filterText: 'Filter',
  clearSelectionText: 'Clear selection',
  openMenuText: 'Open menu',
  closeMenuText: 'Close menu',
  i18n: _objectSpread({}, TablePropTypes.defaultI18NPropTypes),
  hasFastFilter: true,
  enablePercentageColumnWidth: false,
  testId: '',
  showExpanderColumn: false,
  size: undefined,
  filterRowIcon: iconsReact.FilterEdit,
  filterRowIconDescription: 'Edit filters'
};
var generateOrderedColumnRefs = function generateOrderedColumnRefs(ordering) {
  return ordering.map(function (col) {
    return col.columnId;
  }).reduce(function (acc, id) {
    return _objectSpread(_objectSpread({}, acc), {}, _defineProperty__default.default({}, id, /*#__PURE__*/React.createRef()));
  }, {});
};

// This increases the min width of columns when the overflow button and sort is present
var PADDING_WITH_OVERFLOW = 24;
var PADDING_WITH_OVERFLOW_AND_SORT = 58;
var TableHead = function TableHead(_ref) {
  var testID = _ref.testID,
    testId = _ref.testId,
    tableId = _ref.tableId,
    options = _ref.options,
    _ref$options = _ref.options,
    hasRowExpansion = _ref$options.hasRowExpansion,
    hasRowSelection = _ref$options.hasRowSelection,
    hasRowNesting = _ref$options.hasRowNesting,
    hasResize = _ref$options.hasResize,
    wrapCellText = _ref$options.wrapCellText,
    truncateCellText = _ref$options.truncateCellText,
    hasSingleRowEdit = _ref$options.hasSingleRowEdit,
    hasMultiSort = _ref$options.hasMultiSort,
    useAutoTableLayoutForResize = _ref$options.useAutoTableLayoutForResize,
    preserveColumnWidths = _ref$options.preserveColumnWidths,
    useRadioButtonSingleSelect = _ref$options.useRadioButtonSingleSelect,
    hasDragAndDrop = _ref$options.hasDragAndDrop,
    pinHeaderAndFooter = _ref$options.pinHeaderAndFooter,
    pinColumn = _ref$options.pinColumn,
    columns = _ref.columns,
    columnGroups = _ref.columnGroups,
    _ref$tableState = _ref.tableState,
    _ref$tableState$selec = _ref$tableState.selection,
    isSelectAllIndeterminate = _ref$tableState$selec.isSelectAllIndeterminate,
    isSelectAllSelected = _ref$tableState$selec.isSelectAllSelected,
    sort = _ref$tableState.sort,
    activeBar = _ref$tableState.activeBar,
    ordering = _ref$tableState.ordering,
    filters = _ref$tableState.filters,
    isDisabled = _ref$tableState.isDisabled,
    _ref$actions = _ref.actions,
    onSelectAll = _ref$actions.onSelectAll,
    onChangeSort = _ref$actions.onChangeSort,
    onApplyFilter = _ref$actions.onApplyFilter,
    onChangeOrdering = _ref$actions.onChangeOrdering,
    onColumnSelectionConfig = _ref$actions.onColumnSelectionConfig,
    onColumnResize = _ref$actions.onColumnResize,
    onOverflowItemClicked = _ref$actions.onOverflowItemClicked,
    onFilterRowIconClick = _ref$actions.onFilterRowIconClick,
    selectAllText = _ref.selectAllText,
    clearFilterText = _ref.clearFilterText,
    filterText = _ref.filterText,
    clearSelectionText = _ref.clearSelectionText,
    openMenuText = _ref.openMenuText,
    closeMenuText = _ref.closeMenuText,
    lightweight = _ref.lightweight,
    i18n = _ref.i18n,
    hasFastFilter = _ref.hasFastFilter,
    showExpanderColumn = _ref.showExpanderColumn,
    size = _ref.size,
    enablePercentageColumnWidth = _ref.enablePercentageColumnWidth,
    filterRowIcon = _ref.filterRowIcon,
    filterRowIconDescription = _ref.filterRowIconDescription;
  var filterBarActive = activeBar === 'filter';
  var initialColumnWidths = {};
  var columnRef = generateOrderedColumnRefs(ordering);
  var columnResizeRefs = generateOrderedColumnRefs(ordering);
  var _useState = React.useState({}),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    currentColumnWidths = _useState2[0],
    setCurrentColumnWidths = _useState2[1];
  var _useState3 = React.useState(enablePercentageColumnWidth),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    percentageMode = _useState4[0],
    setPercentageMode = _useState4[1];
  if (isEmpty(currentColumnWidths)) {
    columns.forEach(function (col) {
      initialColumnWidths[col.id] = col.width;
    });
  }
  var forwardMouseEvent = function forwardMouseEvent(e) {
    Object.entries(columnResizeRefs).forEach(function (_ref2) {
      var _ref3 = _slicedToArray__default.default(_ref2, 2),
        ref = _ref3[1];
      if (ref.current) {
        ref.current.forwardMouseEvent(e);
      }
    });
  };
  var measureColumnWidths = React.useCallback(function () {
    return ordering.filter(function (col) {
      return !col.isHidden;
    }).map(function (col) {
      var ref = columnRef[col.columnId];
      return {
        id: col.columnId,
        width: ref.current && ref.current.getBoundingClientRect().width
      };
    });
  }, [ordering, columnRef]);
  var updateColumnWidths = function updateColumnWidths(newColumnWidths) {
    var updatedColumns = columns.map(function (col) {
      return _objectSpread(_objectSpread({}, col), {}, {
        width: newColumnWidths[col.id].width !== undefined ? "".concat(newColumnWidths[col.id].width, "px") : col.width
      });
    });
    setCurrentColumnWidths(newColumnWidths);
    if (onColumnResize) {
      onColumnResize(updatedColumns);
    }
  };
  var onManualColumnResize = function onManualColumnResize(modifiedColumnWidths) {
    if (percentageMode) {
      var modifiedColumns = _toConsumableArray__default.default(columns);
      Object.keys(modifiedColumns).forEach(function (key) {
        if (modifiedColumns[key].hasOwnProperty('width')) {
          delete modifiedColumns[key].width;
        }
      });

      // while Resizing setting all column width to default DEFAULT_COLUMN_WIDTH 150px
      var columnPropInlcudingWidths = columnWidthUtilityFunctions.addMissingColumnWidths({
        ordering: ordering,
        columns: modifiedColumns,
        currentColumnWidths: {}
      });
      var newColumnWidths = columnWidthUtilityFunctions.createNewWidthsMap(ordering, columnPropInlcudingWidths);
      setCurrentColumnWidths(newColumnWidths);
      setPercentageMode(false);
    } else {
      var _newColumnWidths = columnWidthUtilityFunctions.createNewWidthsMap(ordering, currentColumnWidths, modifiedColumnWidths);
      updateColumnWidths(_newColumnWidths);
    }
  };
  var onColumnToggle = function onColumnToggle(columnId, newOrdering) {
    if (hasResize) {
      if (preserveColumnWidths) {
        var isToggleShow = columnWidthUtilityFunctions.isColumnVisible(newOrdering, columnId);
        var columnHasNoWidth = columnWidthUtilityFunctions.getOriginalWidthOfColumn(columns, columnId) === undefined;
        if (isToggleShow && columnHasNoWidth) {
          var newColumnWidths = columnWidthUtilityFunctions.createNewWidthsMap(newOrdering, currentColumnWidths, [{
            id: columnId,
            width: columnWidthUtilityFunctions.DEFAULT_COLUMN_WIDTH
          }]);
          updateColumnWidths(newColumnWidths);
        }
      } else {
        var _newColumnWidths2 = columnWidthUtilityFunctions.calculateWidthsOnToggle({
          currentColumnWidths: currentColumnWidths,
          newOrdering: newOrdering,
          columnId: columnId,
          columns: columns
        });
        updateColumnWidths(_newColumnWidths2);
      }
    }
    onChangeOrdering(newOrdering);
  };
  var handleOverflowItemClick = function handleOverflowItemClick(e, option) {
    e.stopPropagation();
    if (onOverflowItemClicked) {
      onOverflowItemClicked(option.id, option.meta);
    }
  };
  React.useLayoutEffect(function () {
    var measureAndAdjustColumns = function measureAndAdjustColumns() {
      if (hasResize && columns.length) {
        var measuredWidths = measureColumnWidths();
        var adjustedWidths = columnWidthUtilityFunctions.adjustInitialColumnWidths(ordering, columns, measuredWidths);
        var newWidthsMap = columnWidthUtilityFunctions.createNewWidthsMap(ordering, currentColumnWidths, adjustedWidths);
        setCurrentColumnWidths(newWidthsMap);
      }
    };

    // An initial measuring is needed since there might not be an initial value from the columns prop
    // which means that the layout engine will have to set the widths dynamically
    // before we know what they are.
    if (isEmpty(currentColumnWidths)) {
      measureAndAdjustColumns();
    }

    // For non fixed tables with resizable columns we need to recalculate the
    // column widths after window resize.
    var handleWindowResize = debounce(function () {
      if (useAutoTableLayoutForResize) {
        measureAndAdjustColumns();
      }
    }, 100);
    window.addEventListener('resize', handleWindowResize);
    return function () {
      return window.removeEventListener('resize', handleWindowResize);
    };
  }, [hasResize, columns, ordering, currentColumnWidths, measureColumnWidths, useAutoTableLayoutForResize]);

  // Handle external modification of columns prop and ordering prop
  var previousColumns = usePrevious.usePrevious(columns);
  var previousOrdering = usePrevious.usePrevious(ordering);
  React.useEffect(function () {
    // We need to update the currentColumnWidths (state) after the initial render
    // if the widths of the column prop are externally updated or if columns are added/removed.
    var externallyModified = !isEqual(columns, previousColumns) || !isEqual(ordering, previousOrdering);
    if (hasResize && columns.length && !isEmpty(currentColumnWidths) && externallyModified && !percentageMode) {
      /* eslint-disable no-param-reassign */
      Object.keys(columns).forEach(function (key) {
        if (columns[key].width && columns[key].width.includes('%')) {
          delete columns[key].width;
        }
      });
      columnWidthUtilityFunctions.checkColumnWidthFormat(columns);

      // PRESERVE WIDTHS
      // Preserve column when possible widths when columns are externally modified
      if (preserveColumnWidths) {
        var columnPropInlcudingWidths = columnWidthUtilityFunctions.addMissingColumnWidths({
          ordering: ordering,
          columns: columns,
          currentColumnWidths: currentColumnWidths
        });
        var newColumnWidths = columnWidthUtilityFunctions.createNewWidthsMap(ordering, columnPropInlcudingWidths);
        if (!isEqual(currentColumnWidths, newColumnWidths)) {
          setCurrentColumnWidths(newColumnWidths);
          // Notify the application if any columns were assigned the rendered or default widths
          if (!isEqual(columnPropInlcudingWidths, columns)) {
            onColumnResize(columnPropInlcudingWidths);
          }
        }
        return;
      }

      // MODIFY WIDTHS
      // Modify existing columns widths when columns are externally modified
      var removedColumnIDs = columnWidthUtilityFunctions.getIDsOfRemovedColumns(ordering, currentColumnWidths);
      var addedVisibleColumnIDs = columnWidthUtilityFunctions.getIDsOfAddedVisibleColumns(ordering, currentColumnWidths);
      var adjustedForRemoved = removedColumnIDs.length > 0 ? columnWidthUtilityFunctions.calculateWidthOnHide(currentColumnWidths, ordering, removedColumnIDs) : currentColumnWidths;
      var adjustedForRemovedAndAdded = addedVisibleColumnIDs.length > 0 ? columnWidthUtilityFunctions.calculateWidthOnShow(adjustedForRemoved, ordering, addedVisibleColumnIDs, columns) : adjustedForRemoved;
      if (addedVisibleColumnIDs.length > 0 || removedColumnIDs.length > 0) {
        setCurrentColumnWidths(adjustedForRemovedAndAdded);
      } else if (columnWidthUtilityFunctions.hasVisibleColumns(ordering) && columnWidthUtilityFunctions.visibleColumnsHaveWidth(ordering, columns)) {
        var propsColumnWidths = columnWidthUtilityFunctions.createNewWidthsMap(ordering, columns);
        if (!isEqual(currentColumnWidths, propsColumnWidths)) {
          setCurrentColumnWidths(propsColumnWidths);
        }
      }
    }
  },
  // We explicitly do NOT want to trigger this effect if currentColumnWidths is modified
  // since it would be directly overridden by the column props. This effect can be removed
  // with issue https://github.com/IBM/carbon-addons-iot-react/issues/1224
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [hasResize, columns, ordering, previousColumns, percentageMode]);
  React.useEffect(function () {
    var tableWidth;
    var columnWidth;
    var filteredColumns = columns.filter(function (colOrder) {
      var hiddenCol = ordering.find(function (col) {
        return col.columnId === colOrder.id;
      });
      return !hiddenCol || !hiddenCol.isHidden;
    });
    var hasOverflowMenu = filteredColumns.some(function (column) {
      return column.overflowMenuItems && column.overflowMenuItems.length > 0;
    });
    var totalColumns = filteredColumns.length;
    if (enablePercentageColumnWidth && filteredColumns.length && percentageMode && !hasOverflowMenu) {
      /* istanbul ignore next */
      if ((hasRowSelection === 'multi' || useRadioButtonSingleSelect && hasRowSelection === 'single') && !(hasRowExpansion || hasRowNesting)) {
        tableWidth = "calc(100% - 54px)";
        columnWidth = "calc(".concat(tableWidth, " / ").concat(totalColumns, ")");
      } else if ((hasRowExpansion || hasRowNesting) && !(hasRowSelection === 'multi' || useRadioButtonSingleSelect && hasRowSelection === 'single')) {
        tableWidth = "calc(100% - 40px)";
        columnWidth = "calc(".concat(tableWidth, " / ").concat(totalColumns, ")");
      } else if ((hasRowExpansion || hasRowNesting) && (hasRowSelection === 'multi' || useRadioButtonSingleSelect && hasRowSelection === 'single')) {
        tableWidth = "calc(100% - 94px)";
        columnWidth = "calc(".concat(tableWidth, " / ").concat(totalColumns, ")");
      } else {
        columnWidth = "".concat(parseInt(100 / filteredColumns.length, 10), "%");
      }
      var updatedColumns = filteredColumns.map(function (col) {
        var updatedCol = _objectSpread({}, col);
        updatedCol.width = columnWidth;
        return updatedCol;
      });
      var columnPropIncludingWidths = columnWidthUtilityFunctions.addMissingColumnWidths({
        ordering: ordering,
        columns: updatedColumns,
        currentColumnWidths: currentColumnWidths
      });
      var newColumnWidths = columnWidthUtilityFunctions.createNewWidthsMap(ordering, columnPropIncludingWidths);
      if (!isEqual(currentColumnWidths, newColumnWidths)) {
        setCurrentColumnWidths(newColumnWidths);
      }
    }
  }, [columns, ordering, hasRowExpansion, hasRowNesting, hasRowSelection, useRadioButtonSingleSelect, currentColumnWidths, enablePercentageColumnWidth, percentageMode]);
  var visibleColumns = ordering.filter(function (col) {
    return !col.isHidden;
  });
  var lastVisibleColumn = visibleColumns.slice(-1)[0];
  var firstVisibleColumn = visibleColumns[0];
  var showColumnGroups = columnGroups.some(function (_ref4) {
    var id = _ref4.id;
    return visibleColumns.find(function (_ref5) {
      var columnGroupId = _ref5.columnGroupId;
      return id === columnGroupId;
    });
  });
  var langDir = useLangDirection.useLangDirection();
  return /*#__PURE__*/React__default.default.createElement(react.TableHead, {
    className: classnames__default.default(_defineProperty__default.default({
      lightweight: lightweight
    }, "".concat(iotPrefix, "--table-head--with-column-groups"), showColumnGroups), tableUtilities.pinColumnClassNames({
      pinColumn: pinColumn,
      hasRowSelection: hasRowSelection,
      hasRowExpansion: hasRowExpansion,
      hasRowNesting: hasRowNesting
    })),
    onMouseMove: hasResize ? forwardMouseEvent : null,
    onMouseUp: hasResize ? forwardMouseEvent : null
    // TODO: remove deprecated 'testID' in v3
    ,
    "data-testid": testID || testId
  }, /*#__PURE__*/React__default.default.createElement(react.TableRow, {
    className: classnames__default.default(_defineProperty__default.default(_defineProperty__default.default({}, "".concat(iotPrefix, "--table-header__column-row"), showColumnGroups), "".concat(iotPrefix, "--table-header__column-row--prevent-small-sizes"), showColumnGroups))
  }, hasDragAndDrop && /*#__PURE__*/React__default.default.createElement(TableHeader.default, {
    width: "2rem",
    initialWidth: "2rem"
  }), hasRowExpansion || hasRowNesting ? /*#__PURE__*/React__default.default.createElement(react.TableExpandHeader, {
    id: "".concat(tableId, "-expand")
    // TODO: remove deprecated 'testID' in v3
    ,
    "data-testid": "".concat(testID || testId, "-row-expansion-column"),
    className: classnames__default.default(_defineProperty__default.default({}, "".concat(iotPrefix, "--table-expand-resize"), hasResize))
  }) : null, hasRowSelection === 'multi' ? /*#__PURE__*/React__default.default.createElement(TableHeader.default
  // TODO: remove deprecated 'testID' in v3
  , {
    testId: "".concat(testID || testId, "-row-selection-column"),
    className: classnames__default.default("".concat(iotPrefix, "--table-header-checkbox"), _defineProperty__default.default({}, "".concat(iotPrefix, "--table-header-checkbox-resize"), hasResize)),
    translateWithId: function translateWithId() {
      return componentUtilityFunctions.tableTranslateWithId.apply(void 0, arguments);
    }
  }, /*#__PURE__*/React__default.default.createElement(react.Checkbox, {
    disabled: isDisabled,
    id: "".concat(tableId, "-head"),
    labelText: selectAllText,
    hideLabel: true,
    indeterminate: isSelectAllIndeterminate,
    checked: isSelectAllSelected,
    onChange: function onChange() {
      return onSelectAll(!isSelectAllSelected);
    }
  })) : hasRowSelection === 'single' && useRadioButtonSingleSelect ? /*#__PURE__*/React__default.default.createElement(TableHeader.default
  // TODO: remove deprecated 'testID' in v3
  , {
    testId: "".concat(testID || testId, "-row-selection-column"),
    className: classnames__default.default("".concat(iotPrefix, "--table-header-radiobutton"), _defineProperty__default.default({}, "".concat(iotPrefix, "--table-header-radiobutton-resize"), hasResize)),
    translateWithId: function translateWithId() {
      return componentUtilityFunctions.tableTranslateWithId.apply(void 0, arguments);
    }
  }) : null, ordering.map(function (item, columnIndex) {
    var _currentColumnWidths$;
    var matchingColumnMeta = columns.find(function (column) {
      return column.id === item.columnId;
    });
    var hasSingleSort = matchingColumnMeta && sort && sort.columnId === matchingColumnMeta.id;
    var multiSortColumn = hasMultiSort && matchingColumnMeta && Array.isArray(sort) && sort.find(function (c) {
      return c.columnId === matchingColumnMeta.id;
    });
    var hasSort = hasSingleSort || hasMultiSort;
    var sortOrder = hasMultiSort && Array.isArray(sort) ? sort.findIndex(function (c) {
      return c.columnId === matchingColumnMeta.id;
    }) + 1 : -1;
    var sortDirection = hasSingleSort ? sort.direction : hasMultiSort && multiSortColumn !== null && multiSortColumn !== void 0 && multiSortColumn.direction ? multiSortColumn.direction : 'NONE';
    var align = matchingColumnMeta && matchingColumnMeta.align ? matchingColumnMeta.align : 'start';
    var hasOverflow = Array.isArray(matchingColumnMeta === null || matchingColumnMeta === void 0 ? void 0 : matchingColumnMeta.overflowMenuItems);

    // Increases the minimum width of the Header when the overflow button is present
    var paddingExtra = hasOverflow ? matchingColumnMeta.isSortable ? PADDING_WITH_OVERFLOW_AND_SORT : PADDING_WITH_OVERFLOW : 0;
    var columnBelongsToExistingGroup = columnGroups.some(function (_ref6) {
      var id = _ref6.id;
      return id === item.columnGroupId;
    });
    var rightmostColumn = langDir === 'ltr' ? lastVisibleColumn : visibleColumns[0];
    var flipTooltipDirection = rightmostColumn === item;
    var flipFirstColumnTooltipDirection = firstVisibleColumn === item;
    return !item.isHidden && matchingColumnMeta ? /*#__PURE__*/React__default.default.createElement(TableHeader.default
    // TODO: remove deprecated 'testID' in v3
    , {
      spanGroupRow: showColumnGroups && !columnBelongsToExistingGroup,
      testId: "".concat(testID || testId, "-column-").concat(matchingColumnMeta.id),
      width: initialColumnWidths[matchingColumnMeta.id],
      initialWidth: initialColumnWidths[matchingColumnMeta.id],
      id: "column-".concat(matchingColumnMeta.id),
      key: "column-".concat(matchingColumnMeta.id),
      "data-column": matchingColumnMeta.id,
      isSortable: matchingColumnMeta.isSortable && !isDisabled,
      isSortHeader: hasSort,
      hasTooltip: !!matchingColumnMeta.tooltip,
      ref: columnRef[matchingColumnMeta.id],
      hasMultiSort: hasMultiSort,
      hasOverflow: hasOverflow,
      thStyle: {
        width: (_currentColumnWidths$ = currentColumnWidths[matchingColumnMeta.id]) === null || _currentColumnWidths$ === void 0 ? void 0 : _currentColumnWidths$.width
      },
      onClick: function onClick() {
        if (matchingColumnMeta.isSortable && onChangeSort) {
          onChangeSort(matchingColumnMeta.id);
        }
      },
      translateWithId: function translateWithId() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        return componentUtilityFunctions.tableTranslateWithId.apply(void 0, [i18n].concat(args));
      },
      sortDirection: sortDirection,
      align: align,
      decorator: matchingColumnMeta === null || matchingColumnMeta === void 0 ? void 0 : matchingColumnMeta.decorator,
      className: classnames__default.default("table-header-label-".concat(align), _defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default({}, "".concat(iotPrefix, "--table-head--table-header"), initialColumnWidths !== undefined), 'table-header-sortable', matchingColumnMeta.isSortable && !isDisabled), "".concat(iotPrefix, "--table-header-resize"), hasResize), "".concat(iotPrefix, "--table-head--table-header--with-overflow"), hasOverflow || hasMultiSort && matchingColumnMeta.isSortable && !isDisabled), "".concat(iotPrefix, "--table-header--last-data-column"), showColumnGroups && item === lastVisibleColumn))
      // data-floating-menu-container is a work around for this carbon issue: https://github.com/carbon-design-system/carbon/issues/4755
      ,
      "data-floating-menu-container": true
    }, /*#__PURE__*/React__default.default.createElement(TableCellRenderer, {
      className: "".concat(iotPrefix, "--table-head--text"),
      wrapText: wrapCellText,
      truncateCellText: truncateCellText,
      allowTooltip: false,
      tooltip: matchingColumnMeta.tooltip,
      tooltipDirection: flipTooltipDirection ? 'bottom-end' : flipFirstColumnTooltipDirection ? 'bottom-start' : undefined
    }, matchingColumnMeta.name), hasOverflow || hasMultiSort && matchingColumnMeta.isSortable && !isDisabled ? /*#__PURE__*/React__default.default.createElement(index.OverflowMenu, {
      size: "md",
      className: "".concat(iotPrefix, "--table-head--overflow"),
      direction: "bottom",
      "data-testid": "table-head--overflow",
      flipped: columnIndex === ordering.length - 1,
      onClick: function onClick(e) {
        return e.stopPropagation();
      }
    }, hasOverflow && matchingColumnMeta.overflowMenuItems.map(function (menuItem) {
      return /*#__PURE__*/React__default.default.createElement(react.OverflowMenuItem, {
        "data-testid": "".concat(testID || testId, "-column-overflow-menu-item-").concat(menuItem.id),
        itemText: menuItem.text,
        key: "".concat(columnIndex, "--overflow-item-").concat(menuItem.id),
        onClick: function onClick(e) {
          return handleOverflowItemClick(e, menuItem);
        }
      });
    }), hasMultiSort && /*#__PURE__*/React__default.default.createElement(react.OverflowMenuItem, {
      "data-testid": "".concat(testID || testId, "-column-overflow-menu-item-multi-sort"),
      itemText: i18n.multiSortOverflowItem,
      key: "".concat(columnIndex, "--overflow-item-multi-sort"),
      onClick: function onClick(e) {
        return handleOverflowItemClick(e, {
          id: 'multi-sort',
          meta: {
            columnId: matchingColumnMeta.id
          }
        });
      }
    })) : null, sortOrder > 0 && !isDisabled && /*#__PURE__*/React__default.default.createElement("span", {
      className: "".concat(iotPrefix, "--table-header-label__sort-order")
    }, sortOrder), hasResize && (item !== lastVisibleColumn || showExpanderColumn) ? /*#__PURE__*/React__default.default.createElement(ColumnResize.default, {
      showExpanderColumn: showExpanderColumn,
      onResize: onManualColumnResize,
      ref: columnResizeRefs[matchingColumnMeta.id],
      currentColumnWidths: currentColumnWidths,
      columnId: matchingColumnMeta.id,
      ordering: ordering,
      paddingExtra: paddingExtra,
      preserveColumnWidths: preserveColumnWidths
    }) : null) : null;
  }), showExpanderColumn ? /*#__PURE__*/React__default.default.createElement(TableHeader.default
  // TODO: remove deprecated 'testID' in v3
  , {
    testId: "".concat(testID || testId, "-expander-column"),
    className: classnames__default.default("".concat(iotPrefix, "--table-header-expander-column"))
  }) : null, options.hasRowActions ? /*#__PURE__*/React__default.default.createElement(TableHeader.default
  // TODO: remove deprecated 'testID' in v3
  , {
    testId: "".concat(testID || testId, "-row-actions-column"),
    className: classnames__default.default("".concat(iotPrefix, "--table-header-row-action-column"), _defineProperty__default.default({}, "".concat(iotPrefix, "--table-header-row-action-column--extra-wide"), hasSingleRowEdit))
  }) : null), showColumnGroups ?
  /*#__PURE__*/
  // Column grouping should visually appear above the normal column headers but since we
  // need the normal column headers to control the width of the columns, and since rowspan
  // only works downward, we place the groups below the normal columns and then switch
  // places using scss.
  React__default.default.createElement(ColumnGrouping, {
    appendedColumns: +showExpanderColumn + !!options.hasRowActions,
    testId: "".concat(testId, "-column-grouping"),
    prependedColumns: +!!(hasRowSelection === 'multi' || useRadioButtonSingleSelect && hasRowSelection === 'single') + !!(hasRowExpansion || hasRowNesting) + !!hasDragAndDrop,
    columnGroups: columnGroups,
    ordering: ordering
  }) : null, filterBarActive && /*#__PURE__*/React__default.default.createElement(FilterHeaderRow
  // TODO: remove deprecated 'testID' in v3
  , {
    testId: "".concat(testID || testId, "-filter-header-row"),
    key: "".concat(testID || testId, "-filter-header-row"),
    columns: columns.map(function (column) {
      var _column$filter, _column$filter2;
      return _objectSpread(_objectSpread({}, column.filter), {}, {
        id: column.id,
        isFilterable: !isNil(column.filter),
        isMultiselect: (_column$filter = column.filter) === null || _column$filter === void 0 ? void 0 : _column$filter.isMultiselect,
        width: column.width,
        customInput: (_column$filter2 = column.filter) === null || _column$filter2 === void 0 ? void 0 : _column$filter2.customInput
      });
    }),
    hasFastFilter: hasFastFilter,
    clearFilterText: clearFilterText,
    filterText: filterText,
    clearSelectionText: clearSelectionText,
    openMenuText: openMenuText,
    closeMenuText: closeMenuText,
    ordering: ordering,
    filters: filters,
    tableOptions: options,
    onApplyFilter: onApplyFilter,
    lightweight: lightweight,
    isDisabled: isDisabled,
    showExpanderColumn: showExpanderColumn,
    size: size,
    langDir: langDir,
    showColumnGroups: showColumnGroups,
    filterRowIcon: filterRowIcon,
    filterRowIconDescription: filterRowIconDescription,
    onFilterRowIconClick: onFilterRowIconClick,
    pinHeaderAndFooter: pinHeaderAndFooter,
    hasDragAndDrop: hasDragAndDrop
  }), activeBar === 'column' && /*#__PURE__*/React__default.default.createElement(ColumnHeaderRow.default
  // TODO: remove deprecated 'testID' in v3
  , {
    testId: "".concat(testID || testId, "-column-header-row"),
    columns: columns.map(function (column) {
      return {
        id: column.id,
        name: column.name
      };
    }),
    ordering: ordering,
    options: options,
    onChangeOrdering: onChangeOrdering,
    onColumnToggle: onColumnToggle,
    lightweight: lightweight,
    onColumnSelectionConfig: onColumnSelectionConfig,
    columnSelectionConfigText: i18n.columnSelectionConfig,
    isDisabled: isDisabled,
    showExpanderColumn: showExpanderColumn,
    hasDragAndDrop: hasDragAndDrop
  }));
};
TableHead.propTypes = propTypes;
TableHead.defaultProps = defaultProps;
TableHead.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TableHead",
  "props": {
    "columnGroups": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "Specify the properties of each column group in the table. Defaults to empty column.",
      "type": {
        "name": "custom",
        "raw": "TableColumnGroupPropType"
      },
      "required": false
    },
    "options": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "Important table options that the head needs to know about",
      "type": {
        "name": "shape",
        "value": {
          "hasRowExpansion": {
            "name": "bool",
            "required": false
          },
          "hasRowSelection": {
            "name": "enum",
            "value": [{
              "value": "'multi'",
              "computed": false
            }, {
              "value": "'single'",
              "computed": false
            }, {
              "value": "false",
              "computed": false
            }],
            "required": false
          },
          "useRadioButtonSingleSelect": {
            "name": "bool",
            "required": false
          },
          "hasRowActions": {
            "name": "bool",
            "required": false
          },
          "hasResize": {
            "name": "bool",
            "required": false
          },
          "hasSingleRowEdit": {
            "name": "bool",
            "required": false
          },
          "hasRowNesting": {
            "name": "union",
            "value": [{
              "name": "bool"
            }, {
              "name": "shape",
              "value": {
                "hasSingleNestedHierarchy": {
                  "name": "bool",
                  "description": "If the hierarchy only has 1 nested level of children",
                  "required": false
                }
              }
            }],
            "required": false
          },
          "wrapCellText": {
            "name": "custom",
            "raw": "WrapCellTextPropTypes.isRequired",
            "required": true
          },
          "truncateCellText": {
            "name": "bool",
            "required": true
          },
          "hasMultiSort": {
            "name": "bool",
            "required": false
          },
          "useAutoTableLayoutForResize": {
            "name": "bool",
            "required": false
          },
          "preserveColumnWidths": {
            "name": "bool",
            "description": "Preserves the widths of existing columns when one or more columns are added, removed, hidden, shown or resized.",
            "required": false
          },
          "hasFilterRowIcon": {
            "name": "bool",
            "required": false
          },
          "hasDragAndDrop": {
            "name": "bool",
            "required": false
          },
          "pinHeaderAndFooter": {
            "name": "bool",
            "description": "Freezes table header and footer",
            "required": false
          },
          "pinColumn": {
            "name": "custom",
            "raw": "PinColumnPropTypes",
            "description": "column to pin in the table",
            "required": false
          }
        }
      },
      "required": false
    },
    "lightweight": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "lightweight",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "selectAllText": {
      "defaultValue": {
        "value": "'Select all'",
        "computed": false
      },
      "description": "internationalized labels",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "clearFilterText": {
      "defaultValue": {
        "value": "'Clear filter'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "filterText": {
      "defaultValue": {
        "value": "'Filter'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "clearSelectionText": {
      "defaultValue": {
        "value": "'Clear selection'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "openMenuText": {
      "defaultValue": {
        "value": "'Open menu'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "closeMenuText": {
      "defaultValue": {
        "value": "'Close menu'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  ...defaultI18NPropTypes,\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "custom",
        "raw": "I18NPropTypes"
      },
      "required": false
    },
    "hasFastFilter": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "description": "should we filter on each keypress",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "enablePercentageColumnWidth": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "''",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "showExpanderColumn": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "shows an additional column that can expand/shrink as the table is resized",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "size": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Size prop from Carbon to shrink row height (and header height in some instances)",
      "type": {
        "name": "custom",
        "raw": "function checkProps(props, propName, componentName) {\n  if (['compact', 'short', 'normal', 'tall'].includes(props[propName])) {\n    warning(\n      false,\n      `The value \\`${props[propName]}\\` has been deprecated for the ` +\n        `\\`${propName}\\` prop on the ${componentName} component. It will be removed in the next major ` +\n        `release. Please use 'xs', 'sm', 'md', 'lg', or 'xl' instead.`\n    );\n  }\n}"
      },
      "required": false
    },
    "filterRowIcon": {
      "defaultValue": {
        "value": "FilterEdit",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "union",
        "value": [{
          "name": "func"
        }, {
          "name": "object"
        }]
      },
      "required": false
    },
    "filterRowIconDescription": {
      "defaultValue": {
        "value": "'Edit filters'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "tableId": {
      "description": "",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "columns": {
      "description": "List of columns",
      "type": {
        "name": "custom",
        "raw": "TableColumnsPropTypes.isRequired"
      },
      "required": false
    },
    "tableState": {
      "description": "Current state of the table",
      "type": {
        "name": "shape",
        "value": {
          "isDisabled": {
            "name": "bool",
            "description": "is the tableHead currently disabled",
            "required": false
          },
          "activeBar": {
            "name": "custom",
            "raw": "ActiveTableToolbarPropType",
            "description": "Which toolbar is currently active",
            "required": false
          },
          "selection": {
            "name": "shape",
            "value": {
              "isSelectAllIndeterminate": {
                "name": "bool",
                "required": false
              },
              "isSelectAllSelected": {
                "name": "bool",
                "required": false
              }
            },
            "description": "What's currently selected in the table?",
            "required": true
          },
          "sort": {
            "name": "union",
            "value": [{
              "name": "custom",
              "raw": "TableSortPropType"
            }, {
              "name": "arrayOf",
              "value": {
                "name": "custom",
                "raw": "TableSortPropType"
              }
            }],
            "description": "What sorting is currently applied",
            "required": true
          },
          "ordering": {
            "name": "custom",
            "raw": "TableOrderingPropType.isRequired",
            "description": "Specify the order, visibility and group belonging of the table columns",
            "required": true
          },
          "filters": {
            "name": "arrayOf",
            "value": {
              "name": "shape",
              "value": {
                "columnId": {
                  "name": "string",
                  "required": true
                },
                "value": {
                  "name": "union",
                  "value": [{
                    "name": "string"
                  }, {
                    "name": "number"
                  }, {
                    "name": "bool"
                  }, {
                    "name": "arrayOf",
                    "value": {
                      "name": "string"
                    }
                  }],
                  "required": true
                }
              }
            },
            "description": "Optional list of applied column filters",
            "required": false
          }
        }
      },
      "required": true
    },
    "actions": {
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "onSelectAll": {
            "name": "func",
            "required": false
          },
          "onChangeSort": {
            "name": "func",
            "required": false
          },
          "onChangeOrdering": {
            "name": "func",
            "required": false
          },
          "onColumnSelectionConfig": {
            "name": "func",
            "required": false
          },
          "onApplyFilter": {
            "name": "func",
            "required": false
          },
          "onColumnResize": {
            "name": "func",
            "required": false
          },
          "onOverflowItemClicked": {
            "name": "func",
            "required": false
          },
          "onFilterRowIconClick": {
            "name": "func",
            "required": false
          }
        }
      },
      "required": true
    },
    "testID": {
      "description": "",
      "type": {
        "name": "custom",
        "raw": "deprecate(\n  PropTypes.string,\n  `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
      },
      "required": false
    }
  }
};
var TableHead$1 = TableHead;

module.exports = TableHead$1;
