"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.AccordionContext = void 0;

var _react = _interopRequireDefault(require("react"));

var _lodash = require("lodash");

var _primitives = require("../../primitives");

var _getIndexedChildren = _interopRequireDefault(require("../../../utils/getIndexedChildren"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

const AccordionContext = /*#__PURE__*/_react.default.createContext({});

exports.AccordionContext = AccordionContext;

const Accordion = ({
  children,
  allowMultiple,
  allowToggle,
  onChange,
  style,
  ...props
}) => {
  const [index, setIndex] = _react.default.useState(props.index || props.defaultIndex || []);

  const changeHandler = (isOpening, activeIndex) => {
    let indexCopy = index.map(i => i);

    if (allowToggle) {
      if (isOpening) {
        indexCopy.push(activeIndex);
        allowMultiple ? setIndex(indexCopy) : setIndex([activeIndex]);
      } else {
        setIndex(index.splice(index.indexOf(activeIndex), 1));
      }
    } else {
      if (isOpening) {
        indexCopy.push(activeIndex);
        allowMultiple ? setIndex(indexCopy) : setIndex([activeIndex]);
      } else {
        (0, _lodash.remove)(indexCopy, n => n === activeIndex);
        setIndex(indexCopy);
      }
    }

    onChange && onChange(indexCopy);
  };

  return /*#__PURE__*/_react.default.createElement(AccordionContext.Provider, {
    value: {
      index: index,
      changeHandler
    }
  }, /*#__PURE__*/_react.default.createElement(_primitives.Box, _extends({
    style: style
  }, props), (0, _getIndexedChildren.default)(children, 'AccordionItem')));
};

var _default = Accordion;
exports.default = _default;
//# sourceMappingURL=Accordion.js.map