import { jsx as m } from "react/jsx-runtime";
/* empty css                              */
/* empty css                             */
import "./index-Youtube.js";
import { useRef as d, useEffect as p } from "react";
import h from "./index-video.es.js";
import { processVideoSource as k } from "./index-utils.js";
const P = (v) => {
  const f = d(null), o = d(null), l = d(!1), {
    opts: T,
    onReady: u
  } = v, {
    src: y,
    type: n,
    tracks: c,
    fallbackSrc: i
  } = T;
  return p(() => {
    var a;
    const e = k(y, n), t = {
      playsinline: !0,
      autoplay: !1,
      controls: !0,
      fluid: !0,
      // aspectRatio: "16:9",
      responsive: !0,
      preload: "auto",
      techOrder: e.isYouTube ? ["youtube", "html5"] : ["html5"],
      plugins: {},
      // Disable Picture-in-Picture
      sources: [{
        src: e.src,
        type: e.type
      }],
      // Add tracks for captions/subtitles
      tracks: c || []
    };
    if (o.current) {
      const r = o.current;
      if (r.autoplay((t == null ? void 0 : t.autoplay) ?? !1), r.src((t == null ? void 0 : t.sources) ?? []), c && c.length > 0) {
        for (; r.remoteTextTracks().length > 0; ) {
          const s = r.remoteTextTracks()[0];
          if (s.kind === "subtitles" || s.kind === "captions")
            try {
              r.removeRemoteTextTrack(s);
            } catch {
              break;
            }
          else
            break;
        }
        c.forEach((s) => {
          r.addRemoteTextTrack(s, !1);
        });
      }
    } else {
      const r = document.createElement("video");
      r.classList.add("vjs-big-play-centered"), (a = f.current) == null || a.appendChild(r);
      const s = o.current = h(r, t, () => {
        h.log("player is ready"), u && u(s);
      });
    }
    l.current = !1;
  }, [y, n, c, u]), p(() => {
    const e = o.current;
    if (!e || !i)
      return;
    l.current = !1;
    const t = () => {
      const a = e.error();
      if (!a || a.code !== 4 || l.current) return;
      l.current = !0;
      const r = k(i, n);
      e.error(null), e.src({
        src: r.src,
        type: r.type
      });
    };
    return e.on("error", t), () => {
      e.off("error", t);
    };
  }, [i, n]), p(() => () => {
    const e = o.current;
    e && !e.isDisposed() && (e.dispose(), o.current = null);
  }, []), m("div", {
    className: "video-js",
    style: {
      width: "100%",
      height: "100%"
    },
    "data-vjs-player": !0,
    "data-testid": "video-player",
    children: m("div", {
      ref: f
    })
  });
};
export {
  P as VideoPlayer
};
