"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_component_exports = {};
__export(video_component_exports, {
  VideoComponent: () => VideoComponent
});
module.exports = __toCommonJS(video_component_exports);
var import_design_system = require("@wix/design-system");
var import_classnames = __toESM(require("classnames"));
var import_lodash = __toESM(require("lodash"));
var import_react = __toESM(require("react"));
var import_is_custom_upload = require("./../../_shared/is-custom-upload.js");
var import_ui_components = require("./../../ui-components/index.js");
var import_get_container_classes = require("../../_shared/figure/get-container-classes.js");
var import_data_hooks = require("../data-hooks.js");
var import_default_video_styles_scss = __toESM(require("../statics/styles/default-video-styles-scss.js"));
var import_video = require("../viewer/video.js");
const isUploading = (videoData) => videoData?.video?.src?.url?.startsWith?.("blob:") ?? false;
function createFakeProgressStepper(onProgress, approximateExpectedDuration = 5e3) {
  let lastTimeoutId;
  let progress = 0;
  const startDate = Date.now();
  const getTimeoutDelay = () => {
    const linearStep = approximateExpectedDuration / 100;
    if (progress <= 25) {
      return linearStep / 4;
    } else if (progress <= 50) {
      return linearStep / 3;
    } else if (progress <= 90) {
      return linearStep / 1.5;
    } else {
      const timeRemaining = approximateExpectedDuration - (Date.now() - startDate);
      return timeRemaining / (100 - progress);
    }
  };
  const run = () => {
    progress += 1;
    if (progress >= 100) {
      return;
    }
    lastTimeoutId = setTimeout(run, getTimeoutDelay());
    onProgress(progress);
  };
  run();
  return () => {
    clearTimeout(lastTimeoutId);
  };
}
class VideoComponent extends import_react.default.Component {
  constructor(props) {
    super(props);
    this.containerRef = import_react.default.createRef();
    this.startFakeLoader = () => {
      if (this.resetFakeLoader) {
        this.resetFakeLoader();
      }
      const isCustomVideo = "video" in this.props.componentData && (!!this.props.componentData.video?.src?.id || (0, import_is_custom_upload.isCustomUpload)(this.props.componentData.video?.src?.url));
      this.resetFakeLoader = createFakeProgressStepper(
        (percent) => this.setState({ fakeLoadingPercent: percent }),
        isCustomVideo ? 5e4 : 8500
      );
    };
    this.handleReady = (player) => {
      if (!this.state.isLoaded) {
        this.setState({ isLoaded: true });
        if (!isUploading(this.props.componentData)) {
          this.resetFakeLoader && this.resetFakeLoader();
        }
      }
      this.handleDuration(player);
    };
    this.handleDuration = (player) => {
      setTimeout(() => {
        const duration = player.current?.getDuration();
        if (duration) {
          this.saveDurationToData(duration);
        } else {
          this.setState({ shouldRenderDurationFix: true });
        }
      }, 3e3);
    };
    this.renderPendingOverlay = ({ title, subtitle }) => {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: import_default_video_styles_scss.default.video_pending_overlay }, /* @__PURE__ */ import_react.default.createElement("span", { className: import_default_video_styles_scss.default.video_pending_overlay_loader }, /* @__PURE__ */ import_react.default.createElement(import_ui_components.DoubleLoader, null)), /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical", gap: "0", align: "center" }, /* @__PURE__ */ import_react.default.createElement(import_design_system.Text, { size: "small", weight: "bold", light: true }, title), /* @__PURE__ */ import_react.default.createElement(import_design_system.Text, { size: "small", weight: "thin", light: true }, subtitle)));
    };
    this.saveDurationToData = (duration) => {
      const { componentData, updateAttributes } = this.props;
      const video = "video" in componentData ? componentData.video : {};
      updateAttributes({ ...componentData, video: { ...video || {}, duration } });
    };
    this.handleUpdateProcessing = (processing) => {
      this.setState({ processing });
    };
    this.renderPlayer = () => {
      const { componentData, config, nodeId } = this.props;
      return /* @__PURE__ */ import_react.default.createElement(
        import_video.Video,
        {
          componentData,
          config,
          onReady: this.handleReady,
          isLoaded: this.state.isLoaded,
          key: this.state.iosFixKey,
          nodeId,
          isLight: false,
          disabled: true,
          onUpdateProcessing: this.handleUpdateProcessing
        }
      );
    };
    this.renderPlayerDurationFix = () => {
      const { componentData, config, nodeId } = this.props;
      const play = (player) => {
        const internalPlayer = player.current?.getInternalPlayer();
        if (internalPlayer && "play" in internalPlayer && import_lodash.default.isFunction(internalPlayer.play)) {
          internalPlayer.play();
          return true;
        }
        return false;
      };
      const onReady = (player) => {
        const hasPlayed = play(player);
        if (hasPlayed) {
          return;
        }
        this.durationFixTimeoutId = setTimeout(() => {
          play(player);
        }, 1e4);
      };
      return /* @__PURE__ */ import_react.default.createElement("div", { className: import_default_video_styles_scss.default.hide_duration }, /* @__PURE__ */ import_react.default.createElement(
        import_video.Video,
        {
          componentData,
          config,
          onReady,
          isLight: false,
          onDuration: (duration) => {
            this.setState({ shouldRenderDurationFix: false });
            this.saveDurationToData(duration);
            clearTimeout(this.durationFixTimeoutId);
          },
          nodeId,
          muted: true,
          onUpdateProcessing: this.handleUpdateProcessing
        }
      ));
    };
    this.getOverlayProps = () => {
      const { t } = this.props;
      const { isLoaded, processing } = this.state;
      const loading = this.props.isLoading || !isLoaded;
      const uploading = isUploading(this.props.componentData);
      if (processing) {
        return {
          title: t("VideoComponent_Processing_Title"),
          subtitle: t("VideoComponent_Processing_Subtitle")
        };
      }
      if (loading && !this.props.componentData.error) {
        return {
          title: uploading ? t("VideoComponent_Uploading_Title") : t("VideoComponent_Loading_Title"),
          subtitle: uploading ? t("VideoComponent_Uploading_Subtitle", {
            percent: Math.round(this.state.fakeLoadingPercent)
          }) : t("VideoComponent_Loading_Subtitle")
        };
      }
      return null;
    };
    this.state = {
      isLoaded: false,
      iosFixKey: 1,
      processing: false,
      fakeLoadingPercent: 1
    };
  }
  componentDidMount() {
    this.handlePlayerFocus();
    if (isUploading(this.props.componentData)) {
      this.startFakeLoader();
    }
  }
  componentDidUpdate(prevProps) {
    this.handlePlayerFocus();
    const wasUploading = isUploading(prevProps.componentData);
    const isNowUploading = isUploading(this.props.componentData);
    const hasTokenChanged = prevProps.componentData.uploadToken !== this.props.componentData.uploadToken && this.props.componentData.uploadToken !== null;
    if (wasUploading && !isNowUploading || hasTokenChanged) {
      this.resetFakeLoader && this.resetFakeLoader();
    }
    if (!wasUploading && isNowUploading || hasTokenChanged) {
      this.startFakeLoader();
    }
  }
  componentWillUnmount() {
    clearTimeout(this.durationFixTimeoutId);
    this.resetFakeLoader && this.resetFakeLoader();
  }
  handlePlayerFocus() {
    const element = this.containerRef.current?.querySelector("iframe, video");
    if (element) {
      element.tabIndex = -1;
    }
  }
  render() {
    const {
      t,
      componentData: { error }
    } = this.props;
    const { shouldRenderDurationFix } = this.state;
    const overlayProps = this.getOverlayProps();
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        ref: this.containerRef,
        "data-hook": import_data_hooks.VIDEO_ROOT,
        className: (0, import_classnames.default)(
          import_default_video_styles_scss.default.video_container,
          (0, import_get_container_classes.getContainerClasses)(this.props.editor, this.props.nodeId, false)
        )
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: import_default_video_styles_scss.default.video_overlay }),
      this.renderPlayer(),
      shouldRenderDurationFix ? this.renderPlayerDurationFix() : null,
      overlayProps && this.renderPendingOverlay(overlayProps),
      error && /* @__PURE__ */ import_react.default.createElement(import_ui_components.MediaItemErrorMsg, { error, t })
    );
  }
}
//# sourceMappingURL=video-component.js.map
