<template>
  <div class="video-player">
    <video 
      ref="videoRef"
      class="video-element"
      controls
      autoplay
      playsinline
    ></video>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-overlay">
      <div class="error-icon">!</div>
      <p>播放错误: {{ error }}</p>
      <p class="hint">请尝试切换线路</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import Hls from 'hls.js'

const props = defineProps({
  url: String,
  title: String
})

const videoRef = ref(null)
const error = ref(null)
let hls = null

const initPlayer = () => {
  if (!props.url) return
  
  error.value = null
  const video = videoRef.value
  
  // 清理旧的 HLS 实例
  if (hls) {
    hls.destroy()
    hls = null
  }
  
  const isHLS = props.url.includes('.m3u8')
  
  if (isHLS && Hls.isSupported()) {
    hls = new Hls({
      enableWorker: true,
      maxBufferLength: 30,
    })
    
    hls.loadSource(props.url)
    hls.attachMedia(video)
    
    hls.on(Hls.Events.MANIFEST_PARSED, () => {
      video.play().catch(e => console.log('播放被阻止:', e))
    })
    
    hls.on(Hls.Events.ERROR, (event, data) => {
      if (data.fatal) {
        error.value = data.type
      }
    })
  } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    video.src = props.url
    video.play()
  } else {
    video.src = props.url
  }
  
  video.onerror = () => {
    error.value = 'networkError'
  }
}

watch(() => props.url, (newUrl) => {
  if (newUrl) initPlayer()
})

onMounted(() => {
  if (props.url) initPlayer()
})

onUnmounted(() => {
  if (hls) {
    hls.destroy()
    hls = null
  }
})

// 暴露方法
defineExpose({
  play: (url) => {
    if (url) {
      props.url = url
      initPlayer()
    }
  }
})
</script>

<style scoped>
.video-player {
  width: 100%;
  height: 100%;
  background: #000;
  position: relative;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0,0,0,0.9);
  color: #fff;
  gap: 10px;
}

.error-icon {
  width: 60px;
  height: 60px;
  background: #ff4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  font-weight: bold;
}

.error-overlay p {
  font-size: 14px;
}

.hint {
  color: #666;
  font-size: 12px;
}
</style>
