import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _typeof from "@babel/runtime/helpers/typeof";
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) { _defineProperty(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; }
import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.array.filter.js";
import "core-js/modules/es.array.find.js";
import "core-js/modules/es.array.includes.js";
import "core-js/modules/es.symbol.js";
import "core-js/modules/es.array.for-each.js";
import "core-js/modules/es.array.index-of.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.array.some.js";
import "core-js/modules/es.array.push.js";
import "core-js/modules/es.array.sort.js";
import "core-js/modules/es.map.js";
import "core-js/modules/es.object.define-properties.js";
import "core-js/modules/es.object.define-property.js";
import "core-js/modules/es.object.get-own-property-descriptor.js";
import "core-js/modules/es.object.get-own-property-descriptors.js";
import "core-js/modules/es.object.keys.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/esnext.iterator.constructor.js";
import "core-js/modules/esnext.iterator.filter.js";
import "core-js/modules/esnext.iterator.find.js";
import "core-js/modules/esnext.iterator.some.js";
import "core-js/modules/esnext.iterator.for-each.js";
import "core-js/modules/esnext.map.delete-all.js";
import "core-js/modules/esnext.map.emplace.js";
import "core-js/modules/esnext.map.every.js";
import "core-js/modules/esnext.map.filter.js";
import "core-js/modules/esnext.map.find.js";
import "core-js/modules/esnext.map.find-key.js";
import "core-js/modules/esnext.map.includes.js";
import "core-js/modules/esnext.map.key-of.js";
import "core-js/modules/esnext.map.map-keys.js";
import "core-js/modules/esnext.map.map-values.js";
import "core-js/modules/esnext.map.merge.js";
import "core-js/modules/esnext.map.reduce.js";
import "core-js/modules/esnext.map.some.js";
import "core-js/modules/esnext.map.update.js";
import "core-js/modules/web.dom-collections.for-each.js";
import "core-js/modules/web.dom-collections.iterator.js";
import { FcrButton } from '../button';
import { List, AutoSizer, CellMeasurerCache, CellMeasurer } from 'react-virtualized';
import { FcrInput } from '../input';
import { FcrParticipant, FcrUserRole } from './attendee';
import { FcrIcon } from '../icon';
import { FcrIconType } from '../icon/type';
import { useMemo, useState } from 'react';
import { useI18n } from '../../i18n';
import { FcrTabs } from '../tabs';
import './index.css';

/** Roles that appear in the "host/guest" tab (host, co-host, participant) */
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
var ROLES_IN_HOST_TAB = [FcrUserRole.HOST, FcrUserRole.COHOST, 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) */
export var PARTICIPANT_LIST_DIVIDER = {
  _divider: true
};
export var 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 && _typeof(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 _toConsumableArray(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 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__*/_jsxs("div", {
        style: _objectSpread(_objectSpread({}, style), {}, {
          height: DIVIDER_ROW_HEIGHT
        }),
        className: "fcr-participant__list-divider",
        children: [/*#__PURE__*/_jsx("span", {
          className: "fcr-participant__list-divider-label",
          children: dividerLabel
        }), /*#__PURE__*/_jsx("span", {
          className: "fcr-participant__list-divider-line"
        })]
      }, key);
    }
    if (isFooter(item)) {
      if (footLabel) {
        return /*#__PURE__*/_jsx("div", {
          style: _objectSpread({}, style),
          className: "fcr-participant__list-footer",
          children: /*#__PURE__*/_jsx("span", {
            className: "fcr-participant__list-footer-label",
            children: footLabel
          })
        }, key);
      }
      return null;
    }
    return /*#__PURE__*/_jsx(CellMeasurer, {
      cache: cache,
      parent: parent,
      columnIndex: 0,
      rowIndex: index,
      children: function children(_ref) {
        var measure = _ref.measure;
        return /*#__PURE__*/_jsx("div", {
          style: _objectSpread(_objectSpread({}, style), {}, {
            pointerEvents: 'all'
          }),
          onLoad: measure,
          children: userRenderer ? userRenderer(item) : /*#__PURE__*/_jsx(FcrParticipant, {
            hasPinnedStream: hasPinnedStream,
            user: item,
            onParticipantsButtonClick: toggleParticipantAction,
            isLocalCameraInSecondaryWindow: isLocalCameraInSecondaryWindow
          })
        });
      }
    }, key);
  };
};
export var 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 = useState(useMemo(function () {
      return searchText || '';
    }, [searchText])),
    _useState2 = _slicedToArray(_useState, 2),
    value = _useState2[0],
    setValue = _useState2[1];
  var _useState3 = useState('host'),
    _useState4 = _slicedToArray(_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 = useI18n();
  var localUserIsHostOrCohost = useMemo(function () {
    return userList.some(function (u) {
      return u.isMe && (u.isHost || u.userRole === FcrUserRole.COHOST);
    });
  }, [userList]);

  /** True when the local user (web viewer / "me") has role AUDIENCE */
  var userRoleIsAudience = useMemo(function () {
    return userList.some(function (u) {
      return u.isMe && u.userRole === 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 = 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 = 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(_toConsumableArray(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__*/_jsxs("div", {
    className: "fcr-participant",
    children: [header, applicationApplyingTips, !userRoleIsAudience && showParticipantListTab && /*#__PURE__*/_jsx("div", {
      className: "fcr-participant__tabs",
      children: /*#__PURE__*/_jsx(FcrTabs, {
        items: [{
          label: "".concat(t('fmt_webinar_role_presenter')).concat(showParticipantListCounts && numberOfHostAndGuest !== 0 ? " (".concat(numberOfHostAndGuest, ")") : ''),
          key: 'host'
        }, {
          label: /*#__PURE__*/_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__*/_jsx(FcrIcon, {
              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__*/_jsxs("div", {
      className: "fcr-participant__search-and-invite",
      children: [/*#__PURE__*/_jsx(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: FcrIconType.FCR_V2_SEARCH,
          colors: {
            iconPrimary: 'var(--fcr_ui_scene_icontext1)'
          }
        }
      }), hasInvite && onInvite ? /*#__PURE__*/_jsx(FcrButton, {
        className: "fcr_participants_button_invite",
        type: "secondary-bordered",
        shape: "rounded",
        size: "XS",
        onClick: onInvite,
        children: t('fmt_participants_button_invite')
      }) : null]
    }), /*#__PURE__*/_jsx("div", {
      className: "fcr-participant__list",
      children: displayedUserList.length === 0 && emptyContent ? /*#__PURE__*/_jsx("div", {
        className: "fcr-participant__list-empty",
        children: emptyContent
      }) : /*#__PURE__*/_jsx("div", {
        className: "fcr-participant__list-scroll",
        children: /*#__PURE__*/_jsx(AutoSizer, {
          children: function children(_ref2) {
            var height = _ref2.height,
              width = _ref2.width;
            return /*#__PURE__*/_jsx(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__*/_jsx("div", {
      className: "fcr-participant__raising-hand-tip",
      role: "status",
      children: /*#__PURE__*/_jsx("span", {
        className: "fcr-participant__raising-hand-tip-text",
        children: t('fmt_webinar_attendees_raising_hand_count', {
          reason1: raiseHandCount
        })
      })
    }) : null, footer ? footer : null]
  });
};