import {
  TextField
} from "./chunk-6RDK3FM2.js";

// src/components/NumberField/NumberField.tsx
import classNames from "classnames/dedupe";
import { useCallback, useEffect, useRef } from "react";
import "@simplybusiness/mobius/src/components/NumberField/NumberField.css";
import { jsx } from "react/jsx-runtime";
var NumberField = ({ ref, ...props }) => {
  const {
    minValue,
    maxValue,
    step,
    defaultValue,
    hideSpinButtons,
    className,
    ...otherProps
  } = props;
  const {
    onFocus: customOnFocus,
    onBlur: customOnBlur,
    ...rest
  } = otherProps;
  const focusedInputRef = useRef(null);
  const wheelHandler = useCallback((ev) => ev.preventDefault(), []);
  useEffect(() => {
    return () => {
      focusedInputRef.current?.removeEventListener("wheel", wheelHandler);
      focusedInputRef.current = null;
    };
  }, [wheelHandler]);
  const containerClasses = classNames("mobius-number-field", className, {
    "--hide-spin-buttons": hideSpinButtons
  });
  const handleBeforeInput = (event) => {
    const { data } = event.nativeEvent;
    if (step && Number.isInteger(step) && data === ".") {
      event.preventDefault();
    }
    if (minValue && minValue >= 0 && data === "-") {
      event.preventDefault();
    }
  };
  const handleBlur = (event) => {
    const { value } = event.target;
    const numValue = parseFloat(value);
    if (step && step > 1 && !isNaN(numValue)) {
      const baseValue = minValue ?? 0;
      const steps = Math.round((numValue - baseValue) / step);
      const snappedValue = baseValue + steps * step;
      if (snappedValue !== numValue) {
        event.target.value = snappedValue.toString();
        const changeEvent = new Event("change", { bubbles: true });
        event.target.dispatchEvent(changeEvent);
        const syntheticChangeEvent = {
          ...event,
          target: event.target,
          currentTarget: event.currentTarget
        };
        otherProps.onChange?.(syntheticChangeEvent);
      }
    }
    customOnBlur?.(event);
  };
  const forwardedProps = {
    ...rest,
    onFocus: (e) => {
      const el = e.currentTarget;
      focusedInputRef.current?.removeEventListener("wheel", wheelHandler);
      focusedInputRef.current = el;
      el.addEventListener("wheel", wheelHandler, { passive: false });
      customOnFocus?.(e);
    },
    onBlur: (e) => handleBlur(e)
  };
  return /* @__PURE__ */ jsx(
    TextField,
    {
      ...forwardedProps,
      className: containerClasses,
      onBeforeInput: handleBeforeInput,
      type: "number",
      min: minValue ?? void 0,
      max: maxValue ?? void 0,
      step,
      ref,
      defaultValue: defaultValue != null ? defaultValue?.toString() : defaultValue
    }
  );
};
NumberField.displayName = "NumberField";

export {
  NumberField
};
//# sourceMappingURL=chunk-VGFVSRWH.js.map
