import { jsx, jsxs } from "../../../packages/jsx/src/jsx-runtime.js";
import { useRef } from "react";
import { ArrowDown } from "../../../atoms/Icon/ArrowDown.js";
import { PinIconButton } from "./PinIconButton.js";
import { Tooltip } from "../../../molecules/Tooltip/Tooltip.js";
import { Flex } from "../../../atoms/Flex/Flex.js";
import { Spacing } from "../../../tokens/Spacing.js";
import { Text } from "../../../atoms/Text/Text.js";
import { buildBorder } from "../../../tokens/utils.js";
const columnSortIconClass = "column-sort-icon";
const pinIconButtonClass = "pin-icon-button";
function TableColumnHeaderCell({
  pinnedColumns,
  className,
  style,
  column,
  "aria-colindex": ariaColIndex,
  sortDescriptor,
  onSortChange,
  tabIndex,
  onFocus,
  onBlur,
  onPointerDown,
  pinningDisabled
}) {
  const ref = useRef(null);
  const isSortedByThisColumn = (sortDescriptor == null ? void 0 : sortDescriptor.column) === column.key;
  const sortedAscending = (sortDescriptor == null ? void 0 : sortDescriptor.direction) === "asc";
  const { tooltip, width, allowsSorting } = column;
  pinningDisabled || (pinningDisabled = column.pinningDisabled);
  const isPinned = pinnedColumns.isPinned ? pinnedColumns.isPinned(column) : false;
  const handleSort = () => {
    if (!allowsSorting) return;
    if (!isSortedByThisColumn) {
      onSortChange == null ? void 0 : onSortChange({ column: column.key, direction: "desc" });
      return;
    }
    onSortChange == null ? void 0 : onSortChange({ column: column.key, direction: sortedAscending ? "desc" : "asc" });
  };
  const handlePin = () => {
    if (!pinnedColumns.pin) return;
    pinnedColumns.pin(column);
    setTimeout(() => {
      const futureSelf = document.querySelector(`[role="columnheader"][data-columnkey="${column.key}"]`);
      if (futureSelf) {
        futureSelf.focus();
      }
    }, 0);
  };
  const onKeyDown = (event) => {
    if (event.key === " " || event.key === "Enter") {
      event.preventDefault();
      handleSort();
    } else if (event.key === "p") {
      event.preventDefault();
      handlePin();
    }
  };
  return /* @__PURE__ */ jsx(
    "div",
    {
      role: "columnheader",
      "aria-colindex": ariaColIndex,
      "data-columnkey": column.key,
      tabIndex,
      className,
      style,
      onFocus,
      onBlur,
      onKeyDown,
      onPointerDown,
      onClick: handleSort,
      sx: {
        display: "table-cell",
        px: Spacing["16px"],
        py: Spacing["8px"],
        width,
        borderBottom: buildBorder(isSortedByThisColumn ? "White88" : "White32"),
        color: isSortedByThisColumn ? "White88" : "White64",
        "&:hover": { color: "White", borderBottomColor: "White" },
        "&:focus-visible": { outline: "none" },
        [`.${columnSortIconClass}`]: {
          opacity: isSortedByThisColumn ? 1 : 0
        },
        "&:hover, &:focus-visible": {
          borderBottom: buildBorder(isSortedByThisColumn ? "White" : "White88"),
          [`.${columnSortIconClass}, .${pinIconButtonClass}`]: {
            opacity: 1
          }
        },
        ...allowsSorting && { cursor: "pointer" }
      },
      ref,
      children: /* @__PURE__ */ jsxs(Flex.Row, { children: [
        /* @__PURE__ */ jsx(Tooltip, { content: typeof tooltip === "string" ? { title: column.label, text: tooltip } : tooltip, children: /* @__PURE__ */ jsxs(Flex, { gap: Spacing["8px"], children: [
          /* @__PURE__ */ jsx(Text.C10, { color: "inherit", sx: { whiteSpace: "nowrap", userSelect: "none" }, children: column.label }),
          allowsSorting && /* @__PURE__ */ jsxs(Flex, { gap: Spacing["8px"], className: columnSortIconClass, align: "center", children: [
            /* @__PURE__ */ jsx(VerticalDivider, { sx: { mr: "2px" } }),
            /* @__PURE__ */ jsx(
              ArrowDown,
              {
                "aria-label": `Sort ${!sortedAscending ? "ascending" : "descending"}`,
                size: "12px",
                sx: {
                  transition: "transform 0.2s ease-in-out",
                  transform: !isSortedByThisColumn || sortedAscending ? "rotateX(180deg)" : "",
                  // This is needed to properly center the icon in Explorer. Why?
                  display: "flex"
                }
              }
            )
          ] })
        ] }) }),
        /* @__PURE__ */ jsx("div", { sx: { flex: 1 } }),
        !pinningDisabled && pinnedColumns.pin && /* @__PURE__ */ jsx(
          PinIconButton,
          {
            onClick: (event) => {
              event.stopPropagation();
              handlePin();
            },
            isPinned,
            className: pinIconButtonClass,
            sx: { ml: Spacing["8px"], opacity: 0 }
          }
        )
      ] })
    }
  );
}
function VerticalDivider({ className }) {
  return /* @__PURE__ */ jsx("div", { className, sx: { borderRight: buildBorder("White16"), height: "100%" } });
}
export {
  TableColumnHeaderCell
};
