"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const vue = require("vue");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const uikitBaseComponentVue3 = require("@tencentcloud/uikit-base-component-vue3");
const room = require("tuikit-atomicx-vue3/room");
const PopUpArrowDown = require("../base/PopUpArrowDown.vue2.js");
const _hoisted_1 = { class: "popup-container" };
const _hoisted_2 = { class: "popup-content" };
const _hoisted_3 = { class: "popup-message" };
const _hoisted_4 = { class: "button-container" };
const _hoisted_5 = { class: "popup-container" };
const _hoisted_6 = { class: "popup-content" };
const _hoisted_7 = { class: "popup-title" };
const _hoisted_8 = { class: "participant-list" };
const _hoisted_9 = ["onClick"];
const _hoisted_10 = { class: "user-info" };
const _hoisted_11 = {
  key: 0,
  class: "selected-indicator"
};
const _hoisted_12 = { class: "popup-footer" };
const _sfc_main = /* @__PURE__ */ vue.defineComponent({
  __name: "index",
  emits: ["leave", "end"],
  setup(__props, { emit: __emit }) {
    const { t } = uikitBaseComponentVue3.useUIKit();
    const emit = __emit;
    const {
      currentRoom,
      leaveRoom: leaveRoomStateApi,
      endRoom: endRoomStateApi
    } = room.useRoomState();
    const { localParticipant, participantList, transferOwner } = room.useRoomParticipantState();
    const showTransferDialog = vue.ref(false);
    const showConfirmDialog = vue.ref(false);
    const selectedUserId = vue.ref("");
    const isTransferring = vue.ref(false);
    const isEnding = vue.ref(false);
    const otherParticipants = vue.computed(
      () => participantList.value.filter(
        (participant) => {
          var _a;
          return participant.userId !== ((_a = localParticipant.value) == null ? void 0 : _a.userId);
        }
      )
    );
    const dialogMessage = vue.computed(() => {
      if (otherParticipants.value.length === 0) {
        return t("Room.LeaveRoomTip");
      }
      return t("Room.ConfirmLeaveTip");
    });
    const leaveRoom = async () => {
      try {
        return await leaveRoomStateApi();
      } catch (_error) {
        if (_error.code === TUIRoomEngine.TUIErrorCode.ERR_INVALID_PARAMETER) {
          return Promise.resolve();
        }
        throw _error;
      }
    };
    const endRoom = async () => {
      try {
        return await endRoomStateApi();
      } catch (_error) {
        if (_error.code === TUIRoomEngine.TUIErrorCode.ERR_INVALID_PARAMETER) {
          return Promise.resolve();
        }
        throw _error;
      }
    };
    const performLeave = async () => {
      var _a;
      try {
        if (!((_a = currentRoom.value) == null ? void 0 : _a.roomId)) {
          return;
        }
        await leaveRoom();
        emit("leave");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.LeaveRoomFailed") });
      }
    };
    const handleEndRoom = async () => {
      var _a;
      if (!((_a = currentRoom.value) == null ? void 0 : _a.roomId) || isEnding.value) {
        return;
      }
      try {
        isEnding.value = true;
        await endRoom();
        showConfirmDialog.value = false;
        emit("end");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.EndRoomFailed") });
      } finally {
        isEnding.value = false;
      }
    };
    const handleParticipantClick = (userId) => {
      if (selectedUserId.value === userId) {
        selectedUserId.value = "";
        return;
      }
      selectedUserId.value = userId;
    };
    const autoTransferAndLeave = async () => {
      var _a;
      if (otherParticipants.value.length !== 1 || !((_a = currentRoom.value) == null ? void 0 : _a.roomId)) {
        return;
      }
      try {
        const targetParticipant = otherParticipants.value[0];
        await transferOwner({ userId: targetParticipant.userId });
        await leaveRoom();
        emit("leave");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.TransferAndLeaveFailed") });
      }
    };
    const handleLeaveFromConfirmDialog = () => {
      showConfirmDialog.value = false;
      if (otherParticipants.value.length === 0) {
        performLeave();
        return;
      }
      if (otherParticipants.value.length === 1) {
        autoTransferAndLeave();
        return;
      }
      showTransferDialog.value = true;
      selectedUserId.value = "";
    };
    const handleTransferAndLeave = async () => {
      var _a;
      if (!selectedUserId.value || !((_a = currentRoom.value) == null ? void 0 : _a.roomId) || isTransferring.value) {
        return;
      }
      try {
        isTransferring.value = true;
        await transferOwner({ userId: selectedUserId.value });
        await leaveRoom();
        showTransferDialog.value = false;
        emit("leave");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.TransferAndLeaveFailed") });
      } finally {
        isTransferring.value = false;
      }
    };
    const handleLeaveRoom = () => {
      var _a, _b;
      if (!((_a = currentRoom.value) == null ? void 0 : _a.roomId)) {
        return;
      }
      const isOwner = ((_b = localParticipant.value) == null ? void 0 : _b.role) === room.RoomParticipantRole.Owner;
      if (!isOwner) {
        uikitBaseComponentVue3.TUIMessageBox.confirm({
          title: t("Room.ConfirmLeaveTitle"),
          content: t("Room.ConfirmLeaveRoom"),
          callback: (action) => {
            if (action === "confirm") {
              performLeave();
            }
          }
        });
        return;
      }
      showConfirmDialog.value = true;
    };
    return (_ctx, _cache) => {
      var _a;
      return vue.openBlock(), vue.createElementBlock(vue.Fragment, null, [
        ((_a = vue.unref(currentRoom)) == null ? void 0 : _a.roomId) ? (vue.openBlock(), vue.createElementBlock("div", {
          key: 0,
          class: "end-room-button",
          onClick: handleLeaveRoom
        }, [
          vue.createVNode(vue.unref(uikitBaseComponentVue3.IconEndRoom), { size: "20" }),
          vue.createElementVNode("span", null, vue.toDisplayString(vue.unref(t)("Room.End")), 1)
        ])) : vue.createCommentVNode("", true),
        vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIPopup), {
          visible: showConfirmDialog.value,
          "onUpdate:visible": _cache[1] || (_cache[1] = ($event) => showConfirmDialog.value = $event),
          title: vue.unref(t)("Room.ConfirmLeaveTitle")
        }, {
          default: vue.withCtx(() => [
            vue.createElementVNode("div", _hoisted_1, [
              vue.createVNode(PopUpArrowDown.default, {
                onClick: _cache[0] || (_cache[0] = ($event) => showConfirmDialog.value = false)
              }),
              vue.createElementVNode("div", _hoisted_2, [
                vue.createElementVNode("div", _hoisted_3, vue.toDisplayString(dialogMessage.value), 1),
                vue.createElementVNode("div", _hoisted_4, [
                  vue.createElementVNode("div", {
                    class: "button-item end-room",
                    onClick: handleEndRoom
                  }, vue.toDisplayString(vue.unref(t)("Room.EndRoom")), 1),
                  vue.createElementVNode("div", {
                    class: "button-item leave-room",
                    onClick: handleLeaveFromConfirmDialog
                  }, vue.toDisplayString(vue.unref(t)("Room.LeaveRoom")), 1)
                ])
              ])
            ])
          ]),
          _: 1
        }, 8, ["visible", "title"]),
        vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIPopup), {
          visible: showTransferDialog.value,
          "onUpdate:visible": _cache[3] || (_cache[3] = ($event) => showTransferDialog.value = $event),
          title: vue.unref(t)("Room.SelectNewHost"),
          height: "90%"
        }, {
          default: vue.withCtx(() => [
            vue.createElementVNode("div", _hoisted_5, [
              vue.createVNode(PopUpArrowDown.default, {
                onClick: _cache[2] || (_cache[2] = ($event) => showTransferDialog.value = false)
              }),
              vue.createElementVNode("div", _hoisted_6, [
                vue.createElementVNode("div", _hoisted_7, vue.toDisplayString(vue.unref(t)("Room.PleaseSelectNewHost")), 1),
                vue.createElementVNode("div", _hoisted_8, [
                  (vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(otherParticipants.value, (participant) => {
                    return vue.openBlock(), vue.createElementBlock("div", {
                      key: participant.userId,
                      class: "participant-item",
                      onClick: ($event) => handleParticipantClick(participant.userId)
                    }, [
                      vue.createVNode(vue.unref(room.Avatar), {
                        src: participant.avatarUrl,
                        size: 40
                      }, null, 8, ["src"]),
                      vue.createElementVNode("div", _hoisted_10, [
                        vue.createElementVNode("span", null, vue.toDisplayString(participant.userName || participant.userId), 1),
                        selectedUserId.value === participant.userId ? (vue.openBlock(), vue.createElementBlock("div", _hoisted_11, [..._cache[4] || (_cache[4] = [
                          vue.createElementVNode("input", {
                            checked: "",
                            type: "checkbox"
                          }, null, -1)
                        ])])) : vue.createCommentVNode("", true)
                      ])
                    ], 8, _hoisted_9);
                  }), 128))
                ])
              ]),
              vue.createElementVNode("div", _hoisted_12, [
                vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIButton), {
                  type: "primary",
                  style: { "min-width": "100%" },
                  size: "large",
                  disabled: !selectedUserId.value,
                  loading: isTransferring.value,
                  onClick: handleTransferAndLeave
                }, {
                  default: vue.withCtx(() => [
                    vue.createTextVNode(vue.toDisplayString(vue.unref(t)("Room.TransferAndLeave")), 1)
                  ]),
                  _: 1
                }, 8, ["disabled", "loading"])
              ])
            ])
          ]),
          _: 1
        }, 8, ["visible", "title"])
      ], 64);
    };
  }
});
exports.default = _sfc_main;
