// packages/components/src/number-control/index.tsx
import clsx from "clsx";
import { useRef, forwardRef } from "@wordpress/element";
import { isRTL, __ } from "@wordpress/i18n";
import { plus as plusIcon, reset as resetIcon } from "@wordpress/icons";
import { useMergeRefs } from "@wordpress/compose";
import deprecated from "@wordpress/deprecated";
import { Input, SpinButton, styles } from "./styles/number-control-styles.js";
import * as inputControlActionTypes from "../input-control/reducer/actions.js";
import { add, subtract, clamp, ensureValidStep } from "../utils/math.js";
import { ensureNumber, isValueEmpty } from "../utils/values.js";
import { HStack } from "../h-stack/index.js";
import { Spacer } from "../spacer/index.js";
import { useCx } from "../utils/index.js";
import { useDeprecated36pxDefaultSizeProp } from "../utils/use-deprecated-props.js";
import { maybeWarnDeprecated36pxSize } from "../utils/deprecated-36px-size.js";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
var noop = () => {
};
function UnforwardedNumberControl(props, forwardedRef) {
  const {
    __unstableStateReducer: stateReducerProp,
    className,
    dragDirection = "n",
    hideHTMLArrows = false,
    spinControls = hideHTMLArrows ? "none" : "native",
    isDragEnabled = true,
    isShiftStepEnabled = true,
    label,
    max = Infinity,
    min = -Infinity,
    required = false,
    shiftStep = 10,
    step = 1,
    spinFactor = 1,
    type: typeProp = "number",
    value: valueProp,
    size = "default",
    suffix,
    onChange = noop,
    __shouldNotWarnDeprecated36pxSize,
    ...restProps
  } = useDeprecated36pxDefaultSizeProp(props);
  maybeWarnDeprecated36pxSize({
    componentName: "NumberControl",
    size,
    __next40pxDefaultSize: restProps.__next40pxDefaultSize,
    __shouldNotWarnDeprecated36pxSize
  });
  if (hideHTMLArrows) {
    deprecated("wp.components.NumberControl hideHTMLArrows prop ", {
      alternative: 'spinControls="none"',
      since: "6.2",
      version: "6.3"
    });
  }
  const inputRef = useRef();
  const mergedRef = useMergeRefs([inputRef, forwardedRef]);
  const isStepAny = step === "any";
  const baseStep = isStepAny ? 1 : ensureNumber(step);
  const baseSpin = ensureNumber(spinFactor) * baseStep;
  const constrainValue = (value, stepOverride) => {
    if (!isStepAny) {
      value = ensureValidStep(value, min, stepOverride !== null && stepOverride !== void 0 ? stepOverride : baseStep);
    }
    return `${clamp(value, min, max)}`;
  };
  const baseValue = constrainValue(0);
  const autoComplete = typeProp === "number" ? "off" : void 0;
  const classes = clsx("components-number-control", className);
  const cx = useCx();
  const spinButtonClasses = cx(size === "small" && styles.smallSpinButtons);
  const spinValue = (value, direction, event) => {
    event?.preventDefault();
    const shift = event?.shiftKey && isShiftStepEnabled;
    const delta = shift ? ensureNumber(shiftStep) * baseSpin : baseSpin;
    let nextValue = isValueEmpty(value) ? baseValue : value;
    if (direction === "up") {
      nextValue = add(nextValue, delta);
    } else if (direction === "down") {
      nextValue = subtract(nextValue, delta);
    }
    return constrainValue(nextValue, shift ? delta : void 0);
  };
  const numberControlStateReducer = (state, action) => {
    const nextState = {
      ...state
    };
    const {
      type,
      payload
    } = action;
    const event = payload.event;
    const currentValue = nextState.value;
    if (type === inputControlActionTypes.PRESS_UP || type === inputControlActionTypes.PRESS_DOWN) {
      nextState.value = spinValue(currentValue, type === inputControlActionTypes.PRESS_UP ? "up" : "down", event);
    }
    if (type === inputControlActionTypes.DRAG && isDragEnabled) {
      const [x, y] = payload.delta;
      const enableShift = payload.shiftKey && isShiftStepEnabled;
      const modifier = enableShift ? ensureNumber(shiftStep) * baseSpin : baseSpin;
      let directionModifier;
      let delta;
      switch (dragDirection) {
        case "n":
          delta = y;
          directionModifier = -1;
          break;
        case "e":
          delta = x;
          directionModifier = isRTL() ? -1 : 1;
          break;
        case "s":
          delta = y;
          directionModifier = 1;
          break;
        case "w":
          delta = x;
          directionModifier = isRTL() ? 1 : -1;
          break;
      }
      if (delta !== 0) {
        delta = Math.ceil(Math.abs(delta)) * Math.sign(delta);
        const distance = delta * modifier * directionModifier;
        nextState.value = constrainValue(
          // @ts-expect-error TODO: Investigate if it's ok for currentValue to be undefined
          add(currentValue, distance),
          enableShift ? modifier : void 0
        );
      }
    }
    if (type === inputControlActionTypes.PRESS_ENTER || type === inputControlActionTypes.COMMIT) {
      const applyEmptyValue = required === false && currentValue === "";
      nextState.value = applyEmptyValue ? currentValue : (
        // @ts-expect-error TODO: Investigate if it's ok for currentValue to be undefined
        constrainValue(currentValue)
      );
    }
    return nextState;
  };
  const buildSpinButtonClickHandler = (direction) => (event) => onChange(String(spinValue(valueProp, direction, event)), {
    // Set event.target to the <input> so that consumers can use
    // e.g. event.target.validity.
    event: {
      ...event,
      target: inputRef.current
    }
  });
  return /* @__PURE__ */ _jsx(Input, {
    autoComplete,
    inputMode: "numeric",
    ...restProps,
    className: classes,
    dragDirection,
    hideHTMLArrows: spinControls !== "native",
    isDragEnabled,
    label,
    max: max === Infinity ? void 0 : max,
    min: min === -Infinity ? void 0 : min,
    ref: mergedRef,
    required,
    step,
    type: typeProp,
    value: valueProp,
    __unstableStateReducer: (state, action) => {
      var _stateReducerProp;
      const baseState = numberControlStateReducer(state, action);
      return (_stateReducerProp = stateReducerProp?.(baseState, action)) !== null && _stateReducerProp !== void 0 ? _stateReducerProp : baseState;
    },
    size,
    __shouldNotWarnDeprecated36pxSize: true,
    suffix: spinControls === "custom" ? /* @__PURE__ */ _jsxs(_Fragment, {
      children: [suffix, /* @__PURE__ */ _jsx(Spacer, {
        marginBottom: 0,
        marginRight: 2,
        children: /* @__PURE__ */ _jsxs(HStack, {
          spacing: 1,
          children: [/* @__PURE__ */ _jsx(SpinButton, {
            className: spinButtonClasses,
            icon: plusIcon,
            size: "small",
            label: __("Increment"),
            onClick: buildSpinButtonClickHandler("up")
          }), /* @__PURE__ */ _jsx(SpinButton, {
            className: spinButtonClasses,
            icon: resetIcon,
            size: "small",
            label: __("Decrement"),
            onClick: buildSpinButtonClickHandler("down")
          })]
        })
      })]
    }) : suffix,
    onChange
  });
}
var NumberControl = forwardRef(UnforwardedNumberControl);
var number_control_default = NumberControl;
export {
  NumberControl,
  number_control_default as default
};
//# sourceMappingURL=index.js.map
