"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "SingleSlider", {
    enumerable: true,
    get: function() {
        return SingleSlider;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _SliderBase = require("../SliderBase/SliderBase");
var _ui = require("../../ui");
var _utils = require("../../utils");
var _utils1 = require("../../../../utils");
var _Slidertokens = require("../../Slider.tokens");
var _SliderBasestyles = require("../SliderBase/SliderBase.styles");
var _Singlestyles = require("./Single.styles");
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 _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
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);
}
var clamp = function clamp(value, min, max) {
    return Math.max(min, Math.min(value, max));
};
var SingleSlider = function SingleSlider(_0) {
    var min = _0.min, max = _0.max, value = _0.value, disabled = _0.disabled, onChangeCommitted = _0.onChangeCommitted, onChange = _0.onChange, ariaLabel = _0.ariaLabel, label = _0.label, labelContentLeft = _0.labelContentLeft, labelContent = _0.labelContent, _0_sliderAlign = _0.sliderAlign, sliderAlign = _0_sliderAlign === void 0 ? 'left' : _0_sliderAlign, showScale = _0.showScale, showRangeValues = _0.showRangeValues, showCurrentValue = _0.showCurrentValue, hideMinValueDiff = _0.hideMinValueDiff, hideMaxValueDiff = _0.hideMaxValueDiff, _0_labelPlacement = _0.labelPlacement, labelPlacement = _0_labelPlacement === void 0 ? 'top' : _0_labelPlacement, rangeValuesPlacementOld = _0.rangeValuesPlacement, _0_scaleAlign = _0.scaleAlign, scaleAlign = _0_scaleAlign === void 0 ? 'bottom' : _0_scaleAlign, _0_multipleStepSize = _0.multipleStepSize, multipleStepSize = _0_multipleStepSize === void 0 ? 10 : _0_multipleStepSize, defaultValue = _0.defaultValue, _0_size = _0.size, size = _0_size === void 0 ? 'm' : _0_size, name = _0.name, _0_pointerSize = _0.pointerSize, pointerSize = _0_pointerSize === void 0 ? 'small' : _0_pointerSize, _0_pointerVisibility = _0.pointerVisibility, pointerVisibility = _0_pointerVisibility === void 0 ? 'always' : _0_pointerVisibility, _0_currentValueVisibility = _0.currentValueVisibility, currentValueVisibility = _0_currentValueVisibility === void 0 ? 'always' : _0_currentValueVisibility, _0_orientation = _0.orientation, orientation = _0_orientation === void 0 ? 'horizontal' : _0_orientation, reversed = _0.reversed, labelReversed = _0.labelReversed, rest = _object_without_properties(_0, [
        "min",
        "max",
        "value",
        "disabled",
        "onChangeCommitted",
        "onChange",
        "ariaLabel",
        "label",
        "labelContentLeft",
        "labelContent",
        "sliderAlign",
        "showScale",
        "showRangeValues",
        "showCurrentValue",
        "hideMinValueDiff",
        "hideMaxValueDiff",
        "labelPlacement",
        "rangeValuesPlacement",
        "scaleAlign",
        "multipleStepSize",
        "defaultValue",
        "size",
        "name",
        "pointerSize",
        "pointerVisibility",
        "currentValueVisibility",
        "orientation",
        "reversed",
        "labelReversed"
    ]);
    var _ref;
    var isVertical = orientation === 'vertical';
    var _useState = _sliced_to_array((0, _react.useState)(false), 2), isHovered = _useState[0], setIsHovered = _useState[1];
    var _useState1 = _sliced_to_array((0, _react.useState)({
        handlePosition: 0,
        stepSize: 0,
        railFillWidth: 0
    }), 2), state = _useState1[0], setState = _useState1[1];
    var innerRef = (0, _react.useRef)(null);
    var _useState2 = _sliced_to_array((0, _react.useState)(0), 2), startOffset = _useState2[0], setStartOffset = _useState2[1];
    var _useState3 = _sliced_to_array((0, _react.useState)(0), 2), endOffset = _useState3[0], setEndOffset = _useState3[1];
    var innerValue = clamp((_ref = value !== null && value !== void 0 ? value : defaultValue) !== null && _ref !== void 0 ? _ref : min, min, max);
    var _useState4 = _sliced_to_array((0, _react.useState)(innerValue), 2), dragValue = _useState4[0], setDragValue = _useState4[1];
    var stepSize = state.stepSize;
    var innerShowScale = showRangeValues || showScale;
    var innerShowCurrentValue = currentValueVisibility === 'hover' ? showCurrentValue && isHovered : showCurrentValue;
    var hasLabelContent = Boolean(label || labelContentLeft || labelContent) && (!isVertical || isVertical && sliderAlign !== 'none');
    var labelPlacementClass = !isVertical && (labelPlacement === 'outer' || labelPlacement === 'top') ? _Slidertokens.classes.labelPlacementOuter : _Slidertokens.classes.labelPlacementInner;
    var rangeValuesPlacement = rangeValuesPlacementOld === 'outer' || scaleAlign === 'bottom' ? 'outer' : 'inner';
    var scaleAlignClass = rangeValuesPlacement === 'outer' ? _Slidertokens.classes.rangeValuesPlacementOuter : _Slidertokens.classes.rangeValuesPlacementInner;
    var hideMinValueDiffClass = hideMinValueDiff && dragValue - min <= hideMinValueDiff ? _Slidertokens.classes.hideMinValue : '';
    var hideMaxValueDiffClass = hideMaxValueDiff && max - dragValue <= hideMaxValueDiff ? _Slidertokens.classes.hideMaxValue : '';
    var verticalOrientationClass = orientation === 'vertical' ? _Slidertokens.classes.verticalOrientation : '';
    var startLabelRef = (0, _react.useRef)(null);
    var endLabelRef = (0, _react.useRef)(null);
    var activeFirstValue = dragValue === min ? _Slidertokens.classes.activeRangeValue : undefined;
    var activeSecondValue = dragValue === max ? _Slidertokens.classes.activeRangeValue : undefined;
    (0, _react.useEffect)(function() {
        var visibleValue = reversed ? max - dragValue + min : dragValue;
        var localValue = Math.min(Math.max(visibleValue, min), max) - min;
        if (!isVertical && rangeValuesPlacement === 'outer') {
            var _startLabelRef_current, _endLabelRef_current;
            var startWidth = (_startLabelRef_current = startLabelRef.current) === null || _startLabelRef_current === void 0 ? void 0 : _startLabelRef_current.offsetWidth;
            if ((0, _utils1.isNumber)(startWidth)) {
                setStartOffset(Number(startWidth));
            }
            var endWidth = (_endLabelRef_current = endLabelRef.current) === null || _endLabelRef_current === void 0 ? void 0 : _endLabelRef_current.offsetWidth;
            if ((0, _utils1.isNumber)(endWidth)) {
                setEndOffset(Number(endWidth));
            }
        } else if (isVertical && innerShowScale && (sliderAlign === 'left' || sliderAlign === 'right')) {
            setStartOffset(12);
            setEndOffset(12);
        } else {
            setStartOffset(0);
            setEndOffset(0);
        }
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                handlePosition: stepSize * localValue,
                railFillWidth: stepSize * localValue
            });
        });
    }, [
        dragValue,
        innerShowScale,
        labelPlacement,
        stepSize,
        rangeValuesPlacement,
        min,
        max,
        isVertical,
        reversed,
        // для перерасчета размеров
        sliderAlign,
        size
    ]);
    var setStepSize = (0, _react.useCallback)(function(newStepSize) {
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                stepSize: newStepSize
            });
        });
    }, []);
    var onHandleChange = function onHandleChange(handleValue, data) {
        var newValue = Math.round(reversed ? max - handleValue + min : handleValue);
        var newHandlePosition = isVertical ? data.y : data.x;
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                railFillWidth: newHandlePosition
            });
        });
        if (onChange) {
            if (value !== undefined) {
                onChange(newValue);
            }
            if (name && !value) {
                onChange({
                    target: {
                        value: newValue,
                        name: name
                    }
                });
            }
        }
        setDragValue(newValue);
    };
    var onHandleChangeCommitted = (0, _react.useCallback)(function(handleValue, data) {
        var newValue = Math.round(reversed ? max - handleValue + min : handleValue);
        if (onChangeCommitted) {
            onChangeCommitted(newValue);
        }
        setState(function(prevState) {
            return _object_spread_props(_object_spread({}, prevState), {
                handlePosition: isVertical ? data.lastY : data.lastX,
                railFillWidth: isVertical ? data.lastY : data.lastX
            });
        });
        setDragValue(newValue);
    }, [
        isVertical,
        min,
        max,
        reversed
    ]);
    (0, _react.useEffect)(function() {
        if (value !== dragValue) {
            var _ref;
            var newValue = clamp((_ref = value !== null && value !== void 0 ? value : defaultValue) !== null && _ref !== void 0 ? _ref : min, min, max);
            var clampedValue = Math.max(min, Math.min(newValue, max));
            setDragValue(clampedValue);
        }
    }, [
        value,
        defaultValue,
        dragValue,
        min,
        max
    ]);
    var labelVerticalPlacement = reversed ? 'bottom' : 'top';
    var valuePlacement = sliderAlign === 'right' ? 'left' : 'right';
    var settings = _utils.sizeData[size][pointerSize === 'large' ? 'large' : 'small'];
    var onPointerEnter = function onPointerEnter() {
        setIsHovered(true);
    };
    var onPointerLeave = function onPointerLeave() {
        setIsHovered(false);
    };
    return /*#__PURE__*/ _react.default.createElement(_Singlestyles.SingleWrapper, {
        className: (0, _utils1.cx)(labelPlacementClass, scaleAlignClass, verticalOrientationClass, sliderAlign === 'right' && _Slidertokens.classes.labelAlignLeft, (sliderAlign === 'center' || sliderAlign === 'none') && _Slidertokens.classes.labelAlignCenter, sliderAlign === 'left' && _Slidertokens.classes.labelAlignRight, labelVerticalPlacement === 'bottom' && _Slidertokens.classes.labelPlacementBottom, labelReversed && _Slidertokens.classes.labelContentReversed),
        onPointerEnter: onPointerEnter,
        onPointerLeave: onPointerLeave
    }, hasLabelContent && /*#__PURE__*/ _react.default.createElement(_Singlestyles.LabelWrapper, null, (labelContentLeft || labelContent) && /*#__PURE__*/ _react.default.createElement(_Singlestyles.LabelContent, null, labelContent), label && /*#__PURE__*/ _react.default.createElement(_Singlestyles.Label, null, label)), /*#__PURE__*/ _react.default.createElement(_Singlestyles.SliderBaseWrapper, {
        className: (0, _utils1.cx)(!isVertical && rangeValuesPlacement === 'outer' && _Slidertokens.classes.rangeValuesPlacementOuter, !isVertical && rangeValuesPlacement !== 'outer' && _Slidertokens.classes.rangeValuesPlacementInner, verticalOrientationClass)
    }, innerShowScale && /*#__PURE__*/ _react.default.createElement(_Singlestyles.StyledRangeValue, {
        ref: startLabelRef,
        className: (0, _utils1.cx)(hideMinValueDiffClass, activeFirstValue)
    }, reversed ? max : min), /*#__PURE__*/ _react.default.createElement(_SliderBase.SliderBase, _object_spread({
        min: min,
        max: max,
        disabled: disabled,
        size: size,
        sliderAlign: sliderAlign,
        setStepSize: setStepSize,
        onChange: onHandleChangeCommitted,
        railFillWidth: state.railFillWidth,
        settings: settings,
        labelPlacement: labelPlacement,
        rangeValuesPlacement: rangeValuesPlacement,
        orientation: orientation,
        reversed: reversed
    }, rest), /*#__PURE__*/ _react.default.createElement(_ui.Handler, {
        size: pointerSize,
        visibility: pointerVisibility,
        isHovered: isHovered,
        orientation: orientation,
        stepSize: state.stepSize,
        onChangeCommitted: onHandleChangeCommitted,
        onChange: onHandleChange,
        position: state.handlePosition,
        min: min,
        max: max,
        startOffset: startOffset,
        endOffset: endOffset,
        value: dragValue,
        disabled: disabled,
        ariaLabel: ariaLabel,
        multipleStepSize: multipleStepSize,
        showCurrentValue: innerShowCurrentValue,
        valuePlacement: valuePlacement
    })), innerShowScale && /*#__PURE__*/ _react.default.createElement(_Singlestyles.StyledRangeValue, {
        ref: endLabelRef,
        className: (0, _utils1.cx)(_Slidertokens.classes.maxRangeValue, hideMaxValueDiffClass, activeSecondValue)
    }, reversed ? min : max)), /*#__PURE__*/ _react.default.createElement(_SliderBasestyles.InputHidden, _object_spread({
        name: name,
        type: "number",
        datatype: "slider-single",
        value: dragValue,
        ref: innerRef
    }, _utils1.noop)));
};
