"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSelected = void 0;
var _react = require("react");
var _getSelectedValues = require("./getSelectedValues");
// Copyright 1999-2025. WebPros International GmbH. All rights reserved.

const alphaSort = (a, b) => a > b ? 1 : -1;
const useSelected = _ref => {
  let {
    multiple,
    externalSelected,
    onChange
  } = _ref;
  const getExternal = () => multiple ? (0, _getSelectedValues.getSelectedValues)(externalSelected) : externalSelected;
  const [selected, setSelected] = (0, _react.useState)(getExternal());
  const [prevExternalSelected, setPrevExternalSelected] = (0, _react.useState)(externalSelected);
  if (prevExternalSelected !== externalSelected) {
    setPrevExternalSelected(externalSelected);
    if (selected !== externalSelected) {
      setSelected(getExternal());
    }
  }
  const handleChange = value => {
    let prevSelected = selected;
    let newSelected;
    if (multiple) {
      const isSelectedArray = Array.isArray(selected);
      newSelected = isSelectedArray ? [...selected] : [];
      if (!isSelectedArray || selected.indexOf(value) === -1) {
        newSelected.push(value);
      } else {
        newSelected.splice(selected.indexOf(value), 1);
      }
      newSelected.sort(alphaSort);
      if (isSelectedArray) {
        prevSelected = [...selected].sort(alphaSort);
      }
    } else {
      newSelected = value;
    }
    if (JSON.stringify(prevSelected) !== JSON.stringify(newSelected)) {
      setSelected(newSelected);
      onChange?.(newSelected);
    }
  };
  return {
    selectedValues: (0, _getSelectedValues.getSelectedValues)(selected),
    handleChange
  };
};
exports.useSelected = useSelected;