<script setup lang="ts">
/**
 * DPlayer 弹层播放器
 * 用于作品详情、视频详情等场景，不覆盖主图
 */
import { ref, watch, onBeforeUnmount, nextTick } from 'vue'
import DPlayer from 'dplayer'
import 'dplayer/dist/DPlayer.min.css'
import Icon from './Icon.vue'

interface Props {
  /** 是否显示弹层 */
  visible: boolean
  /** 视频播放地址 */
  videoUrl: string
  /** 封面图（poster） */
  poster?: string
  /** 弹层标题 */
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  poster: '',
  title: '视频播放',
})

const emit = defineEmits<{ close: [] }>()

const playerContainerRef = ref<HTMLElement | null>(null)
let playerInstance: DPlayer | null = null

/** 初始化 DPlayer 实例 */
const initPlayer = () => {
  destroyPlayer()
  if (!playerContainerRef.value || !props.videoUrl) return

  playerInstance = new DPlayer({
    container: playerContainerRef.value,
    video: {
      url: props.videoUrl,
      pic: props.poster || undefined,
    },
    autoplay: true,
    theme: '#d4b383',
    lang: 'zh-cn',
  })
}

/** 销毁播放器实例，释放资源 */
const destroyPlayer = () => {
  if (playerInstance) {
    playerInstance.destroy()
    playerInstance = null
  }
}

const handleClose = () => {
  destroyPlayer()
  emit('close')
}

watch(
  () => props.visible,
  async (show) => {
    if (show) {
      await nextTick()
      initPlayer()
    } else {
      destroyPlayer()
    }
  }
)

watch(
  () => props.videoUrl,
  async () => {
    if (props.visible) {
      await nextTick()
      initPlayer()
    }
  }
)

onBeforeUnmount(() => destroyPlayer())
</script>

<template>
  <Teleport to="body">
    <Transition
      enter-active-class="transition duration-200 ease-out"
      enter-from-class="opacity-0"
      enter-to-class="opacity-100"
      leave-active-class="transition duration-150 ease-in"
      leave-from-class="opacity-100"
      leave-to-class="opacity-0"
    >
      <div
        v-if="visible"
        class="fixed inset-0 z-[200] flex items-center justify-center bg-black/85 backdrop-blur-sm p-4 md:p-8"
        @click.self="handleClose"
      >
        <div class="relative w-full max-w-5xl bg-[#0d0d0d] rounded-xl border border-white/10 overflow-hidden shadow-2xl">
          <!-- 标题栏 -->
          <div class="flex items-center justify-between px-4 py-3 border-b border-white/10">
            <h3 class="text-sm md:text-base text-white font-medium truncate pr-4">{{ title }}</h3>
            <button
              type="button"
              class="shrink-0 p-2 rounded-full hover:bg-white/10 text-white/70 hover:text-white transition-colors"
              @click="handleClose"
            >
              <Icon name="x" :size="20" />
            </button>
          </div>
          <!-- 播放器容器 -->
          <div ref="playerContainerRef" class="w-full aspect-video bg-black"></div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped>
:deep(.dplayer) {
  width: 100% !important;
  height: 100% !important;
}
</style>
