import { defineComponent, ref, computed, createElementBlock, openBlock, Fragment, createCommentVNode, createVNode, unref, createElementVNode, toDisplayString, withCtx, renderList, createTextVNode } from "vue";
import { TUIErrorCode } from "@tencentcloud/tuiroom-engine-js";
import { useUIKit, IconEndRoom, TUIPopup, TUIButton, TUIToast, TUIMessageBox } from "@tencentcloud/uikit-base-component-vue3";
import { useRoomState, useRoomParticipantState, Avatar, RoomParticipantRole } from "tuikit-atomicx-vue3/room";
import PopUpArrowDown from "../base/PopUpArrowDown.vue2.mjs";
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__ */ defineComponent({
  __name: "index",
  emits: ["leave", "end"],
  setup(__props, { emit: __emit }) {
    const { t } = useUIKit();
    const emit = __emit;
    const {
      currentRoom,
      leaveRoom: leaveRoomStateApi,
      endRoom: endRoomStateApi
    } = useRoomState();
    const { localParticipant, participantList, transferOwner } = useRoomParticipantState();
    const showTransferDialog = ref(false);
    const showConfirmDialog = ref(false);
    const selectedUserId = ref("");
    const isTransferring = ref(false);
    const isEnding = ref(false);
    const otherParticipants = computed(
      () => participantList.value.filter(
        (participant) => {
          var _a;
          return participant.userId !== ((_a = localParticipant.value) == null ? void 0 : _a.userId);
        }
      )
    );
    const dialogMessage = 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 === TUIErrorCode.ERR_INVALID_PARAMETER) {
          return Promise.resolve();
        }
        throw _error;
      }
    };
    const endRoom = async () => {
      try {
        return await endRoomStateApi();
      } catch (_error) {
        if (_error.code === 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) {
        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) {
        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) {
        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) {
        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) === RoomParticipantRole.Owner;
      if (!isOwner) {
        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 openBlock(), createElementBlock(Fragment, null, [
        ((_a = unref(currentRoom)) == null ? void 0 : _a.roomId) ? (openBlock(), createElementBlock("div", {
          key: 0,
          class: "end-room-button",
          onClick: handleLeaveRoom
        }, [
          createVNode(unref(IconEndRoom), { size: "20" }),
          createElementVNode("span", null, toDisplayString(unref(t)("Room.End")), 1)
        ])) : createCommentVNode("", true),
        createVNode(unref(TUIPopup), {
          visible: showConfirmDialog.value,
          "onUpdate:visible": _cache[1] || (_cache[1] = ($event) => showConfirmDialog.value = $event),
          title: unref(t)("Room.ConfirmLeaveTitle")
        }, {
          default: withCtx(() => [
            createElementVNode("div", _hoisted_1, [
              createVNode(PopUpArrowDown, {
                onClick: _cache[0] || (_cache[0] = ($event) => showConfirmDialog.value = false)
              }),
              createElementVNode("div", _hoisted_2, [
                createElementVNode("div", _hoisted_3, toDisplayString(dialogMessage.value), 1),
                createElementVNode("div", _hoisted_4, [
                  createElementVNode("div", {
                    class: "button-item end-room",
                    onClick: handleEndRoom
                  }, toDisplayString(unref(t)("Room.EndRoom")), 1),
                  createElementVNode("div", {
                    class: "button-item leave-room",
                    onClick: handleLeaveFromConfirmDialog
                  }, toDisplayString(unref(t)("Room.LeaveRoom")), 1)
                ])
              ])
            ])
          ]),
          _: 1
        }, 8, ["visible", "title"]),
        createVNode(unref(TUIPopup), {
          visible: showTransferDialog.value,
          "onUpdate:visible": _cache[3] || (_cache[3] = ($event) => showTransferDialog.value = $event),
          title: unref(t)("Room.SelectNewHost"),
          height: "90%"
        }, {
          default: withCtx(() => [
            createElementVNode("div", _hoisted_5, [
              createVNode(PopUpArrowDown, {
                onClick: _cache[2] || (_cache[2] = ($event) => showTransferDialog.value = false)
              }),
              createElementVNode("div", _hoisted_6, [
                createElementVNode("div", _hoisted_7, toDisplayString(unref(t)("Room.PleaseSelectNewHost")), 1),
                createElementVNode("div", _hoisted_8, [
                  (openBlock(true), createElementBlock(Fragment, null, renderList(otherParticipants.value, (participant) => {
                    return openBlock(), createElementBlock("div", {
                      key: participant.userId,
                      class: "participant-item",
                      onClick: ($event) => handleParticipantClick(participant.userId)
                    }, [
                      createVNode(unref(Avatar), {
                        src: participant.avatarUrl,
                        size: 40
                      }, null, 8, ["src"]),
                      createElementVNode("div", _hoisted_10, [
                        createElementVNode("span", null, toDisplayString(participant.userName || participant.userId), 1),
                        selectedUserId.value === participant.userId ? (openBlock(), createElementBlock("div", _hoisted_11, [..._cache[4] || (_cache[4] = [
                          createElementVNode("input", {
                            checked: "",
                            type: "checkbox"
                          }, null, -1)
                        ])])) : createCommentVNode("", true)
                      ])
                    ], 8, _hoisted_9);
                  }), 128))
                ])
              ]),
              createElementVNode("div", _hoisted_12, [
                createVNode(unref(TUIButton), {
                  type: "primary",
                  style: { "min-width": "100%" },
                  size: "large",
                  disabled: !selectedUserId.value,
                  loading: isTransferring.value,
                  onClick: handleTransferAndLeave
                }, {
                  default: withCtx(() => [
                    createTextVNode(toDisplayString(unref(t)("Room.TransferAndLeave")), 1)
                  ]),
                  _: 1
                }, 8, ["disabled", "loading"])
              ])
            ])
          ]),
          _: 1
        }, 8, ["visible", "title"])
      ], 64);
    };
  }
});
export {
  _sfc_main as default
};
