<template>
  <div class="editable-element-frame"
    :style="{
      top: elementInfo.top + 'px',
      left: elementInfo.left + 'px',
      width: elementInfo.width + 'px',
      height: elementInfo.height + 'px',
      overflow: 'hidden',
    }"
  >
    <div
      class="rotate-wrapper"
      :style="{ transform: `rotate(${elementInfo.rotate}deg)` }"
    >
      <div
        class="element-content"
        :class="{ 'is-interactive-widget': isInteractiveSpeakingTool }"
        v-contextmenu="contextmenus"
        @mousedown="$event => handleSelectElement($event)"
        @touchstart="$event => handleSelectElement($event)"
      >
        <!-- 视频类型（type 74）：使用 video 标签 -->
        <video 
          v-if="elementInfo.toolType === 74"
          :src="elementInfo.url"
          :width="elementInfo.width"
          :height="elementInfo.height"
          controls
          :style="{ width: '100%', height: '100%', objectFit: 'contain' }"
        ></video>
        <!-- 英语口语预览（type 77）：使用 Vue 组件直接渲染，url 字段即 configId -->
        <TopicDiscussionPreview
          v-else-if="isTopicDiscussion"
          :configId="elementInfo.url"
          :style="{ width: '100%', height: '100%' }"
        />
        <!-- 文章朗读预览（type 772）：独立分支，不得回落到话题讨论或 iframe -->
        <ArticleReadingPreview
          v-else-if="isArticleReading"
          :configId="elementInfo.url"
          :style="{ width: '100%', height: '100%' }"
        />
        <!-- B站视频类型（type 75）：使用 iframe -->
        <iframe 
          v-else-if="elementInfo.toolType === 75"
          :key="'bilibili-' + iframeKey"
          :src="elementInfo.url"
          :width="elementInfo.width"
          :height="elementInfo.height"
          :frameborder="0" 
          :allowfullscreen="true"
          allow="camera *; microphone *; display-capture; midi; encrypted-media; fullscreen; geolocation; clipboard-read; clipboard-write; accelerometer; autoplay; gyroscope; payment; picture-in-picture; usb; xr-spatial-tracking;"
        ></iframe>
        <!-- 其他类型：保持原有逻辑 -->
        <iframe 
          v-else-if="elementInfo.isHTML"
          :key="'html-' + iframeKey"
          :srcdoc="elementInfo.url"
          :width="elementInfo.width"
          :height="elementInfo.height"
          :frameborder="0" 
          :allowfullscreen="true"
          allow="camera *; microphone *; display-capture; midi; encrypted-media; fullscreen; geolocation; clipboard-read; clipboard-write; accelerometer; autoplay; gyroscope; payment; picture-in-picture; usb; xr-spatial-tracking;"
        ></iframe>
        <iframe 
          v-else
          :key="'src-' + iframeKey"
          :src="elementInfo.url"
          :width="elementInfo.width"
          :height="elementInfo.height"
          :frameborder="0" 
          :allowfullscreen="true"
          allow="camera *; microphone *; display-capture; midi; encrypted-media; fullscreen; geolocation; clipboard-read; clipboard-write; accelerometer; autoplay; gyroscope; payment; picture-in-picture; usb; xr-spatial-tracking;"
        ></iframe>

        <!-- type 77 / 772（英语口语预览）是需要内部交互的 Vue 组件：
             mask / drag-handler 会挡住 wheel 事件导致内部滚不了，
             所以对它们不渲染这两层，选中/拖动走外层 .element-content 的 mousedown。 -->
        <template v-if="!isInteractiveSpeakingTool">
          <div class="drag-handler top"></div>
          <div class="drag-handler bottom"></div>
          <div class="drag-handler left"></div>
          <div class="drag-handler right"></div>

          <div class="mask"
            v-if="handleElementId !== elementInfo.id"
            @mousedown="$event => handleSelectElement($event, false)"
            @touchstart="$event => handleSelectElement($event, false)"
          ></div>
        </template>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { PropType } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/store'
import { useSpeakingStore } from '@/store/speaking'
import { useArticleReadingStore } from '@/store/articleReading'
import { isTopicDiscussionTool, isArticleReadingTool } from '@/configs/englishSpeakingTools'
import type { PPTFrameElement } from '@/types/slides'
import TopicDiscussionPreview from '@/views/Editor/EnglishSpeaking/preview/TopicDiscussionPreview.vue'
import ArticleReadingPreview from '@/views/Editor/EnglishSpeaking/preview/ArticleReadingPreview.vue'
import type { ContextmenuItem } from '@/components/Contextmenu/types'
import { computed, ref, watch } from 'vue'

const props = defineProps({
  elementInfo: {
    type: Object as PropType<PPTFrameElement>,
    required: true,
  },
  selectElement: {
    type: Function as PropType<(e: MouseEvent | TouchEvent, element: PPTFrameElement, canMove?: boolean) => void>,
    required: true,
  },
  contextmenus: {
    type: Function as PropType<() => ContextmenuItem[] | null>,
    required: true,
  },
})

const { handleElementId } = storeToRefs(useMainStore())
const speakingStore = useSpeakingStore()
const articleStore = useArticleReadingStore()

// 英语口语预览工具（FRAME + toolType 77 / 772）：产品上占满整页、不可拖动、不可缩放/旋转。
// 这些 flag 在 template 里决定是否渲染 mask/drag-handler + interactive-widget class，
// 在 handleSelectElement 里决定是否禁止 drag + 弹哪一侧的配置面板。
const isTopicDiscussion = computed(() => isTopicDiscussionTool(props.elementInfo.toolType))
const isArticleReading = computed(() => isArticleReadingTool(props.elementInfo.toolType))
const isInteractiveSpeakingTool = computed(() => isTopicDiscussion.value || isArticleReading.value)

const iframeKey = ref(0)

watch(() => props.elementInfo.url, (newUrl, oldUrl) => {
  if (newUrl !== oldUrl) {
    iframeKey.value++
  }
})

const handleSelectElement = (e: MouseEvent | TouchEvent, canMove = true) => {
  e.stopPropagation()
  // 口语工具：强制 canMove=false 跳过 useSelectElement 的 dragElement 分支，禁止拖动。
  // 点击后仍弹出/切换配置面板（业务需求）。
  const finalCanMove = isInteractiveSpeakingTool.value ? false : canMove
  props.selectElement(e, props.elementInfo, finalCanMove)
  if (isTopicDiscussion.value) speakingStore.openConfigPanel()
  if (isArticleReading.value) articleStore.openConfigPanel(props.elementInfo.url)
}
</script>

<style lang="scss" scoped>
.editable-element-frame {
  position: absolute;
  overflow: hidden;
}
.element-content {
  width: 100%;
  height: 100%;
  cursor: move;
  overflow: hidden;
  position: absolute;
}
// 英语口语预览（type 77）不可拖动，光标维持默认（让内部按钮/输入的 cursor 能生效）
.element-content.is-interactive-widget {
  cursor: default;
}
.element-content iframe{
  width: 100%;
  height: 100%;
  cursor: move;
  overflow: hidden;
  position: absolute;
}
.element-content video {
  width: 100%;
  height: 100%;
  cursor: move;
  object-fit: contain;
  background-color: #000;
  position: absolute;
}
.drag-handler {
  position: absolute;

  &.top {
    height: 20px;
    left: 0;
    right: 0;
    top: 0;
  }
  &.bottom {
    height: 20px;
    left: 0;
    right: 0;
    bottom: 0;
  }
  &.left {
    width: 20px;
    top: 0;
    bottom: 0;
    left: 0;
  }
  &.right {
    width: 20px;
    top: 0;
    bottom: 0;
    right: 0;
  }
}
.mask {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
}
.rotate-wrapper {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style> 