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

export default function Player({ src, poster, subtitles }:{ src:string; poster?:string; subtitles?:{label:string,url:string}[] }){
  const videoRef = useRef<HTMLVideoElement>(null);
  useEffect(()=>{
    const video = videoRef.current;
    if(!video) return;
    if (Hls.isSupported()) {
      const hls = new Hls({ capLevelToPlayerSize: true });
      hls.loadSource(src);
      hls.attachMedia(video);
      return ()=>hls.destroy();
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = src;
    }
  },[src]);
  return (
    <div className="w-full aspect-video bg-black rounded-2xl overflow-hidden">
      <video ref={videoRef} controls poster={poster} className="w-full h-full">
        {subtitles?.map((s, i)=>(
          <track key={i} label={s.label} kind="subtitles" srcLang="en" src={s.url} default={i===0} />
        ))}
      </video>
    </div>
  );
}
