"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 input_with_slider_exports = {};
__export(input_with_slider_exports, {
  InputWithSlider: () => InputWithSlider
});
module.exports = __toCommonJS(input_with_slider_exports);
var import_design_system = require("@wix/design-system");
var import_react = __toESM(require("react"));
var import_ui_components_provider = require("./../ui-components-provider.js");
var import_input_with_slider_scss = __toESM(require("./input-with-slider-scss.js"));
const SLIDER_WIDTH = 88;
const SLIDER_GAP = 18;
const SLIDER_PADDING = 12;
const InputWithSlider = ({
  value,
  onChange,
  onChangeCommit,
  commitUnchanged = false,
  gradientColor,
  zIndex,
  prefix,
  suffix,
  min,
  max,
  dataHook
}) => {
  const [isFocused, setIsFocused] = import_react.default.useState(false);
  const inputRef = (0, import_react.useRef)(null);
  const inputWrapperRef = import_react.default.useRef(null);
  const [inputValue, setInputValue] = (0, import_react.useState)(value ?? "");
  const [sliderValue, setSliderValue] = (0, import_react.useState)(value ?? min);
  const [inputKey, setInputKey] = (0, import_react.useState)(0);
  const sliderValueRef = (0, import_react.useRef)(value ?? min);
  const originalValueRef = (0, import_react.useRef)(value ?? min);
  const isDraggingRef = (0, import_react.useRef)(false);
  const commitTimeoutRef = (0, import_react.useRef)(void 0);
  const removeDragEndListenersRef = (0, import_react.useRef)(void 0);
  const appendToElement = (0, import_ui_components_provider.usePopoverAppendToElement)();
  const inputWrapperDimensions = inputWrapperRef.current?.getBoundingClientRect() ?? { width: 0 };
  const popoverZIndex = `calc(${zIndex} + 100)`;
  const numberInputZIndex = `calc(${popoverZIndex} + 1)`;
  import_react.default.useEffect(() => {
    const newValue = value ?? "";
    if (newValue !== inputValue) {
      setInputValue(newValue);
    }
    if (!isDraggingRef.current && typeof value === "number") {
      setSliderValue(value);
      sliderValueRef.current = value;
    }
  }, [value]);
  import_react.default.useEffect(
    () => () => {
      removeDragEndListenersRef.current?.();
      if (commitTimeoutRef.current !== void 0) {
        window.clearTimeout(commitTimeoutRef.current);
      }
    },
    []
  );
  const handleInputWithinBounds = (data, shouldCommit = true) => {
    const numberValue = Math.round(Number(data));
    const valueWithinBounds = isNaN(numberValue) || numberValue < min ? min : numberValue > max ? max : numberValue;
    setInputValue(valueWithinBounds);
    setSliderValue(valueWithinBounds);
    sliderValueRef.current = valueWithinBounds;
    if (value !== valueWithinBounds || commitUnchanged) {
      onChange(valueWithinBounds);
      if (shouldCommit) {
        onChangeCommit?.(valueWithinBounds, originalValueRef.current);
        originalValueRef.current = valueWithinBounds;
      }
      return;
    }
    setInputKey((prev) => prev + 1);
  };
  const commitSliderValue = () => {
    if (!isDraggingRef.current) {
      return;
    }
    isDraggingRef.current = false;
    const finalValue = sliderValueRef.current;
    const originalValue = originalValueRef.current;
    if (finalValue !== originalValue || commitUnchanged) {
      onChangeCommit?.(finalValue, originalValue);
    }
    originalValueRef.current = finalValue;
  };
  const scheduleSliderCommit = () => {
    if (commitTimeoutRef.current !== void 0) {
      window.clearTimeout(commitTimeoutRef.current);
    }
    commitTimeoutRef.current = window.setTimeout(() => {
      commitTimeoutRef.current = void 0;
      commitSliderValue();
    });
  };
  const handleSliderDragStart = (event) => {
    removeDragEndListenersRef.current?.();
    isDraggingRef.current = true;
    originalValueRef.current = value ?? min;
    sliderValueRef.current = sliderValue;
    const ownerDocument = event.currentTarget.ownerDocument;
    const handleDocumentPointerUp = () => {
      removeDragEndListenersRef.current?.();
      scheduleSliderCommit();
    };
    removeDragEndListenersRef.current = () => {
      ownerDocument.removeEventListener("pointerup", handleDocumentPointerUp, true);
      ownerDocument.removeEventListener("pointercancel", handleDocumentPointerUp, true);
      removeDragEndListenersRef.current = void 0;
    };
    ownerDocument.addEventListener("pointerup", handleDocumentPointerUp, true);
    ownerDocument.addEventListener("pointercancel", handleDocumentPointerUp, true);
  };
  const handleSliderChange = (sliderValue2) => {
    const newValue = typeof sliderValue2 === "number" ? sliderValue2 : sliderValue2[0];
    sliderValueRef.current = newValue;
    setSliderValue(newValue);
    setInputValue(newValue);
    onChange(newValue);
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Popover,
    {
      shown: isFocused,
      placement: "right",
      moveBy: { x: -inputWrapperDimensions.width - SLIDER_WIDTH - SLIDER_GAP - SLIDER_PADDING - 6 },
      zIndex: popoverZIndex,
      onClickOutside: () => setIsFocused(false),
      fixed: true,
      appendTo: appendToElement
    },
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Popover.Element, null, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        ref: inputWrapperRef,
        style: isFocused ? { position: "relative", zIndex: numberInputZIndex } : void 0
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_design_system.NumberInput,
        {
          inputRef,
          key: inputKey,
          size: "small",
          prefix,
          suffix,
          value: inputValue,
          min,
          max,
          onFocus: () => {
            setIsFocused(true);
          },
          onChange: (value2, stringValue) => {
            if (stringValue === "") {
              setInputValue("");
              return;
            }
            if (typeof value2 === "number") {
              onChange(value2);
              setInputValue(value2);
            }
          },
          onBlur: (e) => handleInputWithinBounds(e.target.value, true),
          onKeyDown: (e) => {
            if (["Enter", "Escape"].includes(e.key)) {
              handleInputWithinBounds(inputRef.current?.value, true);
            }
          },
          hideStepper: true,
          dataHook
        }
      )
    )),
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Popover.Content, null, /* @__PURE__ */ import_react.default.createElement("div", { className: import_input_with_slider_scss.default.sliderContainer }, /* @__PURE__ */ import_react.default.createElement("div", { style: { width: SLIDER_WIDTH }, onPointerDown: handleSliderDragStart }, /* @__PURE__ */ import_react.default.createElement(
      import_design_system.Slider,
      {
        gradientColor,
        displayMarks: false,
        min,
        max,
        value: sliderValue,
        onChange: handleSliderChange,
        displayTooltip: false
      }
    )), /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { width: inputWrapperDimensions.width })))
  );
};
//# sourceMappingURL=input-with-slider.js.map
