function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import React, { useCallback, useEffect, useRef, useState } from "react";
import cls from "classnames";
import { SliderBase } from "../SliderBase/SliderBase";
import { Handler } from "../../ui";
import { isNumber, noop } from "../../../../utils";
import { sizeData } from "../../utils";
import { classes } from "../../Slider.tokens";
import { InputHidden } from "../SliderBase/SliderBase.styles";
import { SliderWrapper, InputsWrapper, Label, LabelContentLeft, LabelWrapper, StyledInput, DoubleWrapper } from "./Double.styles";
function getXCenterHandle(handle) {
    var _handle_parentElement_getBoundingClientRect, _handle_parentElement;
    var containerX = ((_handle_parentElement = handle.parentElement) === null || _handle_parentElement === void 0 ? void 0 : (_handle_parentElement_getBoundingClientRect = _handle_parentElement.getBoundingClientRect()) === null || _handle_parentElement_getBoundingClientRect === void 0 ? void 0 : _handle_parentElement_getBoundingClientRect.x) || 0;
    var handleRect = handle.getBoundingClientRect();
    var handlePosition = handleRect.x;
    return handlePosition - containerX;
}
export var DoubleSlider = function DoubleSlider(_0) {
    var min = _0.min, max = _0.max, value = _0.value, disabled = _0.disabled, label = _0.label, labelContentLeft = _0.labelContentLeft, _0_size = _0.size, size = _0_size === void 0 ? 'm' : _0_size, _0_pointerSize = _0.pointerSize, pointerSize = _0_pointerSize === void 0 ? 'small' : _0_pointerSize, onChangeCommitted = _0.onChangeCommitted, onChangeTextField = _0.onChangeTextField, onBlurTextField = _0.onBlurTextField, onKeyDownTextField = _0.onKeyDownTextField, onChange = _0.onChange, ariaLabel = _0.ariaLabel, _0_multipleStepSize = _0.multipleStepSize, multipleStepSize = _0_multipleStepSize === void 0 ? 10 : _0_multipleStepSize, name = _0.name, rest = _object_without_properties(_0, [
        "min",
        "max",
        "value",
        "disabled",
        "label",
        "labelContentLeft",
        "size",
        "pointerSize",
        "onChangeCommitted",
        "onChangeTextField",
        "onBlurTextField",
        "onKeyDownTextField",
        "onChange",
        "ariaLabel",
        "multipleStepSize",
        "name"
    ]);
    var _useState = _sliced_to_array(useState({
        stepSize: 0,
        railFillWidth: 0,
        railFillXPosition: 0,
        xFirstHandle: 0,
        xSecondHandle: 0,
        firstHandleZIndex: 100,
        secondHandleZIndex: 101,
        firstValue: value[0],
        secondValue: value[1]
    }), 2), state = _useState[0], setState = _useState[1];
    var _useState1 = _sliced_to_array(useState(false), 2), firstInputHovered = _useState1[0], setFirstInputHovered = _useState1[1];
    var _useState2 = _sliced_to_array(useState(false), 2), firstInputFocused = _useState2[0], setFirstInputFocused = _useState2[1];
    var _useState3 = _sliced_to_array(useState(false), 2), secondInputHovered = _useState3[0], setSecondInputHovered = _useState3[1];
    var _useState4 = _sliced_to_array(useState(false), 2), secondInputFocused = _useState4[0], setSecondInputFocused = _useState4[1];
    var _useState5 = _sliced_to_array(useState(value[0]), 2), firstValue = _useState5[0], setFirstValue = _useState5[1];
    var _useState6 = _sliced_to_array(useState(value[1]), 2), secondValue = _useState6[0], setSecondValue = _useState6[1];
    var handleClicked = useRef(false);
    var firstHandleRef = useRef(null);
    var secondHandleRef = useRef(null);
    var firstHandleValue = useRef(value[0]);
    var secondHandleValue = useRef(value[1]);
    var innerRefFirst = useRef(null);
    var innerRefSecond = useRef(null);
    var stepSize = state.stepSize;
    var hasLabelContent = label || labelContentLeft;
    var setStepSize = useCallback(function(newStepSize) {
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                stepSize: newStepSize
            });
        });
    }, [
        setState
    ]);
    var onFirstHandleChange = function onFirstHandleChange(handleValue, data) {
        if (!(secondHandleRef === null || secondHandleRef === void 0 ? void 0 : secondHandleRef.current)) {
            return;
        }
        var newHandleXPosition = data.x;
        var secondHandleXPosition = getXCenterHandle(secondHandleRef.current);
        var fillWidth = secondHandleXPosition - newHandleXPosition;
        firstHandleValue.current = handleValue;
        setFirstValue(handleValue);
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                firstHandleZIndex: 101,
                secondHandleZIndex: 100,
                railFillWidth: fillWidth < 0 ? 0 : fillWidth,
                railFillXPosition: newHandleXPosition
            });
        });
        if (onChange) {
            onChange([
                handleValue,
                value[1]
            ]);
        }
    };
    var onFirstHandleChangeCommitted = function onFirstHandleChangeCommitted(handleValue, data) {
        if (!(secondHandleRef === null || secondHandleRef === void 0 ? void 0 : secondHandleRef.current)) {
            return;
        }
        var newHandleXPosition = data.x;
        var secondHandleXPosition = getXCenterHandle(secondHandleRef.current);
        var fillWidth = secondHandleXPosition - newHandleXPosition;
        firstHandleValue.current = handleValue;
        setFirstValue(handleValue);
        if (onChangeCommitted) {
            onChangeCommitted([
                handleValue,
                value[1]
            ]);
        }
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                firstValue: handleValue,
                xFirstHandle: data.x,
                railFillWidth: fillWidth < 0 ? 0 : fillWidth,
                railFillXPosition: newHandleXPosition
            });
        });
    };
    var onFirstTextfieldChange = function onFirstTextfieldChange(event) {
        if (!isNumber(event.target.value)) {
            return;
        }
        var handleValue = Number(event.target.value);
        setFirstValue(handleValue);
        if (onChangeTextField) {
            onChangeTextField([
                handleValue,
                secondValue
            ], event);
        }
    };
    var onFirstTextfieldBlur = function onFirstTextfieldBlur(event) {
        setFirstInputFocused(false);
        setFirstInputHovered(false);
        if (!isNumber(event.target.value)) {
            return;
        }
        var handleValue = Number(event.target.value);
        setFirstValue(handleValue);
        if (onBlurTextField) {
            onBlurTextField && onBlurTextField([
                handleValue,
                secondValue
            ], event);
        }
    };
    var onSecondHandleChange = function onSecondHandleChange(handleValue, data) {
        if (!(firstHandleRef === null || firstHandleRef === void 0 ? void 0 : firstHandleRef.current)) {
            return;
        }
        var firstXHandleXPosition = getXCenterHandle(firstHandleRef.current);
        var newHandleXPosition = data.x;
        var fillWidth = newHandleXPosition - firstXHandleXPosition;
        secondHandleValue.current = handleValue;
        setSecondValue(handleValue);
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                firstHandleZIndex: 100,
                secondHandleZIndex: 101,
                railFillWidth: fillWidth < 0 ? 0 : fillWidth,
                railFillXPosition: firstXHandleXPosition
            });
        });
        if (onChange) {
            onChange([
                value[0],
                handleValue
            ]);
        }
    };
    var onSecondHandleChangeCommitted = function onSecondHandleChangeCommitted(handleValue, data) {
        if (!(firstHandleRef === null || firstHandleRef === void 0 ? void 0 : firstHandleRef.current)) {
            return;
        }
        var firstXHandleXPosition = getXCenterHandle(firstHandleRef.current);
        var newHandleXPosition = data.x;
        var fillWidth = newHandleXPosition - firstXHandleXPosition;
        secondHandleValue.current = handleValue;
        if (onChangeCommitted) {
            onChangeCommitted([
                value[0],
                handleValue
            ]);
        }
        setSecondValue(handleValue);
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                secondValue: handleValue,
                xSecondHandle: data.x,
                railFillWidth: fillWidth < 0 ? 0 : fillWidth,
                railFillXPosition: firstXHandleXPosition
            });
        });
    };
    var onSecondTextfieldChange = function onSecondTextfieldChange(event) {
        if (!isNumber(event.target.value)) {
            return;
        }
        var handleValue = Number(event.target.value);
        setSecondValue(handleValue);
        if (onChangeTextField) {
            onChangeTextField([
                firstValue,
                handleValue
            ], event);
        }
    };
    var onSecondTextfieldBlur = function onSecondTextfieldBlur(event) {
        setSecondInputFocused(false);
        setSecondInputHovered(false);
        if (!isNumber(event.target.value)) {
            return;
        }
        var handleValue = Number(event.target.value);
        setSecondValue(handleValue);
        if (onBlurTextField) {
            onBlurTextField([
                firstValue,
                handleValue
            ], event);
        }
    };
    var onTextfieldKeyDown = function onTextfieldKeyDown(event) {
        if (onKeyDownTextField) {
            onKeyDownTextField([
                firstValue,
                secondValue
            ], event);
        }
    };
    var _ref = _sliced_to_array(ariaLabel || [], 2), ariaLabelLeft = _ref[0], ariaLabelRight = _ref[1];
    var currentFirstSliderValue = Math.max(state.firstValue, min);
    var settings = sizeData[size][pointerSize === 'large' ? 'large' : 'small'];
    useEffect(function() {
        var firstLocalValue = Math.min(Math.max(value[0], min), max) - min;
        var secondLocalValue = Math.min(Math.max(value[1], min), max) - min;
        setFirstValue(value[0]);
        setSecondValue(value[1]);
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                railFillXPosition: stepSize * firstLocalValue,
                railFillWidth: stepSize * secondLocalValue - stepSize * firstLocalValue,
                xFirstHandle: stepSize * firstLocalValue,
                xSecondHandle: stepSize * secondLocalValue
            });
        });
    }, [
        value,
        stepSize,
        min,
        max,
        setFirstValue,
        setSecondValue
    ]);
    useEffect(function() {
        var onMouseUp = function onMouseUp() {
            if (handleClicked.current) {
                handleClicked.current = false;
                setFirstInputFocused(false);
                setSecondInputFocused(false);
            }
        };
        window.addEventListener('mouseup', onMouseUp);
        return function() {
            window.removeEventListener('mouseup', onMouseUp);
        };
    }, []);
    var _obj, _obj1;
    return /*#__PURE__*/ React.createElement(DoubleWrapper, null, hasLabelContent && /*#__PURE__*/ React.createElement(LabelWrapper, null, labelContentLeft && /*#__PURE__*/ React.createElement(LabelContentLeft, null, labelContentLeft), label && /*#__PURE__*/ React.createElement(Label, null, label)), /*#__PURE__*/ React.createElement(SliderWrapper, null, /*#__PURE__*/ React.createElement(SliderBase, _object_spread({
        min: min,
        max: max,
        size: size,
        disabled: disabled,
        setStepSize: setStepSize,
        railFillWidth: state.railFillWidth,
        settings: settings,
        railFillXPosition: state.railFillXPosition,
        orientation: "horizontal"
    }, rest), /*#__PURE__*/ React.createElement(Handler, {
        ref: firstHandleRef,
        size: pointerSize,
        stepSize: state.stepSize,
        multipleStepSize: multipleStepSize,
        onChangeCommitted: onFirstHandleChangeCommitted,
        onChange: onFirstHandleChange,
        min: min,
        max: state.secondValue,
        disabled: disabled,
        bounds: [
            min,
            state.secondValue
        ],
        side: "left",
        orientation: "horizontal",
        position: state.xFirstHandle,
        zIndex: state.firstHandleZIndex,
        value: currentFirstSliderValue,
        ariaLabel: ariaLabelLeft,
        onTouchStart: function onTouchStart() {
            handleClicked.current = true;
            setFirstInputFocused(true);
        },
        onTouchEnd: function onTouchEnd() {
            handleClicked.current = false;
            setFirstInputFocused(false);
        },
        onMouseDown: function onMouseDown() {
            handleClicked.current = true;
            setFirstInputFocused(true);
        },
        onMouseEnter: function onMouseEnter() {
            return setFirstInputHovered(true);
        },
        onMouseLeave: function onMouseLeave() {
            return setFirstInputHovered(false);
        }
    }), /*#__PURE__*/ React.createElement(Handler, {
        ref: secondHandleRef,
        size: pointerSize,
        stepSize: state.stepSize,
        multipleStepSize: multipleStepSize,
        onChangeCommitted: onSecondHandleChangeCommitted,
        onChange: onSecondHandleChange,
        min: min,
        ariaValueMin: currentFirstSliderValue,
        max: max,
        disabled: disabled,
        bounds: [
            state.firstValue,
            max
        ],
        side: "right",
        orientation: "horizontal",
        position: state.xSecondHandle,
        zIndex: state.secondHandleZIndex,
        value: Math.max(state.secondValue, min),
        ariaLabel: ariaLabelRight,
        onTouchStart: function onTouchStart() {
            handleClicked.current = true;
            setSecondInputFocused(true);
        },
        onTouchEnd: function onTouchEnd() {
            handleClicked.current = false;
            setSecondInputFocused(false);
        },
        onMouseDown: function onMouseDown() {
            handleClicked.current = true;
            setSecondInputFocused(true);
        },
        onMouseEnter: function onMouseEnter() {
            return setSecondInputHovered(true);
        },
        onMouseLeave: function onMouseLeave() {
            return setSecondInputHovered(false);
        }
    })), /*#__PURE__*/ React.createElement(InputsWrapper, null, /*#__PURE__*/ React.createElement(StyledInput, {
        className: cls(classes.firstTextField, (_obj = {}, _define_property(_obj, classes.textFieldHovered, !firstInputFocused && firstInputHovered && !disabled), _define_property(_obj, classes.textFieldFocused, firstInputFocused && !disabled), _obj)),
        enumerationType: "plain",
        disabled: disabled,
        value: firstValue,
        onChange: onFirstTextfieldChange,
        onFocus: function onFocus() {
            return setFirstInputFocused(true);
        },
        onBlur: onFirstTextfieldBlur,
        onKeyDown: onTextfieldKeyDown
    }), /*#__PURE__*/ React.createElement(StyledInput, {
        className: cls(classes.secondTextField, (_obj1 = {}, _define_property(_obj1, classes.textFieldHovered, !secondInputFocused && secondInputHovered && !disabled), _define_property(_obj1, classes.textFieldFocused, secondInputFocused && !disabled), _obj1)),
        enumerationType: "plain",
        disabled: disabled,
        value: secondValue,
        onChange: onSecondTextfieldChange,
        onFocus: function onFocus() {
            return setSecondInputFocused(true);
        },
        onBlur: onSecondTextfieldBlur,
        onKeyDown: onTextfieldKeyDown
    }))), /*#__PURE__*/ React.createElement(InputHidden, _object_spread({
        name: name,
        type: "number",
        datatype: "slider-double",
        "data-slidertype": "min",
        value: firstValue,
        ref: innerRefFirst
    }, noop)), /*#__PURE__*/ React.createElement(InputHidden, _object_spread({
        name: name,
        type: "number",
        datatype: "slider-double",
        "data-slidertype": "max",
        value: secondValue,
        ref: innerRefSecond
    }, noop)));
};
