import { defineComponent, watch, onMounted, onBeforeUnmount, createElementBlock, openBlock, normalizeClass, unref, createElementVNode, createVNode, createCommentVNode, createBlock, toDisplayString } from "vue";
import TUIRoomEngine, { TUIErrorCode } from "@tencentcloud/tuiroom-engine-js";
import { useUIKit, IconLoading, TUIToast, TUIMessageBox } from "@tencentcloud/uikit-base-component-vue3";
import { useRoomState, useDeviceState, useRoomModal, ScheduledRoomList, RoomType } from "tuikit-atomicx-vue3/room";
import CameraButton from "../../components/CameraButton/index.vue2.mjs";
import JoinRoomButton from "../../components/JoinRoomButton/index.vue2.mjs";
import LanguageButton from "../../components/LanguageButton/index.vue2.mjs";
import LoginUserInfo from "../../components/LoginUserInfo/index.vue2.mjs";
import MicButton from "../../components/MicButton/index.vue2.mjs";
import ScheduledRoomButton from "../../components/ScheduledRoomButton/index.vue2.mjs";
import StartRoomButton from "../../components/StartRoomButton/index.vue2.mjs";
import ThemeButton from "../../components/ThemeButton/index.vue2.mjs";
const _hoisted_1 = { class: "header" };
const _hoisted_2 = { class: "header-left" };
const _hoisted_3 = { class: "header-right" };
const _hoisted_4 = { class: "main" };
const _hoisted_5 = { class: "title" };
const _hoisted_6 = { class: "main-container" };
const _hoisted_7 = { class: "room-preview-container" };
const _hoisted_8 = { class: "camera-preview-area" };
const _hoisted_9 = { class: "attention-info" };
const _hoisted_10 = {
  key: 0,
  class: "off-camera-info"
};
const _hoisted_11 = { class: "control-container" };
const _hoisted_12 = { class: "media-control-region" };
const _hoisted_13 = { class: "room-control-region" };
const _hoisted_14 = { class: "schedule-list" };
const MAX_ROOM_ID_RETRIES = 5;
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "PreviewView",
  emits: ["create-room", "join-room", "camera-preference-change", "microphone-preference-change", "logout"],
  setup(__props, { emit: __emit }) {
    const emit = __emit;
    const { t, theme, language } = useUIKit();
    const { getRoomInfo } = useRoomState();
    const {
      isMicrophoneTesting,
      isCameraTesting,
      isCameraTestLoading,
      startCameraTest,
      startMicrophoneTest,
      stopCameraTest,
      stopMicrophoneTest
    } = useDeviceState();
    const { handleErrorWithModal } = useRoomModal();
    watch(isMicrophoneTesting, () => {
      emit("microphone-preference-change", isMicrophoneTesting.value);
    });
    watch(isCameraTesting, () => {
      emit("camera-preference-change", isCameraTesting.value);
    });
    const checkRoomExist = async (roomId) => {
      try {
        await getRoomInfo({ roomId });
      } catch (error) {
        if (error.code === TUIErrorCode.ERR_ROOM_ID_NOT_EXIST) {
          return false;
        }
      }
      return true;
    };
    const generateRoomId = async (roomType, retriesLeft = MAX_ROOM_ID_RETRIES) => {
      const roomId = String(Math.floor(Math.random() * 9e5) + 1e5);
      if (!await checkRoomExist(roomId)) {
        return roomType === RoomType.Standard ? roomId : `webinar_${roomId}`;
      }
      if (retriesLeft <= 1) {
        const fallbackId = `${Math.floor(Math.random() * 9e5) + 1e5}_${Date.now()}`;
        return roomType === RoomType.Standard ? fallbackId : `webinar_${fallbackId}`;
      }
      return generateRoomId(roomType, retriesLeft - 1);
    };
    const handleStartRoom = async (roomType) => {
      const roomId = await generateRoomId(roomType);
      sessionStorage.setItem(`room-${roomId}-isCreate`, "true");
      emit("create-room", roomId, roomType);
    };
    const handleJoinRoom = async (roomId) => {
      if (!roomId) {
        TUIToast.error({ message: t("Room.RoomIdRequired") });
        return;
      }
      if (await checkRoomExist(roomId)) {
        const isWebinar = roomId.startsWith("webinar_");
        emit("join-room", roomId, isWebinar ? RoomType.Webinar : RoomType.Standard);
      } else {
        TUIMessageBox.alert({
          type: "error",
          modal: false,
          showClose: false,
          title: t("Room.Alert"),
          content: t("Room.RoomNotFound")
        });
      }
    };
    function handleLogout() {
      emit("logout");
    }
    onMounted(() => {
      const roomPreviewVideo = document.getElementById("room-preview-video");
      TUIRoomEngine.once("ready", async () => {
        if (roomPreviewVideo) {
          try {
            await startCameraTest({ view: roomPreviewVideo });
          } catch (error) {
            handleErrorWithModal(error);
          }
        }
        try {
          await startMicrophoneTest();
        } catch (error) {
          handleErrorWithModal(error);
        }
      });
    });
    onBeforeUnmount(() => {
      stopCameraTest();
      stopMicrophoneTest();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        class: normalizeClass(["home-container", unref(theme)])
      }, [
        createElementVNode("header", _hoisted_1, [
          createElementVNode("div", _hoisted_2, [
            createVNode(ThemeButton)
          ]),
          createElementVNode("div", _hoisted_3, [
            createVNode(LanguageButton),
            createVNode(LoginUserInfo, { onLogout: handleLogout })
          ])
        ]),
        createElementVNode("main", _hoisted_4, [
          createElementVNode("div", _hoisted_5, [
            createElementVNode("div", {
              class: normalizeClass(["logo", unref(language)])
            }, null, 2)
          ]),
          createElementVNode("div", _hoisted_6, [
            createElementVNode("div", _hoisted_7, [
              createElementVNode("div", _hoisted_8, [
                _cache[1] || (_cache[1] = createElementVNode("div", {
                  id: "room-preview-video",
                  class: "video-preview"
                }, null, -1)),
                createElementVNode("div", _hoisted_9, [
                  !unref(isCameraTesting) && !unref(isCameraTestLoading) ? (openBlock(), createElementBlock("span", _hoisted_10, toDisplayString(unref(t)("Off Camera")), 1)) : createCommentVNode("", true),
                  unref(isCameraTestLoading) ? (openBlock(), createBlock(unref(IconLoading), {
                    key: 1,
                    size: "36",
                    class: "loading"
                  })) : createCommentVNode("", true)
                ])
              ]),
              createElementVNode("div", _hoisted_11, [
                createElementVNode("div", _hoisted_12, [
                  createVNode(MicButton),
                  createVNode(CameraButton, { cameraTestContainer: "room-preview-video" })
                ]),
                createElementVNode("div", _hoisted_13, [
                  createVNode(StartRoomButton, {
                    class: "button-item",
                    onStartRoom: handleStartRoom
                  }),
                  createVNode(JoinRoomButton, {
                    class: "button-item",
                    onJoinRoom: handleJoinRoom
                  }),
                  createVNode(ScheduledRoomButton, { class: "button-item" })
                ])
              ])
            ]),
            createElementVNode("div", _hoisted_14, [
              createVNode(unref(ScheduledRoomList), {
                onJoinRoom: _cache[0] || (_cache[0] = (roomInfo) => handleJoinRoom(roomInfo.roomId))
              })
            ])
          ])
        ])
      ], 2);
    };
  }
});
export {
  _sfc_main as default
};
