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);
        } else if (videoRef.current.canPlayType('application/vnd.apple.mpegurl')) {
          videoRef.current.src = streamUrl;
        } else {
          console.error('This browser does not support HLS');
        }
      }
    };

    loadVideo();

    return () => {
      if (hls) {
        hls.destroy();
      }
    };
  }, [streamUrl]);

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

export default VideoPlayer;
