'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var debounce = require('../../../../utilities/debounce.js');
var useEventListener = require('../../../../utilities/use-event-listener.js');
var useIsomorphicLayoutEffect = require('../../../../utilities/use-isomorphic-layout-effect.js');
var Actions$1 = require('./Actions.scss.js');
var MenuGroup = require('../MenuGroup/MenuGroup.js');
var ButtonGroup = require('../../../ButtonGroup/ButtonGroup.js');
var hooks = require('../../../../utilities/i18n/hooks.js');
var SecondaryAction = require('../SecondaryAction/SecondaryAction.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

const ACTION_SPACING = 8;
function Actions({
  actions = [],
  groups = [],
  onActionRollup
}) {
  const i18n = hooks.useI18n();
  const actionsLayoutRef = React.useRef(null);
  const menuGroupWidthRef = React.useRef(0);
  const availableWidthRef = React.useRef(0);
  const actionsAndGroupsLengthRef = React.useRef(0);
  const timesMeasured = React.useRef(0);
  const actionWidthsRef = React.useRef([]);
  const rollupActiveRef = React.useRef(null);
  const [activeMenuGroup, setActiveMenuGroup] = React.useState(undefined);
  const [measuredActions, setMeasuredActions] = React.useState({
    showable: [],
    rolledUp: []
  });
  const defaultRollupGroup = {
    title: i18n.translate('Polaris.ActionMenu.Actions.moreActions'),
    actions: []
  };
  const lastMenuGroup = [...groups].pop();
  const lastMenuGroupWidth = [...actionWidthsRef.current].pop() || 0;
  const handleActionsOffsetWidth = React.useCallback(width => {
    actionWidthsRef.current = [...actionWidthsRef.current, width];
  }, []);
  const handleMenuGroupToggle = React.useCallback(group => setActiveMenuGroup(activeMenuGroup ? undefined : group), [activeMenuGroup]);
  const handleMenuGroupClose = React.useCallback(() => setActiveMenuGroup(undefined), []);
  const updateActions = React.useCallback(() => {
    let actionsAndGroups = [...actions, ...groups];

    if (groups.length > 0) {
      // We don't want to include actions from the last group
      // since it is always rendered with its own actions
      actionsAndGroups = [...actionsAndGroups].slice(0, actionsAndGroups.length - 1);
    }

    setMeasuredActions(currentMeasuredActions => {
      const showable = actionsAndGroups.slice(0, currentMeasuredActions.showable.length);
      const rolledUp = actionsAndGroups.slice(currentMeasuredActions.showable.length, actionsAndGroups.length);
      return {
        showable,
        rolledUp
      };
    });
  }, [actions, groups]);
  const measureActions = React.useCallback(() => {
    if (actionWidthsRef.current.length === 0 || availableWidthRef.current === 0) {
      return;
    }

    const actionsAndGroups = [...actions, ...groups];

    if (actionsAndGroups.length === 1) {
      setMeasuredActions({
        showable: actionsAndGroups,
        rolledUp: []
      });
      return;
    }

    let currentAvailableWidth = availableWidthRef.current;
    let newShowableActions = [];
    let newRolledUpActions = [];
    actionsAndGroups.forEach((action, index) => {
      const canFitAction = actionWidthsRef.current[index] + menuGroupWidthRef.current + ACTION_SPACING + lastMenuGroupWidth <= currentAvailableWidth;

      if (canFitAction) {
        currentAvailableWidth -= actionWidthsRef.current[index] + ACTION_SPACING * 2;
        newShowableActions = [...newShowableActions, action];
      } else {
        currentAvailableWidth = 0; // Find last group if it exists and always render it as a rolled up action below

        if (action === lastMenuGroup) return;
        newRolledUpActions = [...newRolledUpActions, action];
      }
    });

    if (onActionRollup) {
      // Note: Do not include last group actions since we are skipping `lastMenuGroup` above
      // as it is always rendered with its own actions
      const isRollupActive = newShowableActions.length < actionsAndGroups.length - 1;

      if (rollupActiveRef.current !== isRollupActive) {
        onActionRollup(isRollupActive);
        rollupActiveRef.current = isRollupActive;
      }
    }

    setMeasuredActions({
      showable: newShowableActions,
      rolledUp: newRolledUpActions
    });
    timesMeasured.current += 1;
    actionsAndGroupsLengthRef.current = actionsAndGroups.length;
  }, [actions, groups, lastMenuGroup, lastMenuGroupWidth, onActionRollup]);
  const handleResize = React.useMemo(() => debounce.debounce(() => {
    if (!actionsLayoutRef.current) return;
    availableWidthRef.current = actionsLayoutRef.current.offsetWidth; // Set timesMeasured to 0 to allow re-measuring

    timesMeasured.current = 0;
    measureActions();
  }, 50, {
    leading: false,
    trailing: true
  }), [measureActions]);
  useEventListener.useEventListener('resize', handleResize);
  useIsomorphicLayoutEffect.useIsomorphicLayoutEffect(() => {
    if (!actionsLayoutRef.current) return;
    availableWidthRef.current = actionsLayoutRef.current.offsetWidth;

    if ( // Allow measuring twice
    // This accounts for the initial paint and re-flow
    timesMeasured.current >= 2 && [...actions, ...groups].length === actionsAndGroupsLengthRef.current) {
      updateActions();
      return;
    }

    measureActions();
  }, [actions, groups, measureActions, updateActions]);
  const actionsMarkup = actions.map(action => {
    if (measuredActions.showable.length > 0 || measuredActions.rolledUp.includes(action)) return null;
    const {
      content,
      onAction,
      ...rest
    } = action;
    return /*#__PURE__*/React__default["default"].createElement(SecondaryAction.SecondaryAction, Object.assign({
      key: content,
      onClick: onAction
    }, rest, {
      getOffsetWidth: handleActionsOffsetWidth
    }), content);
  });
  const rollUppableActionsMarkup = measuredActions.showable.length > 0 ? measuredActions.showable.map(action => action.content && /*#__PURE__*/React__default["default"].createElement(SecondaryAction.SecondaryAction, Object.assign({
    key: action.content
  }, action, {
    getOffsetWidth: handleActionsOffsetWidth
  }), action.content)) : null;
  const filteredGroups = [...groups, defaultRollupGroup].filter(group => {
    return groups.length === 0 ? group : group === lastMenuGroup || !measuredActions.rolledUp.some(rolledUpGroup => isMenuGroup(rolledUpGroup) && rolledUpGroup.title === group.title);
  });
  const groupsMarkup = filteredGroups.map(group => {
    const {
      title,
      actions: groupActions,
      ...rest
    } = group;
    const isDefaultGroup = group === defaultRollupGroup;
    const isLastMenuGroup = group === lastMenuGroup;
    const [finalRolledUpActions, finalRolledUpSectionGroups] = measuredActions.rolledUp.reduce(([actions, sections], action) => {
      if (isMenuGroup(action)) {
        sections.push({
          title: action.title,
          items: action.actions.map(sectionAction => ({ ...sectionAction,
            disabled: action.disabled || sectionAction.disabled
          }))
        });
      } else {
        actions.push(action);
      }

      return [actions, sections];
    }, [[], []]);

    if (!isDefaultGroup && !isLastMenuGroup) {
      // Render a normal MenuGroup with just its actions
      return /*#__PURE__*/React__default["default"].createElement(MenuGroup.MenuGroup, Object.assign({
        key: title,
        title: title,
        active: title === activeMenuGroup,
        actions: groupActions
      }, rest, {
        onOpen: handleMenuGroupToggle,
        onClose: handleMenuGroupClose,
        getOffsetWidth: handleActionsOffsetWidth
      }));
    } else if (!isDefaultGroup && isLastMenuGroup) {
      // render the last, rollup group with its actions and finalRolledUpActions
      return /*#__PURE__*/React__default["default"].createElement(MenuGroup.MenuGroup, Object.assign({
        key: title,
        title: title,
        active: title === activeMenuGroup,
        actions: [...finalRolledUpActions, ...groupActions],
        sections: finalRolledUpSectionGroups
      }, rest, {
        onOpen: handleMenuGroupToggle,
        onClose: handleMenuGroupClose,
        getOffsetWidth: handleActionsOffsetWidth
      }));
    } else if (isDefaultGroup && groups.length === 0 && finalRolledUpActions.length) {
      // Render the default group to rollup into if one does not exist
      return /*#__PURE__*/React__default["default"].createElement(MenuGroup.MenuGroup, Object.assign({
        key: title,
        title: title,
        active: title === activeMenuGroup,
        actions: finalRolledUpActions,
        sections: finalRolledUpSectionGroups
      }, rest, {
        onOpen: handleMenuGroupToggle,
        onClose: handleMenuGroupClose,
        getOffsetWidth: handleActionsOffsetWidth
      }));
    }
  });
  const groupedActionsMarkup = /*#__PURE__*/React__default["default"].createElement(ButtonGroup.ButtonGroup, {
    spacing: "extraTight"
  }, rollUppableActionsMarkup, actionsMarkup, groupsMarkup);
  return /*#__PURE__*/React__default["default"].createElement("div", {
    className: Actions$1["default"].ActionsLayout,
    ref: actionsLayoutRef
  }, groupedActionsMarkup);
}

function isMenuGroup(actionOrMenuGroup) {
  return 'title' in actionOrMenuGroup;
}

exports.Actions = Actions;
