'use client';

import Hls from 'hls.js';
import { useEffect, useMemo, useRef, useState } from 'react';
import { resolveSourceType } from '@/lib/stream';

type Props = {
  title: string;
  url: string;
  posterUrl?: string | null;
};

export default function VideoPlayer({ title, url, posterUrl }: Props) {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const hlsRef = useRef<Hls | null>(null);
  const [error, setError] = useState<string | null>(null);
  const resolved = useMemo(() => resolveSourceType(url), [url]);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    setError(null);

    if (resolved.normalizedType === 'hls') {
      if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = resolved.url;
        return;
      }

      if (Hls.isSupported()) {
        const hls = new Hls({
          enableWorker: true,
          lowLatencyMode: true
        });
        hlsRef.current = hls;
        hls.loadSource(resolved.url);
        hls.attachMedia(video);
        hls.on(Hls.Events.ERROR, (_, data) => {
          if (data.fatal) {
            setError(`Error HLS: ${data.type}`);
            hls.destroy();
          }
        });
        return () => {
          hls.destroy();
        };
      }

      setError('Este navegador no soporta HLS ni Media Source Extensions para este stream.');
      return;
    }

    video.src = resolved.url;
    return () => {
      if (hlsRef.current) {
        hlsRef.current.destroy();
        hlsRef.current = null;
      }
    };
  }, [resolved]);

  return (
    <div className="player-shell">
      <div className="player-header">
        <div>
          <p className="eyebrow">Reproducción segura</p>
          <h2>{title}</h2>
        </div>
      </div>

      <div className="video-frame">
        <video
          ref={videoRef}
          controls
          playsInline
          poster={posterUrl || undefined}
          preload="metadata"
          className="video-element"
        />
      </div>

      {error ? <p className="error-box">{error}</p> : null}
    </div>
  );
}
