import React, { useCallback, useRef, useState } from "react";
import { SWATCHES } from "./../../../../color-picker/common/data-hooks.js";
import { AddColorButton } from "../add-color-button/index.js";
import { SingleColorSwatch } from "../single-color-swatch/index.js";
import classes from "./new-color-swatches-scss.js";
const COLUMN_COUNT = 6;
const NewColorSwatches = ({
  colors,
  deletableColors,
  selectedColor,
  onAddClick,
  onColorSelected,
  onColorPreviewStart,
  onColorPreviewEnd,
  onColorDeleted,
  dataHook,
  setAddButtonRef,
  labelledById
}) => {
  const [focusedIndex, setFocusedIndex] = useState(null);
  const deletableColorSet = new Set(deletableColors?.map((color) => color.toUpperCase()));
  const swatchRefs = useRef([]);
  const handleKeyDown = (event) => {
    if (focusedIndex === null) {
      return;
    }
    let newIndex = focusedIndex;
    switch (event.key) {
      case "ArrowRight":
        newIndex = (focusedIndex + 1) % colors.length;
        break;
      case "ArrowLeft":
        newIndex = (focusedIndex - 1 + colors.length) % colors.length;
        break;
      case "ArrowDown":
        newIndex = (focusedIndex + COLUMN_COUNT) % colors.length;
        break;
      case "ArrowUp":
        newIndex = (focusedIndex - COLUMN_COUNT + colors.length) % colors.length;
        break;
      default:
        return;
    }
    setFocusedIndex(newIndex);
    event.preventDefault();
    swatchRefs.current[newIndex]?.querySelector("button")?.focus();
  };
  const setColorSwatchRef = useCallback(
    (index) => (element) => swatchRefs.current[index] = element,
    []
  );
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      role: "listbox",
      "aria-labelledby": labelledById,
      "aria-activedescendant": getColorSwatchId(focusedIndex ?? 0),
      "data-hook": dataHook,
      onKeyDown: handleKeyDown,
      tabIndex: 0,
      onFocus: () => {
        if (focusedIndex === null) {
          setFocusedIndex(0);
        }
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: classes.container, "data-hook": SWATCHES }, colors.map((color, index) => /* @__PURE__ */ React.createElement(
      SingleColorSwatch,
      {
        index: getColorSwatchId(index),
        key: color,
        fill: color,
        selectedColor,
        onClick: onColorSelected,
        onMouseEnter: onColorPreviewStart,
        onMouseLeave: onColorPreviewEnd,
        onFocus: () => {
          setFocusedIndex(index);
        },
        onDelete: onColorDeleted && deletableColorSet.has(color.toUpperCase()) ? onColorDeleted : void 0,
        setRef: setColorSwatchRef(index)
      }
    )), !!onAddClick && /* @__PURE__ */ React.createElement(AddColorButton, { onAddClick, setRef: setAddButtonRef }))
  );
};
const getColorSwatchId = (index) => `color-swatch-${index}`;
export {
  NewColorSwatches
};
//# sourceMappingURL=new-color-swatches.js.map
