<template>
  <div class="video-player-container" :style="plyrThemeVars">
    <video
      ref="videoEl"
      :src="videoUrl"
      :type="mimeType"
      controls
      playsinline
      preload="auto"
      class="plyr-video"
    >
      您的浏览器不支持视频播放
    </video>

    <div v-if="isLoading" class="video-loading">
      <p>正在加载视频...</p>
    </div>

    <Transition name="fade">
      <div v-if="playerError" class="video-error">
        <p>⚠️ {{ playerError }}</p>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import Plyr from 'plyr'

const props = defineProps({
  videoUrl: { type: String, default: '' },
  mimeType: { type: String, default: 'video/mp4' },
  autoPlay: { type: Boolean, default: false }
})

const emit = defineEmits(['error', 'ready'])

const videoEl = ref(null)
const isLoading = ref(true)
const playerError = ref('')
let playerInstance = null

// Plyr 主题变量（匹配 GitHub 蓝色）
const plyrThemeVars = computed(() => ({
  '--plyr-color-main': '#0969da',
  '--plyr-control-opacity': '1',
  '--plyr-video-control-color-hover': '#0969da',
}))

onMounted(() => {
  if (!videoEl.value) return

  try {
    playerInstance = new Plyr(videoEl.value, {
      controls: [
        'play-large',
        'play',
        'progress',
        'current-time',
        'mute',
        'volume',
        'settings',
        'pip',
        'airplay',
        'fullscreen'
      ],
      settings: ['quality', 'speed', 'loop'],
      speed: {
        selected: 1,
        options: [0.5, 1, 1.5, 2]
      },
      autoplay: props.autoPlay,
      preload: 'auto',
      muted: false,
      toggleControls: true,
      resetOnEnd: true,
      hideControls: true,
      tooltips: {
        controls: true,
        seek: false
      },
    })

    // 监听播放器事件
    playerInstance.on('ready', () => {
      isLoading.value = false
      emit('ready')
    })

    playerInstance.on('playing', () => {
      isLoading.value = false
    })

    playerInstance.on('error', (error) => {
      console.error('Plyr 播放器错误:', error)
      playerError.value = '视频加载失败，请检查格式或网络'
      emit('error', error)
    })

    playerInstance.on('loadeddata', () => {
      isLoading.value = false
    })

  } catch (error) {
    console.error('Plyr 初始化失败，回退到原生播放器:', error)
    playerError.value = '播放器初始化失败，使用原生控件'
  }
})

onUnmounted(() => {
  if (playerInstance) {
    try {
      playerInstance.destroy()
    } catch (error) {
      console.error('销毁播放器失败:', error)
    }
  }
})

function handleVideoError(event) {
  console.error('视频加载失败:', event.target.error)
  playerError.value = '当前浏览器无法直接播放这个视频格式，请下载后使用本地播放器打开。'
  emit('error', event)
}
</script>

<style scoped>
.video-player-container {
  max-width: 100%;
  min-height: 0;
  border-radius: 8px;
  overflow: hidden;
}

.plyr-video {
  width: 100%;
  height: auto;
  max-height: 480px;
  max-width: 100%;
}

.video-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.video-loading p {
  color: #666;
}

.video-error {
  margin-top: 12px;
  padding: 10px 14px;
  border-radius: 6px;
  background-color: #fff0f0;
  color: #cf222e;
  font-size: 13px;
}

.video-error p {
  margin: 0;
}

/* Plyr 主题覆盖 */
:deep(.plyr) {
  border-radius: 8px;
  font-family: inherit;
}

:deep(.plyr--video .plyr__controls) {
  border-top: none;
}

:deep(.plyr__control--overlaid) {
  background: rgba(9, 105, 218, 0.8);
  color: #fff;
}

:deep(.plyr--full-ui.plyr--video .plyr__control.plyr__tab-focus,
     .plyr--full-ui.plyr--video .plyr__control:hover) {
  background: #0969da;
}

/* 淡入动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

<style>
/* 全局 Plyr 样式（非 scoped，用于控制条主题） */
.plyr--video .plyr__control.plyr__tab-focus {
  box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.5);
}

.plyr--video .plyr__control:hover:not(.plyr__tab-focus) {
  background: #0969da;
}

.plyr--video .plyr__control--overlaid {
  background: rgba(9, 105, 218, 0.9);
}

.plyr--video .plyr__menu__container .plyr__control[role="menuitemradio"][aria-checked="true"] {
  background: #0969da;
}

.plyr__volume {
  color: #0969da;
}
</style>
