// From Gemini.
import React, { useEffect, useRef, useState } from "react";
import "./reader.js";

interface MediaMTXPlayerProps {
  url: string;
  user?: string;
  pass?: string;
  token?: string;
}

export const MediaMtxPlayer: React.FC<MediaMTXPlayerProps> = ({
  url,
  user,
  pass,
  token,
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let reader: any = null;

    if (videoRef.current && url) {
      reader = new MediaMTXWebRTCReader({
        url,
        user,
        pass,
        token,
        onError: (err: any) => {
          console.error("MediaMTX WebRTC Error:", err);
          setError(err);
        },
        onTrack: (evt: RTCTrackEvent) => {
          if (videoRef.current && evt.streams[0]) {
            videoRef.current.srcObject = evt.streams[0];
          }
        },
        onDataChannel: (evt: RTCDataChannelEvent) => {
          console.log("Data channel opened:", evt.channel);
        },
      });
    }

    // Cleanup when component unmounts or URL changes
    return () => {
      if (reader && typeof reader.close === "function") {
        reader.close();
      }
      if (videoRef.current) {
        videoRef.current.srcObject = null;
      }
    };
  }, [url, user, pass, token]);

  return (
    <div style={{ position: "relative", width: "100%", maxWidth: "720px" }}>
      {error && (
        <div style={{ color: "red", marginBottom: "8px" }}>
          Error getting video.
        </div>
      )}
      <video
        ref={videoRef}
        autoPlay
        playsInline
        muted
        controls
        style={{
          width: "100%",
          maxWidth: "720px",
          height: "auto",
          backgroundColor: "#000",
        }}
      />
    </div>
  );
};
