"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

var React = _interopRequireWildcard(require("react"));

var _utils = require("../utils");

var _classnames = _interopRequireDefault(require("classnames"));

var _Box = _interopRequireDefault(require("../box/Box"));

var _Flex = _interopRequireDefault(require("../flex/Flex"));

var _Icon = _interopRequireWildcard(require("../icons/Icon"));

var _Link = _interopRequireDefault(require("../text/Link"));

var _Text = _interopRequireDefault(require("../text/Text"));

var _Accordion = require("./Accordion");

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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; }

var AccordionItem = function AccordionItem(_ref) {
  var title = _ref.title,
      _ref$titleSize = _ref.titleSize,
      titleSize = _ref$titleSize === void 0 ? 'large' : _ref$titleSize,
      children = _ref.children,
      _ref$className = _ref.className,
      className = _ref$className === void 0 ? '' : _ref$className,
      _ref$padding = _ref.padding,
      padding = _ref$padding === void 0 ? 'm' : _ref$padding,
      _ref$tabIndex = _ref.tabIndex,
      tabIndex = _ref$tabIndex === void 0 ? 0 : _ref$tabIndex,
      customId = _ref.id,
      _ref$ariaHeadingLevel = _ref.ariaHeadingLevel,
      ariaHeadingLevel = _ref$ariaHeadingLevel === void 0 ? 2 : _ref$ariaHeadingLevel;
  var contentRef = (0, React.useRef)(null);

  var _useRef = (0, React.useRef)(customId !== null && customId !== void 0 ? customId : "AccordionItem_".concat((0, _utils.generateId)())),
      id = _useRef.current;

  var contentId = "Section_".concat(id);

  var _useContext = (0, React.useContext)(_Accordion.AccordionContext),
      noGapBetweenElements = _useContext.noGapBetweenElements,
      expanded = _useContext.expanded,
      focusedElementId = _useContext.focusedElementId,
      dispatch = _useContext.dispatch,
      reduceMotion = _useContext.reduceMotion,
      onItemSelect = _useContext.onItemSelect;

  var hasRenderedInitially = (0, React.useRef)(false);

  var _useState = (0, React.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      isHovered = _useState2[0],
      setIsHovered = _useState2[1];

  var isCollapsed = !expanded.includes(id);
  var isFocused = focusedElementId === id;
  var isHighlighted = isHovered || isFocused;
  var isBorderHighlighted = isHighlighted && !noGapBetweenElements;
  var isTitleString = typeof title === 'string';
  var toggleOpen = React.useCallback(function () {
    onItemSelect(id, isCollapsed);
  }, [id, isCollapsed, onItemSelect]);
  var handleFocus = React.useCallback(function () {
    dispatch({
      type: 'accordion/SET_FOCUSED',
      payload: {
        id: id
      }
    });
  }, [dispatch, id]);
  var handleBlur = React.useCallback(function () {
    dispatch({
      type: 'accordion/SET_FOCUSED',
      payload: {
        id: ''
      }
    });
  }, [dispatch]);
  (0, React.useEffect)(function () {
    var content = contentRef.current;

    function collapse() {
      if (!contentRef.current) {
        return;
      }

      if (reduceMotion || !hasRenderedInitially.current) {
        contentRef.current.style.height = "".concat(0, "px");
        contentRef.current.hidden = true;
        contentRef.current.style.overflow = 'hidden';
        hasRenderedInitially.current = true;
      } else {
        var sectionHeight = contentRef.current.scrollHeight;
        requestAnimationFrame(function () {
          if (!contentRef.current) {
            return;
          }

          contentRef.current.style.height = "".concat(sectionHeight, "px");
          requestAnimationFrame(function () {
            if (!contentRef.current) {
              return;
            }

            contentRef.current.style.height = "0px";
            contentRef.current.style.overflow = "hidden";
            contentRef.current.addEventListener('transitionend', onTransitionEnd);
          });
        });
      }
    }

    function expand() {
      if (!contentRef.current) {
        return;
      }

      contentRef.current.hidden = false;
      var sectionHeight = contentRef.current.scrollHeight;

      if (reduceMotion || !hasRenderedInitially.current) {
        contentRef.current.style.height = 'auto';
        contentRef.current.style.overflow = 'visible';
        hasRenderedInitially.current = true;
      } else {
        contentRef.current.style.height = "".concat(sectionHeight, "px");
        contentRef.current.addEventListener('transitionend', onTransitionEnd);
      }
    }

    function onTransitionEnd() {
      if (!contentRef.current) {
        return;
      }

      if (contentRef.current.style.height === '0px') {
        // we set hidden in order to prevent gaining focus inside collapsed content
        contentRef.current.hidden = true;
      } else {
        contentRef.current.style.height = 'auto';
        contentRef.current.style.overflow = 'visible';
      }

      contentRef.current.removeEventListener('transitionend', onTransitionEnd);
    }

    isCollapsed ? collapse() : expand();
    return function () {
      if (!content) {
        return;
      }

      content.removeEventListener('transitionend', onTransitionEnd);
    };
  }, [isCollapsed, reduceMotion]);
  return React.useMemo(function () {
    return /*#__PURE__*/React.createElement(_Box.default, {
      color: "white",
      border: true,
      borderColor: isBorderHighlighted ? 'gray-40' : 'gray-20',
      className: (0, _classnames.default)('sg-accordion-item', {
        'sg-accordion-item--no-gap': noGapBetweenElements,
        'sg-accordion-item--reduced-motion': reduceMotion
      }, className),
      padding: null
    }, /*#__PURE__*/React.createElement("div", {
      role: "heading",
      "aria-level": ariaHeadingLevel,
      id: id
    }, /*#__PURE__*/React.createElement(_Box.default, {
      padding: padding,
      className: "sg-accordion-item__button",
      onClick: toggleOpen,
      onMouseEnter: function onMouseEnter() {
        return setIsHovered(true);
      },
      onMouseLeave: function onMouseLeave() {
        return setIsHovered(false);
      },
      onFocus: handleFocus,
      onBlur: handleBlur,
      "aria-expanded": !isCollapsed,
      "aria-controls": contentId,
      role: "button",
      tabIndex: tabIndex
    }, /*#__PURE__*/React.createElement(_Flex.default, {
      direction: "row",
      justifyContent: "space-between",
      alignItems: "center"
    }, isTitleString ? /*#__PURE__*/React.createElement(_Link.default, {
      size: titleSize,
      color: "text-black",
      weight: "bold",
      underlined: isHighlighted,
      disabled: true
    }, title) : /*#__PURE__*/React.createElement("span", {
      className: "sg-accordion-item__title"
    }, title), /*#__PURE__*/React.createElement(_Flex.default, {
      justifyContent: "center",
      alignItems: "center",
      className: (0, _classnames.default)('sg-accordion-item__icon', {
        'sg-accordion-item__icon--hover': isHighlighted
      })
    }, /*#__PURE__*/React.createElement(_Icon.default, {
      type: "chevron_down",
      color: _Icon.ICON_COLOR['icon-black'],
      className: (0, _classnames.default)('sg-accordion-item__arrow', {
        'sg-accordion-item__arrow--visible': !isCollapsed
      }),
      "aria-hidden": "true"
    }))))), /*#__PURE__*/React.createElement("div", {
      ref: contentRef,
      className: "sg-accordion-item__content",
      id: contentId,
      role: "region",
      "aria-labelledby": id,
      hidden: true
    }, /*#__PURE__*/React.createElement(_Box.default, {
      padding: padding,
      className: "sg-accordion-item__content-box"
    }, /*#__PURE__*/React.createElement(_Text.default, null, children))));
  }, [isBorderHighlighted, noGapBetweenElements, ariaHeadingLevel, children, className, contentId, handleBlur, handleFocus, id, isCollapsed, isHighlighted, isTitleString, padding, reduceMotion, tabIndex, title, titleSize, toggleOpen]);
};

var _default = AccordionItem;
exports.default = _default;