"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TableHeaderCell = TableHeaderCell;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _reactTable = require("@tanstack/react-table");
var _faDownLong = require("@fortawesome/free-solid-svg-icons/faDownLong");
var _faUpLong = require("@fortawesome/free-solid-svg-icons/faUpLong");
var _fontAwesomeIcon = require("../../font-awesome-icon");
var _truncateWithTooltip = require("../../truncate-with-tooltip");
var _useTranslation = require("../../hooks/use-translation");
var _types = require("../types");
var _useTableKeyboardNavigation = require("../../hooks/use-table-keyboard-navigation");
var _tableHeaderCellMenu = require("./table-header-cell-menu");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function TableHeaderCell({
  header,
  isLeft,
  isLastPinned,
  shouldShowPinnedShadow,
  isRight,
  shouldShowRightPinnedShadow,
  thClassName,
  onColumnHeaderClick,
  tableContainerWidth,
  columnIndex,
  localizationText,
  tableHeaderCellTestId
}) {
  const {
    t
  } = (0, _useTranslation.useTranslation)();
  const localizationTextWithDefault = localizationText ?? {
    headerCellAriaLabel: (headerLabel, canSort) => {
      return t('Column Header: {{headerLabel}}. To focus on the header column actions press Tab key', {
        headerLabel,
        sortingString: canSort ? t('Sortable.') : ''
      });
    }
  };
  const navigationContext = (0, _react.useContext)(_useTableKeyboardNavigation.TableKeyboardNavigationContext);
  const headerCellRef = (0, _react.useRef)(null);
  const canSort = header.column.getCanSort();
  const canShowMenu = !header.column.columnDef.meta?.hideMenu;
  const isFirstHeaderColumn = header.getContext().table.getVisibleFlatColumns().filter(headerItem => headerItem.id !== _types.EXPAND_TOGGLE_COLUMN.ID)[0]?.id === header.id;
  const sorted = header.column.getIsSorted();
  const sortingHandler = header.column.getToggleSortingHandler();
  const onHeaderClickHandler = (0, _react.useCallback)(event => {
    if (onColumnHeaderClick) {
      onColumnHeaderClick(header, event);
    }
    // if there is no limit on sorting orders - do the normal sorting
    if (sortingHandler && !header.column.columnDef.meta?.limitSorting) {
      sortingHandler(event);
    } else if (header.column.columnDef.meta?.limitSorting) {
      // if there is a limit on sorting orders
      if (sorted) {
        // clear sorting if the column is already sorted
        header.column.clearSorting();
      } else {
        // or toggle sort with correct direction
        header.column.toggleSorting(header.column.columnDef.meta?.limitSorting === _types.SORTING.DESC, false);
      }
    }
  }, [onColumnHeaderClick, sortingHandler, header]);
  const nextSorting = header.column.columnDef.meta?.limitSorting || header.column.getNextSortingOrder();
  const isRightAlignment = header.column.columnDef?.meta?.align === _types.ALIGNMENT.RIGHT;
  const sortingIcon = sorted ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontAwesomeIcon.FontAwesomeIcon, {
    icon: sorted === _types.SORTING.DESC ? _faDownLong.faDownLong : _faUpLong.faUpLong,
    className: "sorting-icon",
    "test-id": "table-react-sorting-svg"
  }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontAwesomeIcon.FontAwesomeIcon, {
    icon: nextSorting === _types.SORTING.DESC ? _faDownLong.faDownLong : _faUpLong.faUpLong,
    className: "sorting-placeholder",
    "test-id": "table-react-sorting-svg"
  });
  const ariaSortedAttr = (0, _react.useMemo)(() => {
    if (!sorted) {
      return 'none';
    }
    return sorted === _types.SORTING.DESC ? 'descending' : 'ascending';
  }, [sorted]);
  const resizeHandler = header.getResizeHandler();

  // we have to use -1 index, cause 0 index will be used by first virtualized row
  // and I did not want to map it every time by shifting to +1 or smth similar
  navigationContext?.registerCell({
    cellRowIndex: -1,
    cellColumnIndex: columnIndex,
    cellRef: headerCellRef,
    cellAction: onHeaderClickHandler
  });
  const isCurrentCellFocused = navigationContext?.focusedCell === (0, _useTableKeyboardNavigation.getCellId)({
    cellRowIndex: -1,
    cellColumnIndex: columnIndex
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("th", {
    className: (0, _classnames.default)('react-table-th', thClassName, header.column.columnDef.meta?.className, canSort && 'can-sort', sorted && 'sorted', isLeft && 'left-pinned', isLeft && isLastPinned && 'last-pinned', shouldShowPinnedShadow && 'left-shadow ', isRight && 'right-pinned', shouldShowRightPinnedShadow && 'right-shadow'),
    "test-id": tableHeaderCellTestId
    // eslint-disable-next-line react/forbid-dom-props
    ,
    style: {
      minWidth: 92,
      width: header.getSize(),
      left: isLeft ? header.getStart('left') : undefined
    },
    ref: headerCellRef,
    tabIndex: isFirstHeaderColumn && !navigationContext?.focusedCell || isCurrentCellFocused ? 0 : -1,
    onFocus: isFirstHeaderColumn && !navigationContext?.focusedCell ? () => navigationContext?.setFocusedCell(`-1-${columnIndex}`) : undefined,
    role: "columnheader",
    scope: "col",
    id: header.column.id,
    "aria-sort": canSort ? ariaSortedAttr : undefined,
    "aria-label": header.column.columnDef.meta?.headerAriaLabel || localizationTextWithDefault?.headerCellAriaLabel(typeof header.column.columnDef.header === 'string' ? header.column.columnDef.header : header.column.id, canSort),
    "aria-hidden": header.column.columnDef.meta?.ariaHidden,
    children: header.isPlaceholder ? null : /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "react-table-cell",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: (0, _classnames.default)('react-table-cell-actions', isRightAlignment && 'right'),
        onClick: onHeaderClickHandler,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_truncateWithTooltip.TruncateWithTooltip, {
          className: "react-table-cell-text",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
            children: (0, _reactTable.flexRender)(header.column.columnDef.header, {
              ...header.getContext(),
              keyboardNavCellId: `${-1}-${columnIndex}`
            })
          })
        }), canSort && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "sort-wrapper",
          "test-id": "table-react-header-cell-sorting-icon",
          children: sortingIcon
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "react-table-cell-splitter"
        })]
      }), canShowMenu && /*#__PURE__*/(0, _jsxRuntime.jsx)(_tableHeaderCellMenu.TableHeaderCellMenu, {
        header: header,
        tableContainerWidth: tableContainerWidth,
        localizationText: localizationTextWithDefault?.headerMenu,
        isVisible: isCurrentCellFocused
      }), !header.column.columnDef.meta?.hideSeparator &&
      /*#__PURE__*/
      // eslint-disable-next-line jsx-a11y/no-static-element-interactions
      (0, _jsxRuntime.jsx)("div", {
        className: (0, _classnames.default)('th-right-border', header.column.getCanResize() && 'can-resize', header.column.getIsResizing() && 'resizing'),
        "test-id": "th-resize-handler",
        onMouseDown: resizeHandler,
        onTouchStart: resizeHandler
      })]
    })
  });
}