<template>
  <div class="video-container" @keyup.space="togglePlay">
    <video class="video-element" ref="videoElement" controls></video>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import Hls from "hls.js";

const props = defineProps({
  src: {
    type: String,
    required: true,
  },
  autoplay: {
    type: Boolean,
    default: false,
  },
});

const videoElement = ref(null);

const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const progress = ref(0);
const volume = ref(1);
const hls = ref(null);

const initPlayer = () => {
  if (Hls.isSupported()) {
    hls.value = new Hls();
    hls.value.loadSource(props.src);
    hls.value.attachMedia(videoElement.value);

    hls.value.on(Hls.Events.MANIFEST_PARSED, () => {
      console.log("HLS 流已解析");
    });

    hls.value.on(Hls.Events.ERROR, (event, data) => {
      console.error("HLS Error:", data);
      if (data.fatal) {
        switch (data.type) {
          case Hls.ErrorTypes.NETWORK_ERROR:
            console.error("网络错误，尝试重新加载");
            hls.value.startLoad();
            break;
          case Hls.ErrorTypes.MEDIA_ERROR:
            console.error("媒体错误，尝试恢复");
            hls.value.recoverMediaError();
            break;
          default:
            hls.value.destroy();
            break;
        }
      }
    });
  } else if (videoElement.value.canPlayType("application/vnd.apple.mpegurl")) {
    // Safari 原生支持
    videoElement.value.src = props.src;
  }
};

const togglePlay = () => {
  isPlaying.value ? videoElement.value.pause() : videoElement.value.play();
};
onMounted(() => {
  initPlayer();

  videoElement.value.addEventListener("loadedmetadata", () => {
    duration.value = videoElement.value.duration;
  });

  videoElement.value.addEventListener("timeupdate", () => {
    currentTime.value = videoElement.value.currentTime;
    progress.value = (currentTime.value / duration.value) * 100;
  });

  videoElement.value.addEventListener("play", () => {
    isPlaying.value = true;
  });

  videoElement.value.addEventListener("pause", () => {
    isPlaying.value = false;
  });

  videoElement.value.addEventListener("volumechange", () => {
    volume.value = videoElement.value.volume;
  });
});

onBeforeUnmount(() => {
  if (hls.value) {
    hls.value.destroy();
  }
});
</script>

<style scoped>
.video-container {
  margin: 0 auto;
  height: 100%;
}

.video-element {
  width: 100%;
  height: 100%;
}
</style>
