/* Video bài học: giữ controls gốc YouTube hoạt động như learn-superapp. */
(function () {
  function isInternal(src) {
    return /^\/agent\/api\/lesson-video/.test(src || "");
  }

  function isYoutube(src) {
    return /youtube(?:-nocookie)?\.com\/embed\//.test(src || "");
  }

  function playerSrc(src) {
    if (!isYoutube(src)) return src;
    try {
      const u = new URL(src, location.href);
      u.searchParams.set("controls", "1");
      u.searchParams.set("rel", "0");
      u.searchParams.set("modestbranding", "1");
      u.searchParams.set("playsinline", "1");
      return u.toString();
    } catch (e) {
      return src;
    }
  }

  function tokenized(src, tokenGetter) {
    const t = (tokenGetter && tokenGetter()) || "";
    return src + "?t=" + encodeURIComponent(t);
  }

  function fullscreen(root, isIOS, fallback) {
    const media = root && root.querySelector(".dcp-video__frame");
    if (!media) return;
    const isVid = media.tagName === "VIDEO";
    const target = media.tagName === "IFRAME" ? root : media;
    if (isIOS && isVid && media.webkitEnterFullscreen) {
      try { media.webkitEnterFullscreen(); } catch (e) {}
      return;
    }
    const fn = target.requestFullscreen || target.webkitRequestFullscreen || target.msRequestFullscreen;
    if (!fn) {
      if (media.tagName === "IFRAME" && fallback) fallback(media.src);
      return;
    }
    try {
      const out = fn.call(target);
      if (out && out.catch) out.catch(function () {
        if (media.tagName === "IFRAME" && fallback) fallback(media.src);
      });
    } catch (e) {
      if (media.tagName === "IFRAME" && fallback) fallback(media.src);
    }
  }

  function replay(root, toast) {
    const video = root && root.querySelector("video");
    const frame = root && root.querySelector("iframe");
    if (video) {
      video.currentTime = 0;
      try { video.play(); } catch (e) {}
    } else if (frame) {
      try {
        const u = new URL(frame.src, location.href);
        if (isYoutube(u.href)) {
          u.searchParams.set("start", "0");
          u.searchParams.set("autoplay", "1");
          u.searchParams.set("_replay", String(Date.now()));
          frame.src = u.toString();
        } else {
          const src = frame.src;
          frame.src = "";
          frame.src = src;
        }
      } catch (e) {
        const src = frame.src;
        frame.src = "";
        frame.src = src;
      }
    }
    if (toast) toast("Phát lại từ đầu…");
  }

  function LessonVideoPlayer(props) {
    const l = props.lesson;
    const local = isInternal(l.video);
    const rootRef = React.useRef(null);
    const cls = "dcp-video dcp-video-muc dcp-lesson-video" +
      (local ? " secure-video" : "") +
      (props.orientation === "portrait" && local ? " is-portrait" : "");
    const fsIcon = props.icon ? props.icon("Fullscreen", 15) : "⛶";

    return (
      <div className={cls} ref={rootRef} onContextMenu={(e) => local && e.preventDefault()}>
        {local ? (
          <video
            className="dcp-video__frame"
            src={tokenized(l.video, props.tokenGetter)}
            controls
            controlsList="nodownload noremoteplayback"
            disablePictureInPicture
            playsInline
            onContextMenu={(e) => e.preventDefault()}
            onLoadedMetadata={(e) => {
              const v = e.target;
              props.setOrientation(v.videoHeight > v.videoWidth * 1.05 ? "portrait" : "landscape");
            }}
            onTimeUpdate={(e) => {
              const v = e.target;
              if (!v.duration) return;
              const pct = Math.round((v.currentTime / v.duration) * 100);
              if (props.onProgress) props.onProgress(pct);
              if (pct >= 95 && props.onAutoDone) props.onAutoDone();
            }}
          />
        ) : (
          <iframe
            className="dcp-video__frame"
            src={playerSrc(l.video)}
            title={l.title}
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen"
            sandbox="allow-scripts allow-same-origin allow-presentation"
            allowFullScreen
          />
        )}
        {local && <div className="secure-video__shield" />}
        {local && <div className="secure-video__wm">{window.__wm || "Sam Nguyen Education"}</div>}
        <div className="dcp-lesson-video-controls">
          {!props.isIOS && (
            <button className="dcp-lesson-video__btn" type="button" onClick={() => fullscreen(rootRef.current, props.isIOS, props.setModalSrc)}>
              {fsIcon} Phóng to
            </button>
          )}
          <button className="dcp-lesson-video__btn" type="button" onClick={() => replay(rootRef.current, props.toast)}>
            ⟳ Phát lại
          </button>
        </div>
        {props.isIOS && (
          <div className="dcp-lesson-video__ios-note">Bấm nút toàn màn hình trong trình phát để xem to</div>
        )}
      </div>
    );
  }

  window.LessonVideoPlayer = LessonVideoPlayer;
})();
