import React, { useEffect, useRef } from 'react';
import Hls from 'hls.js';

const VideoPlayer = ({ streamUrl }) => {
  const videoRef = useRef(null);

  useEffect(() => {
    let hls;

    const loadVideo = () => {
      if (videoRef.current) {
        if (Hls.isSupported()) {
          hls = new Hls();
          hls.loadSource(streamUrl);
          hls.attachMedia(videoRef.current);
          hls.on(Hls.Events.MANIFEST_PARSED, () => {
            videoRef.current.play().catch(error => {
              console.error("Auto-play was prevented:", error);
            });
          });
        } else if (videoRef.current.canPlayType('application/vnd.apple.mpegurl')) {
          videoRef.current.src = streamUrl;
          videoRef.current.play().catch(error => {
            console.error("Auto-play was prevented:", error);
          });
        } else {
          console.error('This browser does not support HLS');
        }
      }
    };

    loadVideo();

    // 添加 ESC 键监听器
    const handleEscKey = (event) => {
      if (event.key === 'Escape' && document.fullscreenElement) {
        document.exitFullscreen();
      }
    };

    document.addEventListener('keydown', handleEscKey);

    return () => {
      if (hls) {
        hls.destroy();
      }
      // 移除 ESC 键监听器
      document.removeEventListener('keydown', handleEscKey);
    };
  }, [streamUrl]);

  return (
    <div className="aspect-w-16 aspect-h-9">
      <video
        ref={videoRef}
        controls
        autoPlay
        muted
        className="w-full h-full object-cover rounded-lg shadow-lg"
      />
    </div>
  );
};

export default VideoPlayer;
