"use strict";

require("core-js/modules/es.symbol.js");
require("core-js/modules/es.array.for-each.js");
require("core-js/modules/es.array.push.js");
require("core-js/modules/es.object.define-properties.js");
require("core-js/modules/es.object.define-property.js");
require("core-js/modules/es.object.get-own-property-descriptor.js");
require("core-js/modules/es.object.get-own-property-descriptors.js");
require("core-js/modules/es.object.keys.js");
require("core-js/modules/esnext.iterator.for-each.js");
require("core-js/modules/web.dom-collections.for-each.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PARTICIPANT_LIST_FOOTER = exports.PARTICIPANT_LIST_DIVIDER = exports.FcrParticipants = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
require("core-js/modules/es.array.concat.js");
require("core-js/modules/es.array.filter.js");
require("core-js/modules/es.array.find.js");
require("core-js/modules/es.array.includes.js");
require("core-js/modules/es.array.index-of.js");
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.array.some.js");
require("core-js/modules/es.array.sort.js");
require("core-js/modules/es.map.js");
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/esnext.iterator.constructor.js");
require("core-js/modules/esnext.iterator.filter.js");
require("core-js/modules/esnext.iterator.find.js");
require("core-js/modules/esnext.iterator.some.js");
require("core-js/modules/esnext.map.delete-all.js");
require("core-js/modules/esnext.map.emplace.js");
require("core-js/modules/esnext.map.every.js");
require("core-js/modules/esnext.map.filter.js");
require("core-js/modules/esnext.map.find.js");
require("core-js/modules/esnext.map.find-key.js");
require("core-js/modules/esnext.map.includes.js");
require("core-js/modules/esnext.map.key-of.js");
require("core-js/modules/esnext.map.map-keys.js");
require("core-js/modules/esnext.map.map-values.js");
require("core-js/modules/esnext.map.merge.js");
require("core-js/modules/esnext.map.reduce.js");
require("core-js/modules/esnext.map.some.js");
require("core-js/modules/esnext.map.update.js");
require("core-js/modules/web.dom-collections.iterator.js");
var _button = require("../button");
var _reactVirtualized = require("react-virtualized");
var _input = require("../input");
var _attendee = require("./attendee");
var _icon = require("../icon");
var _type = require("../icon/type");
var _react = require("react");
var _i18n = require("../../i18n");
var _tabs = require("../tabs");
require("./index.css");
var _jsxRuntime = require("react/jsx-runtime");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } /** Roles that appear in the "host/guest" tab (host, co-host, participant) */
var ROLES_IN_HOST_TAB = [_attendee.FcrUserRole.HOST, _attendee.FcrUserRole.COHOST, _attendee.FcrUserRole.PARTICIPANT];

/** User is in host/guest tab (host, co-host, participant). */
var isInHostTab = function isInHostTab(u) {
  return u.isHost || u.userRole != null && ROLES_IN_HOST_TAB.includes(u.userRole);
};
var isInAudienceTab = function isInAudienceTab(u) {
  return !isInHostTab(u);
};
/** Sentinel for a divider row in the list (e.g. between "me" and host/guest when viewer is audience) */
var PARTICIPANT_LIST_DIVIDER = exports.PARTICIPANT_LIST_DIVIDER = {
  _divider: true
};
var PARTICIPANT_LIST_FOOTER = exports.PARTICIPANT_LIST_FOOTER = {
  _footer: true
};
function isDivider(item) {
  return item._divider === true;
}
function isFooter(item) {
  return item._footer === true;
}

/** raiseHandUserList 项来自业务层（如 FcrUserInfo）；用于排序时取 userId */
function raiseHandListItemUserId(item) {
  if (item && (0, _typeof2["default"])(item) === 'object' && 'userId' in item) {
    var id = item.userId;
    return typeof id === 'string' ? id : null;
  }
  return null;
}

/** 观众列表：raiseHandUserList 中越靠后的用户越靠前展示（最近举手在上） */
function sortAudienceByRaiseHandOrder(audience, raiseHandUserList, userList) {
  var rh = raiseHandUserList;
  if (!(rh !== null && rh !== void 0 && rh.length)) return audience;
  var raiseOrder = new Map();
  var rank = 0;
  for (var i = rh.length - 1; i >= 0; i--) {
    var userId = raiseHandListItemUserId(rh[i]);
    if (userId != null && !raiseOrder.has(userId)) {
      raiseOrder.set(userId, rank++);
    }
  }
  return (0, _toConsumableArray2["default"])(audience).sort(function (a, b) {
    var ra = raiseOrder.get(a.userId);
    var rb = raiseOrder.get(b.userId);
    if (ra !== undefined && rb !== undefined) return ra - rb;
    if (ra !== undefined) return -1;
    if (rb !== undefined) return 1;
    return userList.indexOf(a) - userList.indexOf(b);
  });
}
var cache = new _reactVirtualized.CellMeasurerCache({
  fixedWidth: true,
  defaultHeight: 52
});
var DIVIDER_ROW_HEIGHT = 28;
var userRowRenderer = function userRowRenderer(displayList, userRenderer, hasPinnedStream, toggleParticipantAction, isLocalCameraInSecondaryWindow, dividerLabel, footLabel) {
  return function (renderProps) {
    var key = renderProps.key,
      parent = renderProps.parent,
      index = renderProps.index,
      style = renderProps.style;
    var item = displayList[index];
    if (isDivider(item)) {
      return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        style: _objectSpread(_objectSpread({}, style), {}, {
          height: DIVIDER_ROW_HEIGHT
        }),
        className: "fcr-participant__list-divider",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "fcr-participant__list-divider-label",
          children: dividerLabel
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "fcr-participant__list-divider-line"
        })]
      }, key);
    }
    if (isFooter(item)) {
      if (footLabel) {
        return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          style: _objectSpread({}, style),
          className: "fcr-participant__list-footer",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
            className: "fcr-participant__list-footer-label",
            children: footLabel
          })
        }, key);
      }
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactVirtualized.CellMeasurer, {
      cache: cache,
      parent: parent,
      columnIndex: 0,
      rowIndex: index,
      children: function children(_ref) {
        var measure = _ref.measure;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          style: _objectSpread(_objectSpread({}, style), {}, {
            pointerEvents: 'all'
          }),
          onLoad: measure,
          children: userRenderer ? userRenderer(item) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_attendee.FcrParticipant, {
            hasPinnedStream: hasPinnedStream,
            user: item,
            onParticipantsButtonClick: toggleParticipantAction,
            isLocalCameraInSecondaryWindow: isLocalCameraInSecondaryWindow
          })
        });
      }
    }, key);
  };
};
var FcrParticipants = exports.FcrParticipants = function FcrParticipants(props) {
  var _raiseHandUserList$le, _raiseHandUserList$le2;
  var _props = _objectSpread({}, props),
    searchText = _props.searchText,
    onSearch = _props.onSearch,
    userList = _props.userList,
    userRenderer = _props.userRenderer,
    onInvite = _props.onInvite,
    hasPinnedStream = _props.hasPinnedStream,
    toggleParticipantAction = _props.toggleParticipantAction,
    toggleRoomControlAction = _props.toggleRoomControlAction,
    isLocalCameraInSecondaryWindow = _props.isLocalCameraInSecondaryWindow,
    _props$hasInvite = _props.hasInvite,
    hasInvite = _props$hasInvite === void 0 ? true : _props$hasInvite,
    footer = _props.footer,
    header = _props.header,
    applicationApplyingTips = _props.applicationApplyingTips,
    emptyContent = _props.emptyContent,
    _props$showParticipan = _props.showParticipantListTab,
    showParticipantListTab = _props$showParticipan === void 0 ? false : _props$showParticipan,
    controlledTab = _props.participantListTab,
    onParticipantListTabChange = _props.onParticipantListTabChange,
    audienceCountFromRoom = _props.audienceCountFromRoom,
    raiseHandUserList = _props.raiseHandUserList,
    _props$showParticipan2 = _props.showParticipantListCounts,
    showParticipantListCounts = _props$showParticipan2 === void 0 ? true : _props$showParticipan2;
  var _useState = (0, _react.useState)((0, _react.useMemo)(function () {
      return searchText || '';
    }, [searchText])),
    _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
    value = _useState2[0],
    setValue = _useState2[1];
  var _useState3 = (0, _react.useState)('host'),
    _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
    internalTab = _useState4[0],
    setInternalTab = _useState4[1];
  var isTabControlled = controlledTab !== undefined;
  var participantListTab = isTabControlled ? controlledTab : internalTab;
  var setParticipantListTab = function setParticipantListTab(key) {
    if (!isTabControlled) setInternalTab(key);
    onParticipantListTabChange === null || onParticipantListTabChange === void 0 || onParticipantListTabChange(key);
  };
  var t = (0, _i18n.useI18n)();
  var localUserIsHostOrCohost = (0, _react.useMemo)(function () {
    return userList.some(function (u) {
      return u.isMe && (u.isHost || u.userRole === _attendee.FcrUserRole.COHOST);
    });
  }, [userList]);

  /** True when the local user (web viewer / "me") has role AUDIENCE */
  var userRoleIsAudience = (0, _react.useMemo)(function () {
    return userList.some(function (u) {
      return u.isMe && u.userRole === _attendee.FcrUserRole.AUDIENCE;
    });
  }, [userList]);
  var raiseHandCount = (_raiseHandUserList$le = raiseHandUserList === null || raiseHandUserList === void 0 ? void 0 : raiseHandUserList.length) !== null && _raiseHandUserList$le !== void 0 ? _raiseHandUserList$le : 0;
  var showAudienceRaisingHandTip = localUserIsHostOrCohost && showParticipantListTab && participantListTab === 'audience' && raiseHandCount > 0;
  var _useMemo = (0, _react.useMemo)(function () {
      var fromList = userList.filter(isInAudienceTab).length;
      return {
        numberOfHostAndGuest: userList.filter(isInHostTab).length,
        numberOfAudience: userRoleIsAudience && audienceCountFromRoom !== undefined ? audienceCountFromRoom : fromList
      };
    }, [userList, userRoleIsAudience, audienceCountFromRoom]),
    numberOfHostAndGuest = _useMemo.numberOfHostAndGuest,
    numberOfAudience = _useMemo.numberOfAudience;
  var displayedUserList = (0, _react.useMemo)(function () {
    if (userRoleIsAudience) {
      var me = userList.find(function (u) {
        return u.isMe;
      });
      var hostAndGuest = userList.filter(isInHostTab);
      var rest = hostAndGuest.filter(function (u) {
        return u.userId !== (me === null || me === void 0 ? void 0 : me.userId);
      });
      if (me) return [me, PARTICIPANT_LIST_DIVIDER].concat((0, _toConsumableArray2["default"])(rest), [PARTICIPANT_LIST_FOOTER]);
      return hostAndGuest;
    }
    if (!showParticipantListTab) return userList;
    if (participantListTab === 'host') return userList.filter(isInHostTab);
    var audienceList = userList.filter(isInAudienceTab);
    if (localUserIsHostOrCohost) {
      return sortAudienceByRaiseHandOrder(audienceList, raiseHandUserList, userList);
    }
    return audienceList;
  }, [userList, showParticipantListTab, participantListTab, userRoleIsAudience, raiseHandUserList]);
  var handleChange = function handleChange(val) {
    setValue(val);
    onSearch(val);
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "fcr-participant",
    children: [header, applicationApplyingTips, !userRoleIsAudience && showParticipantListTab && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "fcr-participant__tabs",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_tabs.FcrTabs, {
        items: [{
          label: "".concat(t('fmt_webinar_role_presenter')).concat(showParticipantListCounts && numberOfHostAndGuest !== 0 ? " (".concat(numberOfHostAndGuest, ")") : ''),
          key: 'host'
        }, {
          label: /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
            className: "fcr-participant__tab-label fcr-participant__tab-label--audience",
            children: ["".concat(t('fmt_webinar_role_attendee')).concat(showParticipantListCounts && numberOfAudience !== 0 ? " (".concat(numberOfAudience, ")") : ''), ((_raiseHandUserList$le2 = raiseHandUserList === null || raiseHandUserList === void 0 ? void 0 : raiseHandUserList.length) !== null && _raiseHandUserList$le2 !== void 0 ? _raiseHandUserList$le2 : 0) > 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_icon.FcrIcon, {
              type: _type.FcrIconType.FCR_RAISEHAND1_SINGLE,
              size: 24,
              colors: {
                iconPrimary: 'var(--fcr_ui_scene_icontext1)'
              }
            }) : null]
          }),
          key: 'audience'
        }],
        activeKey: participantListTab,
        onChange: function onChange(key) {
          return setParticipantListTab(key);
        }
      })
    }), !userRoleIsAudience && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "fcr-participant__search-and-invite",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_input.FcrInput, {
        size: "small",
        placeholder: t('fmt_attendies_button_serach'),
        value: value,
        shape: "rounded",
        onChange: handleChange,
        maxLength: 21,
        style: {
          background: 'var(--fcr_ui_scene_input2)'
        }
        // autoFocus
        ,
        iconPrefix: {
          type: _type.FcrIconType.FCR_V2_SEARCH,
          colors: {
            iconPrimary: 'var(--fcr_ui_scene_icontext1)'
          }
        }
      }), hasInvite && onInvite ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.FcrButton, {
        className: "fcr_participants_button_invite",
        type: "secondary-bordered",
        shape: "rounded",
        size: "XS",
        onClick: onInvite,
        children: t('fmt_participants_button_invite')
      }) : null]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "fcr-participant__list",
      children: displayedUserList.length === 0 && emptyContent ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "fcr-participant__list-empty",
        children: emptyContent
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "fcr-participant__list-scroll",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactVirtualized.AutoSizer, {
          children: function children(_ref2) {
            var height = _ref2.height,
              width = _ref2.width;
            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactVirtualized.List, {
              width: width,
              height: height,
              rowCount: displayedUserList.length,
              rowHeight: function rowHeight(_ref3) {
                var index = _ref3.index;
                return isDivider(displayedUserList[index]) ? DIVIDER_ROW_HEIGHT : 52;
              },
              rowRenderer: userRowRenderer(displayedUserList, userRenderer, hasPinnedStream, toggleParticipantAction, isLocalCameraInSecondaryWindow, userRoleIsAudience ? "".concat(t('fmt_webinar_participant_list_label_presenter_panel')).concat(showParticipantListCounts && numberOfHostAndGuest !== 0 ? " (".concat(numberOfHostAndGuest, ")") : '') : undefined, userRoleIsAudience && showParticipantListCounts && numberOfAudience >= 1 ? "".concat(t('fmt_webinar_participant_list_attendee_with_others', {
                reason1: numberOfAudience - 1 === 0 ? '0' : numberOfAudience - 1
              })) : undefined)
            });
          }
        })
      })
    }), showAudienceRaisingHandTip ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "fcr-participant__raising-hand-tip",
      role: "status",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        className: "fcr-participant__raising-hand-tip-text",
        children: t('fmt_webinar_attendees_raising_hand_count', {
          reason1: raiseHandCount
        })
      })
    }) : null, footer ? footer : null]
  });
};