import { compose, setPropTypes, withHandlers, lifecycle } from 'recompose';
import { constructWebexEnhancer, withIntl } from '@webex/webex-widget-base';
import mercury, { connectToMercury, enhancer } from '@webex/redux-module-mercury';
import { Record, fromJS } from 'immutable';
import MessageWidget, { reducers as reducers$1 } from '@webex/widget-message';
import MeetWidget, { reducers as reducers$2 } from '@webex/widget-meet';
import RosterWidget, { reducers as reducers$3 } from '@webex/widget-roster';
import errors$1, { addError, removeError, resetErrors } from '@webex/redux-module-errors';
import features, { getFeature } from '@webex/redux-module-features';
import media from '@webex/redux-module-media';
import spaces, { fetchSpace } from '@webex/redux-module-spaces';
import users, { getUser } from '@webex/redux-module-users';
import { validateAndDecodeId, isUuid, deconstructHydraId } from '@webex/react-component-utils';
import { defineMessages } from 'react-intl';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import classNames from 'classnames';
import { Icon, Button } from '@momentum-ui/react';
import TitleBar from '@webex/react-component-title-bar';
import LoadingScreen from '@webex/react-component-loading-screen';
import Timer from '@webex/react-component-timer';
import ErrorDisplay from '@webex/react-component-error-display';
import ActivityMenu from '@webex/react-component-activity-menu';
import FilesWidget from '@webex/widget-files';
import { fetchAvatar } from '@webex/redux-module-avatar';
import { resetConversation } from '@webex/redux-module-conversation';
import { createSelector } from 'reselect';

/*
 * WidgetSpace Messages
 *
 * This contains all the text for the FeaturePage component.
 */
var messages$1 = defineMessages({
  errorConnection: {
    id: 'ciscospark.container.space.error.connection',
    defaultMessage: 'Connection unavailable.'
  },
  errorNotFound: {
    id: 'ciscospark.container.space.error.notfound',
    defaultMessage: 'Either the Space does not exist or you don\'t have permission to view this Space'
  },
  errorBadToken: {
    id: 'ciscospark.container.space.error.badtoken',
    defaultMessage: 'Error: Bad or Invalid Access Token'
  },
  errorToSelf: {
    id: 'ciscospark.container.space.error.toself',
    defaultMessage: 'Error: You Cannot Open a Space with Yourself'
  },
  badSpaceId: {
    id: 'ciscospark.container.space.error.badid',
    defaultMessage: 'Error: Invalid Space ID'
  },
  disabledInitialActivity: {
    id: 'ciscospark.container.space.error.invalidActivity',
    defaultMessage: 'Error: The selected initial activity is invalid'
  },
  invalidSendMessageConfiguration: {
    id: 'ciscospark.container.space.error.invalidSendMessageConfiguration',
    defaultMessage: 'Error: The current configuration will not allow for sending messages'
  },
  unableToLoad: {
    id: 'ciscospark.container.space.error.unabletoload',
    defaultMessage: 'Unable to Load Space'
  },
  unknownDestination: {
    id: 'ciscospark.container.space.error.unknownDestination',
    defaultMessage: 'Please provide a Space ID or To Person'
  },
  invalidDestination: {
    id: 'ciscospark.container.space.error.invalidDestination',
    defaultMessage: 'Destination IDs must be fully encoded (not a UUID)'
  },
  unknownError: {
    id: 'ciscospark.container.space.error.unknown',
    defaultMessage: 'There was a problem loading space'
  },
  reconnecting: {
    id: 'ciscospark.container.space.error.reconnecting',
    defaultMessage: 'Reconnecting...'
  },
  errorConversation: {
    id: 'ciscospark.container.space.error.noConversation',
    defaultMessage: 'Conversation Not Available'
  },
  noAbilityToStartMeeting: {
    id: 'ciscospark.container.space.error.noAbilityToStartMeetingTooltip',
    defaultMessage: 'Your account currently does not have the ability to start a meeting.'
  }
});

/* eslint-disable import/prefer-default-export */

// exports the types of  destination we can dial to 
const destinationTypes = {
  EMAIL: 'email',
  USERID: 'userId',
  SPACEID: 'spaceId',
  SIP: 'sip',
  PSTN: 'pstn'
};

const FETCHING_SPACE_DETAILS = 'widget-space/FETCHING_SPACE_DETAILS';
const RELOAD_WIDGET = 'widget-space/RELOAD_WIDGET';
const STORE_ACTIVITY_TYPES = 'widget-space/STORE_ACTIVITY_TYPES';
const STORE_DESTINATION = 'widget-space/STORE_DESTINATION';
const STORE_SPACE_DETAILS = 'widget-space/STORE_SPACE_DETAILS';
const TOGGLE_ACTIVITY_MENU_VISIBLE = 'widget-space/TOGGLE_ACTIVITY_MENU_VISIBLE';
const UPDATE_ACTIVITY_TYPE = 'widget-space/UPDATE_ACTIVITY_TYPE';
const UPDATE_ACTIVITY_TYPE_SECONDARY = 'widget-space/UPDATE_ACTIVITY_TYPE_SECONDARY';
const UPDATE_ACTIVITY_MENU_VISIBLE = 'widget-space/UPDATE_ACTIVITY_MENU_VISIBLE';
const UPDATE_WIDGET_STATUS = 'widget-space/UPDATE_WIDGET_STATUS';
function updateActivityType(type) {
  return {
    type: UPDATE_ACTIVITY_TYPE,
    payload: {
      type
    }
  };
}
function updateSecondaryActivityType(type) {
  return {
    type: UPDATE_ACTIVITY_TYPE_SECONDARY,
    payload: {
      type
    }
  };
}

/**
 * Resets the widget to "almost" default values
 * This is usually triggered when a destination changes
 *
 * @export
 * @returns {Object}
 */
function reloadWidget() {
  return {
    type: RELOAD_WIDGET
  };
}

/**
 * Stores the space widget's destination
 *
 * @export
 * @param {Object} {id, location}
 * @returns {Object}
 */
function storeDestination({
  id,
  cluster,
  type
}) {
  return {
    type: STORE_DESTINATION,
    payload: {
      id,
      type,
      // Don't store a undefined value
      ...(cluster && {
        cluster
      })
    }
  };
}
function toggleActivityMenuVisible() {
  return {
    type: TOGGLE_ACTIVITY_MENU_VISIBLE
  };
}
function storeSpaceDetails(details) {
  return {
    type: STORE_SPACE_DETAILS,
    payload: {
      details
    }
  };
}
function storeActivityTypes(activityTypes) {
  return {
    type: STORE_ACTIVITY_TYPES,
    payload: {
      activityTypes
    }
  };
}
function updateWidgetStatus(status) {
  return {
    type: UPDATE_WIDGET_STATUS,
    payload: {
      status
    }
  };
}
function fetchingSpaceDetails() {
  return {
    type: FETCHING_SPACE_DETAILS
  };
}

/**
 * Gets details about the space
 * @param {Object} options.sparkInstance
 * @param {String} options.destinationId
 * @param {String} options.destinationType
 * @param {String} options.destinationCluster
 * @param {Object} options.intl
 * @returns {Thunk}
 */
function getSpaceDetails$1({
  sparkInstance,
  destinationId,
  destinationType,
  intl
}) {
  return dispatch => {
    // We cannot fetch space details for 1:1's here, it will be handled in conversation store
    if ([destinationTypes.EMAIL, destinationTypes.USERID, destinationTypes.SIP, destinationTypes.PSTN].includes(destinationType)) {
      return dispatch(storeSpaceDetails({
        type: 'direct'
      }));
    }
    const {
      formatMessage
    } = intl;
    const {
      id: spaceIdUUID
    } = validateAndDecodeId(destinationId);
    if (!spaceIdUUID) {
      const displayTitle = formatMessage(messages$1.unableToLoad);
      const displaySubtitle = formatMessage(messages$1.badSpaceId);
      return dispatch(addError({
        id: 'getSpace.badId',
        displayTitle,
        displaySubtitle,
        temporary: false
      }));
    }
    dispatch(fetchingSpaceDetails());
    return sparkInstance.request({
      service: 'hydra',
      resource: `/rooms/${destinationId}`
    }).then(res => dispatch(storeSpaceDetails(res.body))).catch(error => {
      const displayTitle = formatMessage(messages$1.unableToLoad);
      let displaySubtitle;
      if (error.statusCode === 401) {
        displaySubtitle = formatMessage(messages$1.errorBadToken);
      } else if (error.statusCode === 404) {
        displaySubtitle = formatMessage(messages$1.errorNotFound);
      }
      return dispatch(addError({
        id: 'getSpace.hydraFail',
        displayTitle,
        displaySubtitle,
        temporary: false,
        code: error.statusCode
      }));
    });
  };
}

const Status = Record({
  activityMenuVisible: false,
  hasError: false,
  hasFetchedFeatureFlags: false,
  isFetchingFeatureFlags: false,
  isFetchingSpaceDetails: false,
  shouldReloadWidget: false
});
const Destination = Record({
  id: null,
  type: null
});
const initialState = fromJS({
  activityTypes: [],
  destination: null,
  error: null,
  primaryActivityType: null,
  secondaryActivityType: null,
  spaceDetails: null,
  status: new Status()
});
function reducer(state = initialState, action) {
  switch (action.type) {
    case UPDATE_ACTIVITY_MENU_VISIBLE:
      return state.set('activityMenuVisible', action.payload.isActivityMenuVisible);
    case UPDATE_ACTIVITY_TYPE:
      return state.set('primaryActivityType', action.payload.type).set('secondaryActivityType', null).setIn(['status', 'activityMenuVisible'], false);
    case UPDATE_ACTIVITY_TYPE_SECONDARY:
      return state.set('secondaryActivityType', action.payload.type).setIn(['status', 'activityMenuVisible'], false);
    case TOGGLE_ACTIVITY_MENU_VISIBLE:
      return state.setIn(['status', 'activityMenuVisible'], !state.getIn(['status', 'activityMenuVisible']));
    case FETCHING_SPACE_DETAILS:
      return state.setIn(['status', 'isFetchingSpaceDetails'], true);
    case STORE_SPACE_DETAILS:
      return state.setIn(['status', 'isFetchingSpaceDetails'], false).set('spaceDetails', fromJS(Object.assign({}, action.payload.details)));
    case STORE_ACTIVITY_TYPES:
      {
        return state.set('activityTypes', fromJS(action.payload.activityTypes));
      }
    case STORE_DESTINATION:
      {
        return state.set('destination', new Destination(action.payload));
      }
    case UPDATE_WIDGET_STATUS:
      {
        return state.mergeIn(['status'], action.payload.status);
      }
    case RELOAD_WIDGET:
      {
        return state.setIn(['status', 'shouldReloadWidget'], false).set('destination', null).set('spaceDetails', null);
      }
    default:
      return state;
  }
}
const reducers = {
  ...reducers$1,
  ...reducers$2,
  ...reducers$3,
  errors: errors$1,
  features,
  users,
  mercury,
  media,
  spaces,
  widgetSpace: reducer
};

function _extends() {
  _extends = Object.assign ? Object.assign.bind() : 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 UNREGISTER_DEVICE_FAILURE = 'spark/UNREGISTER_DEVICE_FAILURE';
const UPDATE_SPARK_STATUS = 'spark/UPDATE_SPARK_STATUS';
function unregisterDeviceFailure(error) {
  return {
    type: UNREGISTER_DEVICE_FAILURE,
    payload: {
      error
    }
  };
}
function updateSparkStatus(status) {
  return {
    type: UPDATE_SPARK_STATUS,
    payload: {
      status
    }
  };
}
function unregisterDevice(spark) {
  return dispatch => {
    dispatch(updateSparkStatus({
      unregistering: true
    }));
    return spark.internal.device.unregister().then(() => dispatch(updateSparkStatus({
      unregistering: false,
      registered: false
    }))).catch(error => dispatch(unregisterDeviceFailure(error)));
  };
}

const propTypes$1 = {
  activityTypes: PropTypes.array.isRequired,
  onChange: PropTypes.func,
  onExit: PropTypes.func
};
const defaultProps$1 = {
  onChange: () => {},
  onExit: () => {}
};
function SpaceActivityMenu({
  activityTypes,
  onChange,
  onExit
}) {
  function handleChange(activity) {
    return () => onChange(activity);
  }
  const buttons = activityTypes.map(a => ({
    label: a.displayName,
    buttonClassName: a.buttonClassName,
    buttonType: a.buttonType,
    onClick: handleChange(a)
  }));
  return /*#__PURE__*/React.createElement(ActivityMenu, {
    buttons: buttons,
    onExit: onExit,
    showExitButton: true
  });
}
SpaceActivityMenu.propTypes = propTypes$1;
SpaceActivityMenu.defaultProps = defaultProps$1;

function styleInject(css, ref) {
  if (ref === void 0) ref = {};
  var insertAt = ref.insertAt;
  if (!css || typeof document === 'undefined') {
    return;
  }
  var head = document.head || document.getElementsByTagName('head')[0];
  var style = document.createElement('style');
  style.type = 'text/css';
  if (insertAt === 'top') {
    if (head.firstChild) {
      head.insertBefore(style, head.firstChild);
    } else {
      head.appendChild(style);
    }
  } else {
    head.appendChild(style);
  }
  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
}

var css_248z$1 = "$brand-font-folder: \"~@momentum-ui/core/fonts\";\n$icon-font-path: \"~@momentum-ui/icons/fonts\";\n\n@import '~@momentum-ui/core/scss/momentum-ui-components';\n";
styleInject(css_248z$1);

var css_248z = ".widget-space__spaceWidget__LnNwYWNl {\n  display: flex;\n  height: 100%;\n  overflow: hidden;\n  font-size: 16px;\n  font-weight: 200;\n  background: #fff;\n  box-sizing: border-box;\n  flex-direction: column;\n  flex: 1 1 auto;\n\n\n  /* IE 11 scrollbar styling workarounds */\n  scrollbar-face-color: #E0E0E0;\n  scrollbar-arrow-color: #E0E0E0;\n  scrollbar-shadow-color: white;\n  scrollbar-track-color: white;\n}\n\n.widget-space__activityComponentWrapper__LnNwYWNl {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  display: flex;\n  width: 100%;\n  height: 100%;\n  overflow: hidden;\n}\n\n.widget-space__activityComponentWrapper__LnNwYWNl > div {\n  display: flex;\n  width: inherit;\n}\n\n.widget-space__widgetBody__LnNwYWNl {\n  position: relative;\n  z-index: 10;\n  width: 100%;\n  flex: 1 1 auto;\n}\n\n.widget-space__hidden__LnNwYWNl {\n  visibility: hidden;\n}\n\n.widget-space__spaceWidget__LnNwYWNl .widget-space__messageButton__LnNwYWNl {\n  background-color: #07c1e4;\n}\n\n.widget-space__spaceWidget__LnNwYWNl .widget-space__meetButton__LnNwYWNl {\n  background-color: #30d557;\n}\n\n.widget-space__spaceWidget__LnNwYWNl .widget-space__peopleButton__LnNwYWNl {\n  background-color: #00d6a2;\n}\n\n.widget-space__spaceWidget__LnNwYWNl .widget-space__filesButton__LnNwYWNl {\n  background-color: #ffb400;\n}\n\n.widget-space__activityMenuButtonWrapper__LnNwYWNl {\n  padding: 0 16px;\n}\n\n.widget-space__tabContainer__LnNwYWNl {\n  display: grid;\n  grid-template-columns: repeat(3, auto) 1fr;\n  grid-template-areas:\n    'messages content people huddle';\n  gap: 8px;\n  border-block-end: .99px solid rgb(236, 236, 237);\n  height: 48px;\n  padding-left: 16px;\n  padding-right: 16px;\n}\n\n.widget-space__tabMeet__LnNwYWNl {\n  height: 100%;\n  place-self: end;\n  grid-area: huddle;\n  display: grid;\n  align-items: center;\n}\n\n#widget-space__huddle__LnNwYWNl {\n  background-color: #00853C;\n}\n\n#widget-space__huddle__LnNwYWNl:hover {\n  background-color: #03612C;\n}\n\n#widget-space__huddle__LnNwYWNl:active {\n  background-color: #08421F;\n}\n\n.widget-space__tabOther__LnNwYWNl {\n  background: transparent;\n  box-shadow: 0px 0px 0px transparent;\n  border: 0px solid transparent;\n  text-shadow: 0px 0px 0px transparent;\n  cursor: pointer;\n  font-size: 14px;\n  color: #545454;\n  font-family: 'CiscoSansTT Regular';\n  margin-block-start: 12px;\n  padding: 0px 8px;\n  width: fit-content;\n}\n\n.widget-space__tabOther__LnNwYWNl:disabled {\n  background: transparent;\n  box-shadow: 0px 0px 0px transparent;\n  text-shadow: 0px 0px 0px transparent;\n}\n\n.widget-space__tabActive__LnNwYWNl {\n  border-bottom: 2px solid #121212 !important;\n  border-block-end: 2px solid #121212;\n  margin-block-end: -2px;\n  color: #121212;\n}\n\n.widget-space__activityMenuButton__LnNwYWNl {\n  display: flex;\n}\n\n.widget-space__activityMenuWrapper__LnNwYWNl {\n  position: absolute;\n  top: 1px;\n  right: 1px;\n  z-index: 90;\n  width: 280px;\n  height: 100%;\n  overflow: hidden;\n  box-shadow: 0 2px 6px 2px rgba(0, 0, 0, 0.1);\n  animation: widget-space__slideIn__LnNwYWNl 350ms;\n}\n\n.widget-space__callTimer__LnNwYWNl {\n  margin-left: 10px;\n  font-size: 12px;\n  color: #858688;\n  display: none;\n}\n\n.widget-space__errorWrapper__LnNwYWNl {\n  position: absolute;\n  z-index: 100;\n  width: 100%;\n  height: 100%;\n}\n\n.widget-space__secondaryWidget__LnNwYWNl {\n  position: absolute;\n  top: 1px;\n  right: 1px;\n  z-index:  80;\n  height: 100%;\n  overflow: hidden;\n  background-color: #fff;\n  box-shadow: 0 2px 6px 2px rgba(0, 0, 0, 0.1);\n}\n\n.widget-space__secondaryWidgetCover__LnNwYWNl {\n  width: 280px;\n}\n\n.widget-space__secondaryWidgetFull__LnNwYWNl {\n  width: 100%;\n}\n\n.widget-space__secondaryWidget__LnNwYWNl > div {\n  height: 100%;\n}\n\n@keyframes widget-space__slideIn__LnNwYWNl {\n  from {\n    right: -50%;\n  }\n\n  to {\n    right: 0;\n  }\n}\n";
var styles = {"spaceWidget":"widget-space__spaceWidget__LnNwYWNl","activityComponentWrapper":"widget-space__activityComponentWrapper__LnNwYWNl","widgetBody":"widget-space__widgetBody__LnNwYWNl","hidden":"widget-space__hidden__LnNwYWNl","messageButton":"widget-space__messageButton__LnNwYWNl","meetButton":"widget-space__meetButton__LnNwYWNl","peopleButton":"widget-space__peopleButton__LnNwYWNl","filesButton":"widget-space__filesButton__LnNwYWNl","activityMenuButtonWrapper":"widget-space__activityMenuButtonWrapper__LnNwYWNl","tabContainer":"widget-space__tabContainer__LnNwYWNl","tabMeet":"widget-space__tabMeet__LnNwYWNl","huddle":"widget-space__huddle__LnNwYWNl","tabOther":"widget-space__tabOther__LnNwYWNl","tabActive":"widget-space__tabActive__LnNwYWNl","activityMenuButton":"widget-space__activityMenuButton__LnNwYWNl","activityMenuWrapper":"widget-space__activityMenuWrapper__LnNwYWNl","slideIn":"widget-space__slideIn__LnNwYWNl","callTimer":"widget-space__callTimer__LnNwYWNl","errorWrapper":"widget-space__errorWrapper__LnNwYWNl","secondaryWidget":"widget-space__secondaryWidget__LnNwYWNl","secondaryWidgetCover":"widget-space__secondaryWidgetCover__LnNwYWNl","secondaryWidgetFull":"widget-space__secondaryWidgetFull__LnNwYWNl"};
styleInject(css_248z);

// room and call events
const eventNames$1 = {
  SPACES_READ: 'rooms:read',
  SPACES_UNREAD: 'rooms:unread',
  MESSAGES_CREATED: 'messages:created',
  CALLS_CREATED: 'calls:created',
  CALLS_CONNECTED: 'calls:connected',
  CALLS_DISCONNECTED: 'calls:disconnected',
  CALL_MEMBERSHIPS_NOTIFIED: 'calls:memberships:notified',
  CALL_MEMBERSHIPS_CONNECTED: 'calls:memberships:connected',
  CALL_MEMBERSHIPS_DECLINED: 'calls:memberships:declined',
  CALL_MEMBERSHIPS_DISCONNECTED: 'calls:memberships:disconnected',
  ACTIVITY_CHANGED: 'activity:changed'
};
var events = {
  eventNames: eventNames$1
};

const ACTIVITY_TYPE_PRIMARY = 'ACTIVITY_TYPE_PRIMARY';
const ACTIVITY_TYPE_SECONDARY = 'ACTIVITY_TYPE_SECONDARY';
const DEFAULT_ACTIVITY = 'message';
const propTypes = {
  initialActivity: PropTypes.string
};

/**
 * Builds widget elements from activityTypes list
 *
 * @param {List} activityTypes Immutable List of activity types
 * @param {String} primaryActivityType Active activity type
 * @returns {Array} of Widget elements
 */

function constructActivityWidgets(props) {
  return (activityTypes, primaryActivityType, composerActions) => activityTypes.filter(activityType => activityType.type !== ACTIVITY_TYPE_SECONDARY).map(a => {
    // Only allow widget if it's available for this space type
    const Widget = a.component;
    const isVisible = primaryActivityType === a.name ? '' : styles.hidden;
    return /*#__PURE__*/React.createElement("div", {
      className: classNames(`webex-${a.name}-wrapper`, styles.activityComponentWrapper, isVisible),
      key: a.name
    }, /*#__PURE__*/React.createElement(Widget, _extends({}, props, {
      composerActions: composerActions,
      eventNames: eventNames$1,
      injectProvider: false,
      toPerson: props.spaceDetails.toPerson
    })));
  });
}

/**
 * Builds secondary widget elements
 *
 * @param {Object} props
 * @returns {Function}
 */
function constructSecondaryActivityWidget(props) {
  return (activityTypes, secondaryActivityType) => {
    if (!secondaryActivityType) {
      return null;
    }
    const secondaryWidgetClassNames = ['webex-secondary-widget', styles.secondaryWidget,
    // eslint-disable-next-line react/prop-types
    props.secondaryActivitiesFullWidth ? styles.secondaryWidgetFull : styles.secondaryWidgetCover];
    return activityTypes.filter(activityType => activityType.type === ACTIVITY_TYPE_SECONDARY && activityType.name === secondaryActivityType).map(activityType => {
      const Widget = activityType.component;
      return /*#__PURE__*/React.createElement("div", {
        className: classNames(secondaryWidgetClassNames),
        key: activityType.name
      }, /*#__PURE__*/React.createElement(Widget, _extends({}, props, activityType.props, {
        eventNames: eventNames$1,
        injectProvider: false
      })));
    });
  };
}
function handleActivityChange(props) {
  return activity => {
    if (activity.type === ACTIVITY_TYPE_PRIMARY) {
      props.updateActivityType(activity.name);
    } else {
      props.updateSecondaryActivityType(activity.name);
    }
    // Emit Event
    props.onEvent(eventNames$1.ACTIVITY_CHANGED, activity);
  };
}
function handleSecondaryDismiss(props) {
  return () => props.updateSecondaryActivityType(null);
}
function handleMenuClick(props) {
  return () => props.toggleActivityMenuVisible();
}
function getFeatureFlags(props) {
  const {
    widgetSpace,
    widgetStatus
  } = props;
  if (widgetStatus.get('hasFetchedFeatureFlags') || widgetStatus.get('isFetchingFeatureFlags')) {
    return;
  }
  props.updateWidgetStatus({
    isFetchingFeatureFlags: true
  });
  widgetSpace.get('activityTypes').toJS().forEach(activityType => {
    if (!activityType.feature) {
      return;
    }
    props.getFeature(activityType.feature.type, activityType.feature.key, props.sparkInstance);
  });
  props.updateWidgetStatus({
    hasFetchedFeatureFlags: true,
    isFetchingFeatureFlags: false
  });
}
var activityMenu = compose(connect(state => state, dispatch => bindActionCreators({
  getFeature,
  updateWidgetStatus,
  updateActivityType,
  storeActivityTypes,
  toggleActivityMenuVisible,
  updateSecondaryActivityType
}, dispatch)), setPropTypes(propTypes), withHandlers({
  handleSecondaryDismiss,
  handleMenuClick,
  handleActivityChange,
  constructActivityWidgets,
  constructSecondaryActivityWidget
}), lifecycle({
  componentWillMount() {
    const {
      props
    } = this;
    // Store activity types used in widget

    const DEFAULT_ACTIVITY_TYPES = [{
      displayName: 'Messages',
      name: 'message',
      buttonClassName: styles.messageButton,
      buttonType: 'chat',
      component: MessageWidget,
      spaceTypes: ['group', 'direct'],
      type: ACTIVITY_TYPE_PRIMARY
    }, {
      displayName: 'Content',
      name: 'files',
      buttonClassName: styles.filesButton,
      buttonType: 'files',
      component: FilesWidget,
      spaceTypes: ['direct', 'group'],
      type: ACTIVITY_TYPE_PRIMARY,
      props: {
        onClickClose: props.handleSecondaryDismiss,
        onClickMenu: props.handleMenuClick
      }
    }, {
      displayName: 'People',
      name: 'people',
      buttonClassName: styles.peopleButton,
      buttonType: {
        color: 'mint',
        icon: /*#__PURE__*/React.createElement(Icon, {
          name: "icon-people_28"
        })
      },
      component: RosterWidget,
      spaceTypes: ['direct', 'group'],
      type: ACTIVITY_TYPE_PRIMARY,
      props: {
        onClickClose: props.handleSecondaryDismiss,
        onClickMenu: props.handleMenuClick
      }
    }, {
      displayName: 'Call',
      name: 'meet',
      buttonClassName: styles.meetButton,
      buttonType: 'camera',
      component: MeetWidget,
      spaceTypes: ['direct', 'group'],
      type: ACTIVITY_TYPE_PRIMARY
    }];
    let activityTypes = DEFAULT_ACTIVITY_TYPES;
    if (typeof props.customActivityTypes === 'object') {
      activityTypes = activityTypes.concat(props.customActivityTypes);
    }
    props.storeActivityTypes(activityTypes);
  },
  componentWillReceiveProps(nextProps) {
    const {
      activityTypes,
      spaceDetails,
      sparkInstance,
      sparkState,
      initialActivity,
      call
    } = nextProps;
    const {
      props
    } = this;

    // Set the initial activity once we get space details
    if (sparkInstance && sparkState.get('authenticated') && sparkState.get('registered') && !sparkState.get('hasError')) {
      getFeatureFlags(nextProps);
    }
    if (!props.spaceDetails && spaceDetails) {
      if (activityTypes.find(a => a.name === initialActivity)) {
        props.updateActivityType(initialActivity);
      }
      // if default activity is available
      else if (activityTypes.find(a => a.name === DEFAULT_ACTIVITY)) {
        props.updateActivityType(DEFAULT_ACTIVITY);
      }
      // use first available activity in activity list
      else {
        props.updateActivityType(activityTypes[0].name);
      }
    }
    const prevCall = props.call;
    const hasMeet = activityTypes.some(activity => activity.name === 'meet');
    const hasMessage = activityTypes.some(activity => activity.name === 'message');

    // Switch to Meet if ringing
    if (hasMeet && call && !prevCall && !call.get('isDeclined')) {
      nextProps.updateActivityType('meet');
    }

    // Reset back to message view after call ends
    if (hasMessage && prevCall && !call) {
      nextProps.updateActivityType('message');
    }
  }
}));

function checkForMercuryErrors(props) {
  const {
    errors,
    intl,
    mercury
  } = props;
  // Add Mercury disconnect error
  const mercuryError = 'mercury.disconnect';
  const isMercuryConnected = mercury.getIn(['status', 'connected']);
  const isMercuryDisconnected = !isMercuryConnected && mercury.getIn(['status', 'hasConnected']);
  const hasError = errors.get('hasError');
  const hasMercuryError = errors.get('errors').has(mercuryError);
  const hasNoMercuryError = !hasError || !hasMercuryError;
  if (isMercuryDisconnected && hasNoMercuryError) {
    // Create UI Error
    const {
      formatMessage
    } = intl;
    props.addError({
      id: mercuryError,
      displayTitle: formatMessage(messages$1.errorConnection),
      displaySubtitle: formatMessage(messages$1.reconnecting),
      temporary: true
    });
  }
  if (isMercuryConnected && hasMercuryError) {
    props.removeError(mercuryError);
  }
}

/**
 * Checks for SDK device registration errors
 * @param {Object} props
 */
function checkForRegistrationErrors(props) {
  const {
    errors,
    sparkState,
    spark
  } = props;
  const {
    formatMessage
  } = props.intl;
  const registerErrorId = 'spark.register';
  if (sparkState.get('registerError') && (!errors.get('hasError') || !errors.get('errors').has(registerErrorId))) {
    const error = spark.get('error');
    let displaySubtitle = formatMessage(messages$1.unknownError);
    if (error.statusCode === 401) {
      displaySubtitle = formatMessage(messages$1.errorBadToken);
    }
    props.addError({
      id: registerErrorId,
      displayTitle: formatMessage(messages$1.unableToLoad),
      displaySubtitle,
      temporary: false,
      code: error.statusCode
    });
  }
}

/**
 * Verifies the destination provided is valid
 * @param {Object} props
 */
function checkForDestinationErrors(props) {
  const {
    currentUser,
    destination,
    destinationId,
    destinationType,
    errors
  } = props;
  const {
    formatMessage
  } = props.intl;

  // Destination type and id are required
  const missingDestinationErrorId = 'space.error.missingDestination';
  if (!destinationId && !destinationType && (!errors.get('hasError') || !errors.get('errors').has(missingDestinationErrorId))) {
    // No destination found
    props.addError({
      id: missingDestinationErrorId,
      displayTitle: formatMessage(messages$1.unableToLoad),
      displaySubtitle: formatMessage(messages$1.unknownDestination),
      temporary: false
    });
  }

  // Cannot start a space with yourself
  const toSelfErrorId = 'space.error.toSelf';
  if (destination && currentUser && currentUser.id && currentUser.email && (!errors.get('hasError') || !errors.get('errors').has(toSelfErrorId))) {
    // Check for to user being self
    if (destination.type === destinationTypes.EMAIL && currentUser.email === destination.id || destination.type === destinationTypes.USERID && validateAndDecodeId(destination.id).id === currentUser.id) {
      props.addError({
        id: toSelfErrorId,
        displayTitle: formatMessage(messages$1.unableToLoad),
        displaySubtitle: formatMessage(messages$1.errorToSelf),
        temporary: false
      });
    }
  }

  // Cannot start a space to a UUID destination ID
  const invalidDestinationErrorId = 'space.error.invalidDestination';
  if (destinationId && isUuid(destinationId) && (!errors.get('hasError') || !errors.get('errors').has(invalidDestinationErrorId))) {
    // No destination found
    props.addError({
      id: invalidDestinationErrorId,
      displayTitle: formatMessage(messages$1.unableToLoad),
      displaySubtitle: formatMessage(messages$1.invalidDestination),
      temporary: false
    });
  }
}

/**
 * Verifies the prop based activity types are valid
 * @param {Object} props
 */
function checkActivityTypes(props) {
  const {
    activityTypes,
    errors,
    initialActivity
  } = props;
  const {
    formatMessage
  } = props.intl;
  if (activityTypes && activityTypes.length > 0) {
    const invalidActivityId = 'ciscospark.container.space.error.invalidActivity';
    const defaultActivity = 'message';
    let validActivity = false;
    if (activityTypes.some(activity => activity.name === initialActivity) || activityTypes.some(activity => activity.name === defaultActivity) || activityTypes[0] && activityTypes[0].name && activityTypes[0].type === ACTIVITY_TYPE_PRIMARY) {
      validActivity = true;
    }
    if (!validActivity && !errors.get('errors').has(invalidActivityId)) {
      props.addError({
        id: invalidActivityId,
        displayTitle: formatMessage(messages$1.disabledInitialActivity),
        temporary: false
      });
    }
    if (validActivity && errors.get('errors').has(invalidActivityId)) {
      props.removeError(invalidActivityId);
    }
  }
}

/**
 * Verifies the prop based messaging options are valid
 * @param {Object} props
 */
function checkCanSendMessage(props) {
  const {
    activityTypes,
    errors,
    showSubmitButton,
    sendMessageOnReturnKey
  } = props;
  const {
    formatMessage
  } = props.intl;
  const defaultActivity = 'message';
  if (activityTypes && activityTypes.length > 0) {
    const invalidMessagingId = 'ciscospark.container.space.error.invalidSendMessageConfiguration';
    const hasEnabledMessaging = activityTypes.some(activity => activity.name === defaultActivity);
    const hasErrorCurrently = errors.get('errors').has(invalidMessagingId);
    if (hasEnabledMessaging && !showSubmitButton && !sendMessageOnReturnKey && !hasErrorCurrently) {
      props.addError({
        id: invalidMessagingId,
        displayTitle: formatMessage(messages$1.invalidSendMessageConfiguration),
        temporary: false
      });
    }
    if (hasEnabledMessaging && (showSubmitButton || sendMessageOnReturnKey) && hasErrorCurrently) {
      props.removeError(invalidMessagingId);
    }
  }
}
function checkForErrors(props) {
  checkForMercuryErrors(props);
  checkForRegistrationErrors(props);
  checkForDestinationErrors(props);
  checkActivityTypes(props);
  checkCanSendMessage(props);
}
var errors = compose(connect(state => state, dispatch => bindActionCreators({
  addError,
  removeError
}, dispatch)), lifecycle({
  componentWillMount() {
    checkForErrors(this.props);
  },
  componentWillReceiveProps: nextProps => {
    checkForErrors(nextProps);
  }
}));

const getWidget = state => state.widgetSpace;
const getSpark = state => state.spark;
const getMedia = state => state.media;
const getConversation = state => state.conversation;
const getFeatures = state => state.features;
const getUsers = state => state.users;
const getSpaces = state => state.spaces;
const getOwnProps = (state, ownProps) => ownProps;
const getMercuryStatus = state => state.mercury.get('status');
const getCall = createSelector([getConversation, getMedia, getWidget, getOwnProps], (conversation, media, widget, ownProps) => {
  if (ownProps && ownProps.call && typeof ownProps.call === 'object' && ownProps.call.id) {
    return ownProps.call;
  }
  let mediaId;

  // Conversation is the easiest way to get a media id
  if (conversation.has('locusUrl')) {
    mediaId = media.getIn(['byLocusUrl', conversation.get('locusUrl')]);
  } else {
    const destination = widget.get('destination');
    if (!destination) {
      return null;
    }
    mediaId = media.getIn(['byDestination', destination.id]);

    // Incoming call
    if (!mediaId && [destinationTypes.SIP, destinationTypes.PSTN].includes(destination.type)) {
      // This is a bit of a hack. We're matching on the string, but this can
      // cause ambiguity if the phone numbers are too close.
      const matchedCall = media.get('byId').find(call => {
        if (call && call.has('instance')) {
          const {
            locus
          } = call.get('instance');
          if (locus && locus.host) {
            if (destination.type === destinationTypes.PSTN && locus.host.phoneNumber) {
              if (destination.id.startsWith('+')) {
                return locus.host.phoneNumber === destination.id;
              }
              return locus.host.phoneNumber.includes(destination.id);
            }
            if (locus.info && locus.info.sipUri) {
              return locus.info.sipUri.includes(destination.id);
            }
          }
        }
        return false;
      });
      if (matchedCall) {
        mediaId = media.getIn(['byLocusUrl', matchedCall.get('instance').locusUrl]);
      }
    }
  }
  const call = media.getIn(['byId', mediaId]);
  if (call && call.isDismissed) {
    return null;
  }
  return call;
});
const getCurrentActivity = createSelector([getWidget, getFeatures, getOwnProps], widget => {
  if (widget.get('secondaryActivityType')) return widget.get('secondaryActivityType');
  return widget.get('primaryActivityType');
});

/**
 * Builds a space details object from store + calculated title & avatarid
 */
const getSpaceDetails = createSelector([getWidget, getUsers, getSpaces, getCall], (widget, users, spaces, call) => {
  if (!widget.get('spaceDetails')) {
    return null;
  }
  const spaceDetails = widget.get('spaceDetails').toJS();
  const destination = widget.get('destination');
  if (!destination) {
    return spaceDetails;
  }
  const {
    id,
    type
  } = destination;
  let avatarId, displayName;
  switch (type) {
    case destinationTypes.SIP:
    case destinationTypes.PSTN:
      {
        var _call$locusInfo, _call$locusInfo$self;
        if (call !== null && call !== void 0 && (_call$locusInfo = call.locusInfo) !== null && _call$locusInfo !== void 0 && (_call$locusInfo$self = _call$locusInfo.self) !== null && _call$locusInfo$self !== void 0 && _call$locusInfo$self.displayInfo) {
          displayName = call.locusInfo.self.displayInfo.primaryDisplayName;
        } else {
          displayName = id;
        }
        break;
      }
    case destinationTypes.EMAIL:
      {
        avatarId = users.getIn(['byEmail', id]);
        displayName = users.getIn(['byId', avatarId, 'displayName']);
        break;
      }
    case destinationTypes.USERID:
      {
        const {
          id: userId
        } = validateAndDecodeId(id);
        displayName = users.getIn(['byId', userId, 'displayName']);
        avatarId = userId;
        break;
      }
    case destinationTypes.SPACEID:
      if (spaceDetails.type === 'direct') {
        const currentUserId = users.get('currentUserId');
        const toUser = users.get('byId').find(u => u.get('id') !== currentUserId);
        displayName = spaceDetails.title;
        if (toUser) {
          avatarId = toUser.get('id');
        }
      } else {
        const {
          id: tempId
        } = validateAndDecodeId(id);
        displayName = spaces.getIn(['byId', tempId, 'displayName']);
        avatarId = tempId;
      }
      break;
    default:
      displayName = null;
  }
  spaceDetails.avatarId = avatarId;
  spaceDetails.title = displayName;
  return spaceDetails;
});
const getActivityTypes = createSelector([getWidget, getFeatures, getOwnProps], (widget, features, ownProps) => {
  const {
    spaceActivities,
    call
  } = ownProps;
  const destination = widget.get('destination');
  const spaceType = widget.getIn(['spaceDetails', 'type']);
  const filteredActivityTypes = [];
  let activityTypes = widget.get('activityTypes').toJS();
  if (spaceActivities) {
    activityTypes = activityTypes.filter(a => spaceActivities[a.name] !== false);
  }
  activityTypes.forEach(activityType => {
    let isValid = true;

    // Filter activity Type based on spaceType
    if (spaceType && !activityType.spaceTypes.includes(spaceType)) {
      isValid = false;
    }
    // Filter activity type based on feature requirement
    if (activityType.feature && !activityType.feature.hide && !features.getIn(['items', activityType.feature.key])) {
      isValid = false;
    }
    // Hide flag on feature means to hide activity if feature is enabled
    if (activityType.feature && activityType.feature.hide && features.getIn(['items', activityType.feature.key])) {
      isValid = false;
    }
    // Filter based on destination type
    if (destination && destination.type && ([destinationTypes.SIP, destinationTypes.PSTN].includes(destination.type) || call) && ['message', 'files'].includes(activityType.name)) {
      isValid = false;
    }
    if (isValid) {
      filteredActivityTypes.push(activityType);
    }
  });
  return filteredActivityTypes;
});
const getSubmitOptions = createSelector([getOwnProps], ownProps => {
  const {
    showSubmitButton = false,
    sendMessageOnReturnKey = true
  } = ownProps;
  return {
    showSubmitButton,
    sendMessageOnReturnKey
  };
});
const getSpaceWidgetProps = createSelector([getWidget, getSpark, getMedia, getSpaceDetails, getActivityTypes, getCall, getMercuryStatus, getCurrentActivity, getSubmitOptions], (widget, spark, media, spaceDetails, activityTypes, call, mercuryStatus, currentActivity, {
  showSubmitButton,
  sendMessageOnReturnKey
}) => ({
  activityTypes,
  destination: widget.get('destination'),
  media,
  mercuryStatus: mercuryStatus.toJS(),
  sparkInstance: spark.get('spark'),
  sparkState: spark.get('status'),
  spaceDetails,
  widgetStatus: widget.get('status'),
  call,
  currentActivity,
  showSubmitButton,
  sendMessageOnReturnKey
}));

function setup(props, prevProps = {}) {
  const {
    conversation,
    destination,
    errors,
    sparkInstance,
    sparkState,
    spaceDetails,
    widgetStatus,
    mercuryStatus,
    users,
    spaces
  } = props;
  if (sparkInstance && sparkState.authenticated && sparkState.registered && !sparkState.hasError) {
    // Check if we need to reload space
    if (widgetStatus.shouldReloadWidget && prevProps && !prevProps.widgetStatus.shouldReloadWidget) {
      props.resetConversation();
      props.reloadWidget();
      props.resetErrors();
    }

    // Check for destination Change
    if (destination && prevProps.destination) {
      const previousDestination = prevProps.destination;
      if (destination.id !== previousDestination.id || destination.type !== previousDestination.type) {
        sparkInstance.logger.info('Destination has changed, widget reloading...');
        props.updateWidgetStatus({
          shouldReloadWidget: true
        });
      }
    }

    // Connect to websocket (mercury)
    if (!mercuryStatus.hasConnected && !mercuryStatus.connecting && !mercuryStatus.connected && sparkState.registered) {
      props.connectToMercury(sparkInstance);
    }

    // Get space details for given destination
    // Get space details for given destination
    if (!widgetStatus.isFetchingSpaceDetails && !errors.get('hasError') && !spaceDetails) {
      // If the selector isn't returning a destination object and we have props for them, store
      if (destination) {
        // Use destination object from store to fetch space details
        props.getSpaceDetails({
          sparkInstance,
          destinationId: destination.id,
          destinationType: destination.type,
          intl: props.intl
        });
        // Fetch 1:1 User details
        if (destination.type === destinationTypes.EMAIL && !users.getIn(['byEmail', destination.id])) {
          props.getUser({
            email: destination.id
          }, sparkInstance);
        }
        if (destination.type === destinationTypes.USERID && !users.getIn(['byId', destination.id])) {
          props.getUser({
            id: destination.id
          }, sparkInstance);
        }
        if (destination.type === destinationTypes.SPACEID && !spaces.getIn(['byId', validateAndDecodeId(destination.id).id])) {
          props.fetchSpace(sparkInstance, validateAndDecodeId(destination.id));
        }
      } else {
        // Destination has not been stored yet, process and store.
        const {
          destinationId,
          destinationType
        } = props;
        let cluster;
        let id = destinationId;
        if (destinationType === destinationTypes.EMAIL && destinationId) {
          id = destinationId.toLowerCase();
        } else if (destinationType === destinationTypes.SPACEID && destinationId) {
          ({
            cluster
          } = deconstructHydraId(destinationId));
        }
        props.storeDestination({
          id,
          type: destinationType,
          // Add cluster if cluster information exists
          ...(cluster && {
            cluster
          })
        });
      }
    }
    if (conversation.get('id')) {
      props.fetchAvatar({
        space: conversation.toJS()
      }, sparkInstance);
    }
  }
}
var setup$1 = compose(connect(getSpaceWidgetProps, dispatch => bindActionCreators({
  connectToMercury,
  fetchSpace,
  getUser,
  getSpaceDetails: getSpaceDetails$1,
  reloadWidget,
  resetConversation,
  resetErrors,
  storeDestination,
  updateWidgetStatus,
  fetchAvatar
}, dispatch)), lifecycle({
  componentWillMount() {
    setup(this.props);
  },
  shouldComponentUpdate(nextProps) {
    return nextProps !== this.props;
  },
  componentWillReceiveProps(nextProps) {
    setup(nextProps, this.props);
  }
}));

function changeCurrentActivity(props) {
  const {
    activityTypes,
    setCurrentActivity
  } = props;

  // Check if activity is valid
  const toActivity = activityTypes.find(activity => activity.name === setCurrentActivity);
  if (toActivity) {
    if (toActivity.type === ACTIVITY_TYPE_PRIMARY) {
      props.updateActivityType(setCurrentActivity);
    }
    if (toActivity.type === ACTIVITY_TYPE_SECONDARY) {
      // Secondary activities need to have the menu opened
      props.updateSecondaryActivityType(setCurrentActivity);
    }
    // Emit Event
    props.onEvent(eventNames$1.ACTIVITY_CHANGED, toActivity);
  }
}
function checkForExternalTrigger(nextProps, currentProps) {
  const {
    setCurrentActivity
  } = nextProps;

  // Change Current Activity
  if (setCurrentActivity && setCurrentActivity !== currentProps.setCurrentActivity) {
    changeCurrentActivity(nextProps);
  }
}
var externalControl = compose(connect(state => state, dispatch => bindActionCreators({
  addError,
  removeError
}, dispatch)), lifecycle({
  componentWillReceiveProps(nextProps) {
    checkForExternalTrigger(nextProps, this.props);
  }
}));

var enhancers = [setup$1, errors, activityMenu, externalControl];

const injectedPropTypes = {
  activityTypes: PropTypes.array.isRequired,
  call: PropTypes.object,
  conversation: PropTypes.object.isRequired,
  currentActivity: PropTypes.string,
  errors: PropTypes.object.isRequired,
  sparkInstance: PropTypes.object,
  widgetSpace: PropTypes.object.isRequired
};
const ownPropTypes = {
  composerActions: PropTypes.shape({
    attachFiles: PropTypes.bool
  }),
  customActivityTypes: PropTypes.object,
  destinationId: PropTypes.string,
  destinationType: PropTypes.oneOf(['email', 'userId', 'spaceId', 'sip', 'pstn']),
  muteNotifications: PropTypes.bool,
  secondaryActivitiesFullWidth: PropTypes.bool,
  setCurrentActivity: PropTypes.string,
  spaceActivities: PropTypes.shape({
    files: PropTypes.bool,
    meet: PropTypes.bool,
    message: PropTypes.bool,
    people: PropTypes.bool
  }),
  startCall: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
  disablePresence: PropTypes.bool,
  disableFlags: PropTypes.bool,
  showSubmitButton: PropTypes.bool,
  sendMessageOnReturnKey: PropTypes.bool,
  ...propTypes,
  ...injectedPropTypes
};
const defaultProps = {
  composerActions: {
    attachFiles: true
  },
  customActivityTypes: undefined,
  destinationId: null,
  destinationType: null,
  muteNotifications: false,
  secondaryActivitiesFullWidth: true,
  setCurrentActivity: '',
  spaceActivities: {
    files: true,
    meet: true,
    message: true,
    people: true
  },
  startCall: false,
  disablePresence: false,
  disableFlags: false,
  showSubmitButton: false,
  sendMessageOnReturnKey: true
};
class SpaceWidget extends Component {
  componentWillUnmount() {
    const {
      sparkInstance
    } = this.props;

    // Make sure we unregister device when unmouting this component
    this.props.unregisterDevice(sparkInstance);
  }
  handleTabKeyDown = (e, index, visibleTabs) => {
    const {
      key
    } = e;
    const allTabs = document.querySelectorAll('[role="tab"]');
    const meetButton = document.querySelector('.webex-tab-meet button'); // meet button element

    switch (key) {
      case 'ArrowRight':
        {
          e.preventDefault();

          // If last tab (People) → go to Meet button
          if (index === visibleTabs.length - 1 && meetButton) {
            meetButton.focus();
          } else {
            const next = (index + 1) % visibleTabs.length;
            allTabs[next].focus();
          }
          break;
        }
      case 'ArrowLeft':
        {
          e.preventDefault();

          // If focus is currently on Meet button → move to last tab (People)
          if (document.activeElement === meetButton) {
            allTabs[visibleTabs.length - 1].focus();
          } else {
            const prev = (index - 1 + visibleTabs.length) % visibleTabs.length;
            allTabs[prev].focus();
          }
          break;
        }
      case 'Home':
        {
          e.preventDefault();
          allTabs[0].focus();
          break;
        }
      case 'End':
        {
          e.preventDefault();
          // End should go to Meet button if present, else last tab
          if (meetButton) {
            meetButton.focus();
          } else {
            allTabs[visibleTabs.length - 1].focus();
          }
          break;
        }
      case ' ':
      case 'Enter':
        {
          e.preventDefault();
          this.props.handleActivityChange(visibleTabs[index]);
          break;
        }
    }
  };
  handleMeetKeyDown = e => {
    const allTabs = document.querySelectorAll('[role="tab"]');
    switch (e.key) {
      case 'ArrowLeft':
        {
          e.preventDefault();
          // Move focus back to last tab (People)
          allTabs[allTabs.length - 1].focus();
          break;
        }
      case 'Home':
        {
          e.preventDefault();
          allTabs[0].focus();
          break;
        }
      case 'End':
        {
          e.preventDefault();
          // Stay on Meet (already focused)
          e.currentTarget.focus();
          break;
        }
    }
  };
  render() {
    const {
      props
    } = this;
    const {
      activityTypes,
      call,
      conversation,
      currentActivity,
      composerActions,
      sparkInstance,
      spaceDetails,
      errors,
      widgetSpace,
      widgetStatus
    } = props;
    const {
      formatMessage
    } = props.intl;
    let errorElement;
    if (errors.get('hasError') || conversation.getIn(['status', 'error'])) {
      let widgetError = errors.get('errors').first();
      if (!widgetError) {
        widgetError = {
          displaySubtitle: conversation.getIn(['status', 'error', 'description']),
          temporary: false,
          title: formatMessage(messages$1.errorConversation)
        };
      }
      errorElement = /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-error-wrapper', styles.errorWrapper)
      }, /*#__PURE__*/React.createElement(ErrorDisplay, _extends({
        secondaryTitle: widgetError.displaySubtitle,
        title: widgetError.displayTitle,
        transparent: widgetError.temporary
      }, widgetError)));
    }
    if (sparkInstance && spaceDetails) {
      // Construct widgets
      const primaryActivityType = widgetSpace.get('primaryActivityType');
      const secondaryActivityType = widgetSpace.get('secondaryActivityType');
      const widgets = props.constructActivityWidgets(activityTypes, primaryActivityType, composerActions);
      const secondaryWidget = props.constructSecondaryActivityWidget(activityTypes, secondaryActivityType);
      const {
        avatarId,
        title = 'Loading...'
      } = spaceDetails;
      const callStartTime = (call === null || call === void 0 ? void 0 : call.activeParticipantsCount) > 0 ? call === null || call === void 0 ? void 0 : call.startTime : null;
      let menuButton;
      const {
        preferredWebexSite
      } = sparkInstance.meetings;
      let isMeetButtonDisabled = false;
      if (props.destinationType === 'spaceId' && activityTypes.some(activity => activity.name === 'meet')) {
        isMeetButtonDisabled = !preferredWebexSite;
      }
      const errorElementSpace = /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-error-wrapper', styles.errorWrapper)
      }, /*#__PURE__*/React.createElement(ErrorDisplay, {
        transparent: false,
        title: formatMessage(messages$1.noAbilityToStartMeeting)
      }));
      if (activityTypes) {
        menuButton = [];
        activityTypes.filter(at => at.name);
        const visibleTabs = activityTypes.filter(at => at.name !== 'meet');
        const totalTabs = visibleTabs.length;
        activityTypes.forEach(at => {
          const tabActive = currentActivity === at.name;
          if (at.name === 'meet') {
            menuButton.push( /*#__PURE__*/React.createElement("span", {
              key: at.name,
              className: classNames(`webex-tab-${at.name}`, styles.tabMeet),
              title: isMeetButtonDisabled ? formatMessage(messages$1.noAbilityToStartMeeting) : ''
            }, /*#__PURE__*/React.createElement(Button, {
              role: "button",
              ariaLabel: at.displayName,
              circle: !call,
              id: styles.huddle,
              color: "green",
              size: 25,
              disabled: isMeetButtonDisabled,
              onClick: () => this.props.handleActivityChange(at),
              onKeyDown: this.handleMeetKeyDown
            }, /*#__PURE__*/React.createElement(Icon, {
              name: `icon-${at.buttonType}_16`,
              style: {
                paddingRight: callStartTime ? '0.5rem' : 'inherit'
              }
            }), callStartTime && /*#__PURE__*/React.createElement(Timer, {
              startTime: callStartTime
            }))));
          } else {
            const tabIndexInList = visibleTabs.findIndex(vt => vt.name === at.name);
            menuButton.push( /*#__PURE__*/React.createElement("button", {
              key: at.name,
              role: "tab",
              "aria-selected": tabActive,
              "aria-posinset": tabIndexInList + 1,
              "aria-setsize": totalTabs,
              tabIndex: 0,
              "aria-label": at.displayName,
              onClick: () => this.props.handleActivityChange(at),
              onKeyDown: e => this.handleTabKeyDown(e, tabIndexInList, visibleTabs),
              className: classNames(`webex-tab-${at.name}`, styles.tabOther, {
                [styles.tabActive]: tabActive
              })
            }, at.displayName));
          }
        });
      }
      return /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-space-widget', 'md', styles.spaceWidget)
      }, errorElement, widgetStatus.get('activityMenuVisible') && /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-activity-menu-wrapper', styles.activityMenuWrapper)
      }, /*#__PURE__*/React.createElement(SpaceActivityMenu, {
        activityTypes: activityTypes,
        onChange: props.handleActivityChange,
        onExit: props.handleMenuClick,
        showExitButton: true
      })), secondaryWidget, /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-title-bar-wrapper', styles.titleBarWrapper)
      }, /*#__PURE__*/React.createElement(TitleBar, {
        avatarId: avatarId,
        name: title,
        type: spaceDetails.type
      }, callStartTime && /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-title-bar-call-timer', styles.callTimer)
      }, /*#__PURE__*/React.createElement(Timer, {
        startTime: callStartTime
      })))), /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-tabs', styles.tabContainer),
        role: "tablist",
        "aria-label": "Space Widget"
      }, menuButton), /*#__PURE__*/React.createElement("div", {
        className: classNames('webex-widget-body', styles.widgetBody)
      }, isMeetButtonDisabled && currentActivity === 'meet' ? errorElementSpace : widgets));
    }
    if (errors.get('hasError')) {
      return errorElement;
    }
    return /*#__PURE__*/React.createElement(LoadingScreen, null);
  }
}
SpaceWidget.propTypes = ownPropTypes;
SpaceWidget.defaultProps = defaultProps;
var ConnectedSpace = compose(connect(null, dispatch => bindActionCreators({
  storeDestination,
  unregisterDevice
}, dispatch)), ...enhancers)(SpaceWidget);

var messages = {};

const {
  eventNames
} = events;
var index = compose(constructWebexEnhancer({
  name: 'space',
  reducers
}), enhancer, withIntl({
  locale: 'en',
  messages
}))(ConnectedSpace);

export { index as default, destinationTypes, eventNames, reducers };
//# sourceMappingURL=index.js.map
