"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var video_exports = {};
__export(video_exports, {
  Video: () => Video
});
module.exports = __toCommonJS(video_exports);
var import_react = __toESM(require("react"));
var import_is_custom_upload = require("./../../_shared/is-custom-upload.js");
var import_wix_rich_content_common = require("./../../wix-rich-content-common/index.js");
var import_react_player_wrapper = require("../react-player-wrapper.js");
var import_video_viewer_scss = __toESM(require("../statics/styles/video-viewer-scss.js"));
const Video = ({
  config,
  componentData,
  nodeId,
  isLight,
  onReady,
  isLoaded,
  seoMode,
  jsdomMode,
  muted,
  onDuration,
  disabled,
  onUpdateProcessing
}) => {
  const retryTimeoutRef = (0, import_react.useRef)(null);
  const [playerKey, setPlayerKey] = (0, import_react.useState)("");
  const [state, setState] = (0, import_react.useState)(() => {
    const { src } = componentData.video || {};
    const getInitialVideoUrlState = () => {
      if (src?.url) {
        const normalizedUrl = normalizeVideoUrl(src.url);
        return normalizedUrl ? { type: "READY", loadedUrl: normalizedUrl } : { type: "INITIAL", loadedUrl: void 0 };
      }
      if (src?.id && config.getVideoUrl) {
        try {
          const url = config.getVideoUrl({ pathname: src.id });
          if (typeof url === "string") {
            const normalizedUrl = normalizeVideoUrl(url);
            return normalizedUrl ? { type: "READY", loadedUrl: normalizedUrl } : { type: "INITIAL", loadedUrl: void 0 };
          }
        } catch {
        }
      }
      return { type: "INITIAL", loadedUrl: void 0 };
    };
    const getInitialThumbnailUrlState = () => {
      const thumbnailSrc = componentData?.thumbnail?.src?.url;
      return thumbnailSrc ? { type: "READY", loadedUrl: thumbnailSrc } : { type: "INITIAL", loadedUrl: void 0 };
    };
    return {
      videoUrl: getInitialVideoUrlState(),
      thumbnailUrl: getInitialThumbnailUrlState()
    };
  });
  (0, import_react.useEffect)(() => {
    return () => {
      if (retryTimeoutRef.current) {
        clearTimeout(retryTimeoutRef.current);
      }
    };
  }, []);
  (0, import_react.useEffect)(() => {
    setPlayerKey("mounted");
  }, []);
  const scheduleNextRetry = (currentAttempt, _videoUrl) => {
    const maxRetries = 20;
    const nextAttempt = currentAttempt + 1;
    if (nextAttempt > maxRetries) {
      setState((prev) => {
        if (prev.videoUrl.type === "PROCESSING") {
          onUpdateProcessing?.(false);
          return {
            ...prev,
            videoUrl: {
              type: "ERROR",
              error: "Max retries exceeded",
              retryCount: nextAttempt,
              loadedUrl: prev.videoUrl.loadedUrl
            }
          };
        }
        return prev;
      });
      return;
    }
    setState((prev) => {
      if (prev.videoUrl.type === "PROCESSING") {
        return {
          ...prev,
          videoUrl: {
            ...prev.videoUrl,
            retryCount: nextAttempt
          }
        };
      }
      return prev;
    });
    const delay = Math.min(1e3 * Math.pow(2, nextAttempt - 1), 3e4);
    retryTimeoutRef.current = setTimeout(() => {
      setPlayerKey(`retry-${nextAttempt}-${Date.now()}`);
    }, delay);
  };
  const retryVideoUrl = () => {
    setState((prevState) => {
      if (prevState.videoUrl.type === "PROCESSING" || prevState.videoUrl.type === "INITIAL" || prevState.videoUrl.type === "LOADING") {
        return prevState;
      }
      const loadedUrl = prevState.videoUrl.loadedUrl;
      if (retryTimeoutRef.current) {
        clearTimeout(retryTimeoutRef.current);
        retryTimeoutRef.current = null;
      }
      onUpdateProcessing?.(true);
      scheduleNextRetry(0, loadedUrl);
      return {
        ...prevState,
        videoUrl: {
          type: "PROCESSING",
          retryCount: 1,
          loadedUrl
        }
      };
    });
  };
  (0, import_react.useEffect)(() => {
    const { src } = componentData.video || {};
    if (state.videoUrl.type === "LOADING" || state.videoUrl.type === "PROCESSING") {
      return;
    }
    if (src?.url) {
      const normalizedUrl = normalizeVideoUrl(src.url);
      const currentUrl = state.videoUrl.loadedUrl;
      if (normalizedUrl && normalizedUrl !== currentUrl) {
        setState((prev) => ({
          ...prev,
          videoUrl: { type: "READY", loadedUrl: normalizedUrl }
        }));
      }
      return;
    }
    if (src?.id && config.getVideoUrl) {
      const loadVideo = async () => {
        if (!src.id) {
          return;
        }
        setState((prev) => ({
          ...prev,
          videoUrl: { type: "LOADING", loadedUrl: void 0 }
        }));
        try {
          const url = await config.getVideoUrl({ pathname: src.id });
          if (url) {
            const normalizedUrl = normalizeVideoUrl(url);
            if (normalizedUrl) {
              setState((prev) => {
                if (prev.videoUrl.type === "LOADING") {
                  return {
                    ...prev,
                    videoUrl: { type: "READY", loadedUrl: normalizedUrl }
                  };
                }
                return prev;
              });
              return;
            }
          }
        } catch {
          retryVideoUrl();
        }
      };
      loadVideo();
    }
  }, [componentData.video?.src, config.getVideoUrl]);
  (0, import_react.useEffect)(() => {
    const { src } = componentData.thumbnail || {};
    const thumbnailId = src?.id;
    const thumbnailSrc = src?.url;
    const currentThumbnailUrl = state.thumbnailUrl.loadedUrl;
    if (thumbnailSrc && thumbnailSrc !== currentThumbnailUrl) {
      setState((prev) => ({
        ...prev,
        thumbnailUrl: { type: "READY", loadedUrl: thumbnailSrc }
      }));
      return;
    }
    if (thumbnailId && config.getThumbnailUrl && !currentThumbnailUrl) {
      const loadThumbnail = async () => {
        setState((prev) => ({
          ...prev,
          thumbnailUrl: { type: "LOADING", loadedUrl: void 0 }
        }));
        try {
          const url = await config.getThumbnailUrl({ pathname: thumbnailId });
          if (url) {
            setState((prev) => ({
              ...prev,
              thumbnailUrl: { type: "READY", loadedUrl: url }
            }));
          }
        } catch {
          setState((prev) => ({
            ...prev,
            thumbnailUrl: {
              type: "ERROR",
              error: "Failed to load thumbnail",
              retryCount: 0,
              loadedUrl: ""
            }
          }));
        }
      };
      loadThumbnail();
    }
  }, [componentData.thumbnail?.src, config.getThumbnailUrl]);
  const onReactPlayerReady = (player) => {
    setState((prev) => {
      if (prev.videoUrl.type === "PROCESSING") {
        onUpdateProcessing?.(false);
        if (retryTimeoutRef.current) {
          clearTimeout(retryTimeoutRef.current);
          retryTimeoutRef.current = null;
        }
        return {
          ...prev,
          videoUrl: {
            type: "READY",
            loadedUrl: prev.videoUrl.loadedUrl
          }
        };
      }
      if (prev.videoUrl.type === "ERROR") {
        onUpdateProcessing?.(false);
        if (retryTimeoutRef.current) {
          clearTimeout(retryTimeoutRef.current);
          retryTimeoutRef.current = null;
        }
        return {
          ...prev,
          videoUrl: {
            type: "READY",
            loadedUrl: prev.videoUrl.loadedUrl
          }
        };
      }
      const currentVideoUrl = prev.videoUrl.loadedUrl;
      if (!currentVideoUrl) {
        return prev;
      }
      return {
        ...prev,
        videoUrl: {
          type: "READY",
          loadedUrl: currentVideoUrl
        }
      };
    });
    if (onReady) {
      onReady(player);
      return;
    }
  };
  const onVideoError = () => {
    const { src } = componentData.video || {};
    const isCustomVideo2 = !!src?.id || (0, import_is_custom_upload.isCustomUpload)(src?.url);
    if (!isCustomVideo2 || !src?.id) {
      return;
    }
    if (state.videoUrl.type === "READY") {
      return retryVideoUrl();
    }
    if (state.videoUrl.type === "PROCESSING") {
      if (retryTimeoutRef.current) {
        clearTimeout(retryTimeoutRef.current);
        retryTimeoutRef.current = null;
      }
      return scheduleNextRetry(state.videoUrl.retryCount, state.videoUrl.loadedUrl);
    }
  };
  const handleContextMenu = (e) => componentData.disableDownload && e.preventDefault();
  const getDownloadProps = () => {
    if ((0, import_wix_rich_content_common.isDefined)(componentData?.disableDownload) && componentData.disableDownload || (0, import_wix_rich_content_common.isDefined)(config?.disableDownloadDefault) && config.disableDownloadDefault) {
      return {
        config: {
          file: {
            attributes: {
              controlsList: "nodownload"
            }
          }
        }
      };
    }
    return {
      config: {}
    };
  };
  const getLightProps = () => {
    if (!isLight) {
      return {
        isLight: false
      };
    }
    return {
      isLight: true,
      thumbnail: state.thumbnailUrl.loadedUrl
    };
  };
  const videoUrl = state.videoUrl.loadedUrl;
  if (!videoUrl) {
    return null;
  }
  const isCustomVideo = !!componentData.video?.src?.id;
  const shouldRenderSeoLink = ((0, import_wix_rich_content_common.isSSR)() || jsdomMode) && seoMode;
  const { autoPlay = false, playInLoop = false, showControls = true } = componentData.options || {};
  const poster = state.videoUrl.type === "PROCESSING" ? state.thumbnailUrl.loadedUrl : void 0;
  if (shouldRenderSeoLink) {
    return /* @__PURE__ */ import_react.default.createElement("a", { "data-hook": "video-ssr-viewer", href: videoUrl, target: "_blank", rel: "noopener noreferrer" }, videoUrl);
  }
  return /* @__PURE__ */ import_react.default.createElement(
    import_react_player_wrapper.ReactPlayerWrapper,
    {
      className: import_video_viewer_scss.default.video_player,
      onContextMenu: handleContextMenu,
      controls: isLoaded !== false && showControls,
      url: videoUrl,
      onReady: onReactPlayerReady,
      onError: onVideoError,
      disabled,
      width: "100%",
      height: "100%",
      key: playerKey,
      onDuration,
      onProgress: (progress) => {
        config.onProgress?.({ ...progress, id: nodeId });
      },
      progressInterval: config.progressInterval || 1e3,
      muted: muted || autoPlay,
      isLoaded: isLoaded || state.videoUrl.type === "READY" || state.videoUrl.type === "PROCESSING" || state.videoUrl.type === "ERROR",
      autoPlay,
      loop: playInLoop,
      isCustomVideo,
      poster,
      ...getLightProps(),
      ...getDownloadProps()
    }
  );
};
const normalizeVideoUrl = (url) => url ? url.toLowerCase().indexOf("vimeo") === 0 ? "https://" + url : url : void 0;
//# sourceMappingURL=video.js.map
