import { n as AnalyticsId } from "./constants2.js";
import { t as usePseudoClasses } from "./usePseudoClasses.js";
import { n as mergeRefs, t as isMutableRefObject } from "./refs.js";
import { t as useIdWithFallback } from "./useIdWithFallback.js";
import { n as getAriaLabelAttributes } from "./accessibility.js";
import { t as ErrorWrapper_default } from "./ErrorWrapper.js";
import { t as useSize } from "./useSize.js";
import { t as Title_default } from "./Title2.js";
import classNames from "classnames";
import { useEffect, useId, useRef, useState } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import styles from "./components/Slider/styles.module.scss";
var useSafeNumberValue = (initial, min, max) => {
	const [value, setValue] = useState(initial);
	const [prevMin, setPrevMin] = useState(min);
	const [prevMax, setPrevMax] = useState(max);
	const getSafeValue = (newValue) => {
		if (newValue > max) return max;
		if (newValue < min) return min;
		return newValue;
	};
	const setSafeValue = (newValue) => {
		setValue(getSafeValue(newValue));
	};
	if (min !== prevMin || max !== prevMax) {
		setPrevMin(min);
		setPrevMax(max);
		const safeValue = getSafeValue(initial);
		if (safeValue !== value) setValue(safeValue);
	}
	return [value, setSafeValue];
};
const Slider = (props) => {
	const { title, ariaLabel, error, errorText, errorTextId: errorTextIdProp, errorWrapperClassName, labelLeft, labelRight, disabled = false, onChange, steps, step = 1, minValue = 0, maxValue = steps ? steps.length - 1 : 100, selected = true, testId, value, ref, ...rest } = props;
	const [isMoving, setIsMoving] = useState(false);
	const [selectedState, setSelectedState] = useState(typeof value === "undefined" ? selected : true);
	const [valueState, setValueState] = useSafeNumberValue(typeof value === "undefined" ? (maxValue - minValue) / 2 + minValue : value, minValue, maxValue);
	const errorTextId = useIdWithFallback(errorTextIdProp);
	const baseId = useId();
	const titleId = "title-" + baseId;
	const labelLeftId = "label-" + baseId;
	const labelRightId = "label-right-" + baseId;
	const trackRef = useRef(null);
	const { refObject, isFocused } = usePseudoClasses(isMutableRefObject(ref) ? ref : null);
	const mergedRefs = mergeRefs([ref, refObject]);
	const { width: trackWidth } = useSize(trackRef) || { width: 0 };
	const largeStep = maxValue / 10;
	const invalid = !!errorText || !!error;
	useEffect(() => {
		const handlePointerUp = () => {
			setIsMoving(false);
		};
		document.addEventListener("pointerup", handlePointerUp);
		return () => {
			document.removeEventListener("pointerup", handlePointerUp);
		};
	}, []);
	const getValueBasedOnMarkerPosition = (markerPosition) => {
		let value$1 = (markerPosition - (trackRef.current?.getBoundingClientRect().x ?? 0)) / trackWidth * (maxValue - minValue) + minValue;
		value$1 = Math.round(value$1 / step) * step;
		value$1 = Math.max(minValue, Math.min(maxValue, value$1));
		return value$1;
	};
	useEffect(() => {
		const handlePointerMove = (e) => {
			if (!disabled && isMoving) setValueState(getValueBasedOnMarkerPosition(e.clientX));
		};
		document.addEventListener("pointermove", handlePointerMove);
		return () => {
			document.removeEventListener("pointermove", handlePointerMove);
		};
	}, [isMoving]);
	useEffect(() => {
		if (value !== valueState && typeof value !== "undefined") {
			handleSelected();
			setValueState(value);
		}
	}, [value]);
	useEffect(() => {
		if (typeof value === "undefined" && selected !== selectedState) setSelectedState(selected);
	}, [selected]);
	const handleSelected = () => {
		if (selectedState === false) setSelectedState(true);
	};
	const handleKeyDown = (e) => {
		if (disabled) return;
		let flag = false;
		switch (e.key) {
			case "ArrowLeft":
			case "ArrowDown":
				setValueState(valueState - step);
				flag = true;
				break;
			case "PageDown":
				setValueState(valueState - largeStep);
				flag = true;
				break;
			case "ArrowRight":
			case "ArrowUp":
				setValueState(valueState + step);
				flag = true;
				break;
			case "PageUp":
				setValueState(valueState + largeStep);
				flag = true;
				break;
			case "Home":
				setValueState(minValue);
				flag = true;
				break;
			case "End":
				setValueState(maxValue);
				flag = true;
				break;
			default: break;
		}
		if (flag) {
			handleSelected();
			e.preventDefault();
			e.stopPropagation();
		}
	};
	const handleTrackClick = (e) => {
		if (disabled) return;
		setValueState(getValueBasedOnMarkerPosition(e.clientX));
		refObject.current?.focus();
	};
	const handlePointerDown = (e) => {
		if (disabled) return;
		handleTrackClick(e);
		setIsMoving(true);
		handleSelected();
		e.preventDefault();
		e.stopPropagation();
		refObject.current?.focus();
	};
	const markerXPos = maxValue !== minValue ? trackWidth / (maxValue - minValue) * (valueState - minValue) : 0;
	const getAriaValueText = () => {
		const stepIndex = steps ? Math.round((valueState - minValue) / step) : null;
		if (steps && stepIndex !== null && stepIndex >= 0 && stepIndex < steps.length) {
			const step$1 = steps[stepIndex];
			const emojiCode = step$1.emojiUniCode;
			const label = typeof step$1.label !== "undefined" ? step$1.label.toString() : void 0;
			return emojiCode && label ? `${emojiCode} ${label}` : emojiCode || label;
		}
	};
	const getAriaLabeledById = () => {
		if (title && labelLeft && labelRight) return [
			titleId,
			labelLeftId,
			labelRightId
		].join(" ");
		if (title && labelLeft) return [titleId, labelLeftId].join(" ");
		if (title && labelRight) return [titleId, labelRightId].join(" ");
		if (title) return titleId;
	};
	const ariaLabelAttributes = getAriaLabelAttributes({
		label: ariaLabel,
		id: getAriaLabeledById(),
		prefer: "label"
	});
	const getXPositionStyling = (index, stepsLength) => {
		return { left: `${index / (stepsLength - 1) * 100}%` };
	};
	useEffect(() => {
		if (selectedState && onChange) onChange({ target: {
			name: props.name,
			value: valueState
		} });
	}, [valueState, selectedState]);
	const renderEmojies = () => {
		return /* @__PURE__ */ jsx("div", {
			className: styles["slider__emoji-container"],
			children: steps?.map((step$1, index) => {
				return step$1.emojiUniCode && /* @__PURE__ */ jsx("div", {
					"aria-hidden": true,
					className: styles["slider__emoji"],
					style: getXPositionStyling(index, steps.length),
					children: step$1.emojiUniCode
				}, "emoji" + index);
			})
		});
	};
	const renderSteps = () => {
		return steps?.map((_step, index) => {
			return /* @__PURE__ */ jsx("div", {
				className: styles["slider__track__step"],
				style: getXPositionStyling(index, steps.length)
			}, "step" + index);
		});
	};
	const renderStepLabels = () => {
		return /* @__PURE__ */ jsx("div", {
			className: styles["slider__value-container"],
			children: steps?.map((step$1, index) => {
				return typeof step$1.label !== "undefined" && /* @__PURE__ */ jsx("div", {
					"aria-hidden": true,
					className: styles["slider__value"],
					style: getXPositionStyling(index, steps.length),
					children: step$1.label
				}, "label" + index);
			})
		});
	};
	return /* @__PURE__ */ jsxs(ErrorWrapper_default, {
		className: errorWrapperClassName,
		errorText,
		errorTextId,
		children: [/* @__PURE__ */ jsx("input", {
			"aria-valuetext": getAriaValueText(),
			className: styles["sr-only-slider"],
			disabled,
			min: minValue,
			max: maxValue,
			onChange,
			onKeyDown: handleKeyDown,
			value: valueState,
			ref: mergedRefs,
			type: "range",
			...rest,
			...ariaLabelAttributes
		}), /* @__PURE__ */ jsxs("div", {
			className: styles.slider,
			"data-testid": testId,
			"data-analyticsid": AnalyticsId.Slider,
			children: [
				title && /* @__PURE__ */ jsx(Title_default, {
					className: styles["slider__title"],
					htmlMarkup: "h3",
					margin: 0,
					appearance: "title3",
					id: titleId,
					children: title
				}),
				/* @__PURE__ */ jsxs("div", {
					className: styles["slider__content-container"],
					children: [
						renderEmojies(),
						/* @__PURE__ */ jsxs("div", {
							ref: trackRef,
							className: classNames(styles["slider__track-wrapper"], disabled && styles["slider__track-wrapper--disabled"]),
							onPointerDown: handlePointerDown,
							children: [/* @__PURE__ */ jsx("div", {
								className: classNames(styles.slider__track, disabled && styles["slider__track--disabled"]),
								children: renderSteps()
							}), /* @__PURE__ */ jsx("div", {
								className: classNames(styles.slider__marker, {
									[styles["slider__marker--disabled"]]: disabled,
									[styles["slider__marker--selected"]]: selectedState,
									[styles["slider__marker--invalid"]]: invalid,
									[styles["slider__marker--focused"]]: !disabled && isFocused
								}),
								style: { left: `${markerXPos}px` }
							})]
						}),
						renderStepLabels()
					]
				}),
				(labelLeft || labelRight) && /* @__PURE__ */ jsxs("span", {
					className: styles.slider__options,
					children: [/* @__PURE__ */ jsx("span", {
						id: labelLeftId,
						children: labelLeft
					}), /* @__PURE__ */ jsx("span", {
						id: labelRightId,
						children: labelRight
					})]
				})
			]
		})]
	});
};
Slider.displayName = "Slider";
var Slider_default$1 = Slider;
export { Slider as n, Slider_default$1 as t };

//# sourceMappingURL=Slider.js.map