"use strict";

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

var _react = require("@emotion/react");

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

var _useResizeObserver = _interopRequireDefault(require("../hooks/useResizeObserver"));

var _CollapseExpandIcon = _interopRequireDefault(require("../icons/CollapseExpandIcon"));

var _AccordionGroup = require("./AccordionGroup");

var _constants = require("./constants");

var _styles = require("./styles");

var _jsxRuntime = require("@emotion/react/jsx-runtime");

var _excluded = ["summary", "children"];

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var _ref2 = process.env.NODE_ENV === "production" ? {
  name: "1s8dkvp",
  styles: "border-style:solid;border-bottom-width:1px;--tw-border-opacity:1;border-color:rgba(58, 93, 174, var(--tw-border-opacity))"
} : {
  name: "1mtm4gm-Accordion",
  styles: "border-style:solid;border-bottom-width:1px;--tw-border-opacity:1;border-color:rgba(58, 93, 174, var(--tw-border-opacity));label:Accordion;",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
};

var _ref3 = process.env.NODE_ENV === "production" ? {
  name: "0",
  styles: ""
} : {
  name: "1rz2gw-Accordion",
  styles: ";label:Accordion;",
  toString: _EMOTION_STRINGIFIED_CSS_ERROR__
};

var Accordion = function Accordion(_ref) {
  var summary = _ref.summary,
      children = _ref.children,
      props = _objectWithoutProperties(_ref, _excluded);

  var accordionId = _react2["default"].useMemo(function () {
    return "accordion-".concat(Math.random().toString(16).slice(2));
  }, []);

  var _React$useState = _react2["default"].useState('0px'),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      height = _React$useState2[0],
      setHeight = _React$useState2[1];

  var resizeRef = (0, _useResizeObserver["default"])(_react2["default"].useCallback(function (entries) {
    var _iterator = _createForOfIteratorHelper(entries),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var entry = _step.value;
        var _height = entry.contentRect.height;
        setHeight("".concat(_height, "px"));
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }, [setHeight]));

  var _React$useState3 = _react2["default"].useState(false),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      isOpen = _React$useState4[0],
      setIsOpen = _React$useState4[1];

  var _React$useState5 = _react2["default"].useState(isOpen ? 'opened' : 'closed'),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      transitionState = _React$useState6[0],
      setTransitionState = _React$useState6[1];

  _react2["default"].useEffect(function () {
    var timeout = setTimeout(function () {
      setTransitionState(function (transitionState) {
        if (transitionState === 'opening') {
          return 'opened';
        }

        if (transitionState === 'closing') {
          return 'closed';
        }
      });
      timeout = null;
    }, _constants.TRANSITION_DURATION);
    return function () {
      if (!timeout) return;
      clearTimeout(timeout);
    };
  }, [isOpen, setTransitionState]);

  _react2["default"].useEffect(function () {
    if (isOpen) {
      if (transitionState !== 'opened') setTransitionState('opening');
    } else {
      if (transitionState !== 'closed') setTransitionState('closing');
    }
  }, [isOpen, setTransitionState]);

  var handleToggle = _react2["default"].useCallback(function (e) {
    e.target.dispatchEvent(new CustomEvent('accordion', {
      bubbles: true,
      detail: accordionId
    }));
    setIsOpen(function (state) {
      return !state;
    });
  }, [setIsOpen]);

  var activeAccordion = _react2["default"].useContext(_AccordionGroup.AccordionContext);

  _react2["default"].useEffect(function () {
    if (!activeAccordion || !accordionId) return;
    if (activeAccordion === accordionId) return;
    setIsOpen(false);
  }, [activeAccordion, accordionId, setIsOpen]);

  return (0, _jsxRuntime.jsxs)("div", {
    css: _ref2,
    children: [(0, _jsxRuntime.jsxs)(_styles.AccordionBtn, {
      id: accordionId,
      onClick: handleToggle,
      children: [(0, _jsxRuntime.jsx)(_styles.AccordionBtnSummary, {
        css: _ref3,
        children: summary
      }), (0, _jsxRuntime.jsx)(_CollapseExpandIcon["default"], {
        duration: _constants.TRANSITION_DURATION,
        timingFunction: _constants.TRANSITION_FUNCTION,
        mode: isOpen ? 'collapse' : 'expand'
      })]
    }), (0, _jsxRuntime.jsx)(_styles.AccordionContent, _objectSpread(_objectSpread({
      "aria-hidden": !isOpen,
      tabIndex: -1,
      isOpen: isOpen,
      transitionState: transitionState,
      css: /*#__PURE__*/(0, _react.css)("height:", isOpen ? height : 0, ";" + (process.env.NODE_ENV === "production" ? "" : ";label:Accordion;"), process.env.NODE_ENV === "production" ? "" : "/*# sourceMappingURL=data:application/json;charset=utf-8;base64,  */")
    }, props), {}, {
      children: (0, _jsxRuntime.jsx)("div", {
        ref: resizeRef,
        children: children
      })
    }))]
  });
};

exports.Accordion = Accordion;
var _default = Accordion;
exports["default"] = _default;