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(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _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 _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _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, { useRef, useState, forwardRef } from "react";
import Draggable from "react-draggable";
import { useForkRef } from "../../../../hooks";
import { cx } from "../../../../utils";
import { getSliderThumbValue, getOffsets } from "../../utils";
import { Thumb } from "../Thumb/Thumb";
import { classes } from "../../Slider.tokens";
import { HandlerStyled, StyledValue } from "./Handler.styles";
import { computeKeyPressData } from "./computeKeyPressData";
export var Handler = /*#__PURE__*/ forwardRef(function(_0, _1) {
    var _ref = [
        _0,
        _1
    ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), size = _ref2.size, visibility = _ref2.visibility, isHovered = _ref2.isHovered, orientation = _ref2.orientation, stepSize = _ref2.stepSize, onChangeCommitted = _ref2.onChangeCommitted, onChange = _ref2.onChange, _ref_position = _ref2.position, position = _ref_position === void 0 ? 0 : _ref_position, min = _ref2.min, max = _ref2.max, _ref_bounds = _ref2.bounds, bounds = _ref_bounds === void 0 ? [] : _ref_bounds, zIndex = _ref2.zIndex, disabled = _ref2.disabled, side = _ref2.side, _ref_showCurrentValue = _ref2.showCurrentValue, showCurrentValue = _ref_showCurrentValue === void 0 ? false : _ref_showCurrentValue, _ref_startOffset = _ref2.startOffset, startOffset = _ref_startOffset === void 0 ? 0 : _ref_startOffset, _ref_endOffset = _ref2.endOffset, endOffset = _ref_endOffset === void 0 ? 0 : _ref_endOffset, value = _ref2.value, valuePlacement = _ref2.valuePlacement, rest = _object_without_properties(_ref2, [
        "size",
        "visibility",
        "isHovered",
        "orientation",
        "stepSize",
        "onChangeCommitted",
        "onChange",
        "position",
        "min",
        "max",
        "bounds",
        "zIndex",
        "disabled",
        "side",
        "showCurrentValue",
        "startOffset",
        "endOffset",
        "value",
        "valuePlacement"
    ]), _rest1 = _sliced_to_array(_rest, 1), ref = _rest1[0];
    var nodeRef = useRef(null);
    var combinedRef = useForkRef(nodeRef, ref);
    var isVertical = orientation === 'vertical';
    var _useState = _sliced_to_array(useState(false), 2), isDrag = _useState[0], setIsDrag = _useState[1];
    var lastOnChangeValue = useRef();
    var _getOffsets = _sliced_to_array(getOffsets(nodeRef, side, isVertical), 2), startClientOffset = _getOffsets[0], endClientOffset = _getOffsets[1];
    var _bounds = _sliced_to_array(bounds, 2), startValueBound = _bounds[0], endValueBound = _bounds[1];
    var startPositionBound = startValueBound ? (startValueBound - min) * stepSize : null;
    var endPositionBound = endValueBound ? (endValueBound - min) * stepSize : null;
    var dragPosition = typeof position === 'number' ? {
        x: isVertical ? 0 : position,
        y: isVertical ? position : 0
    } : undefined;
    var tabIndex = disabled ? -1 : 0;
    var _obj;
    var computedBounds = (_obj = {}, _define_property(_obj, isVertical ? 'top' : 'left', (startPositionBound !== null && startPositionBound !== void 0 ? startPositionBound : 0) - (startClientOffset ? stepSize : 0)), _define_property(_obj, isVertical ? 'bottom' : 'right', (endPositionBound !== null && endPositionBound !== void 0 ? endPositionBound : stepSize * (max - min)) - (endClientOffset ? stepSize : 0)), _obj);
    var showCurrentValueCondition = showCurrentValue && (position >= startOffset && position <= max * stepSize - endOffset || position === 0 && value !== 0);
    var onDrag = function onDrag(_, data) {
        var newValue = getSliderThumbValue(isVertical ? data.y : data.x, stepSize, min, max);
        if (lastOnChangeValue.current !== newValue) {
            onChange === null || onChange === void 0 ? void 0 : onChange(newValue, data);
            lastOnChangeValue.current = newValue;
        }
    };
    var onStart = function onStart() {
        setIsDrag(true);
    };
    var onStop = function onStop(_, data) {
        setIsDrag(false);
        var newValue = getSliderThumbValue(isVertical ? data.y : data.x, stepSize, min, max);
        onChangeCommitted && onChangeCommitted(newValue, data);
    };
    var onKeyPress = function onKeyPress(event) {
        event.persist();
        var computedMultipleSteps = stepSize * (rest.multipleStepSize / 100 * max);
        var data = computeKeyPressData(event, {
            isVertical: isVertical,
            stepSize: stepSize,
            position: position,
            max: max,
            computedMultipleSteps: computedMultipleSteps
        });
        if (!data) {
            return;
        }
        var left = computedBounds.left, right = computedBounds.right, top = computedBounds.top, bottom = computedBounds.bottom;
        /*
             * INFO: Находим значение в диапазоне между указанными левой и правой границами.
             * Или между верхней и нижней
             * Необходимо для правильного расчета положения SliderThumb.
             * см. функция clamp
             */ var boundedValue = isVertical ? Math.max(Math.min(bottom, data.y), top) : Math.max(Math.min(right, data.x), left);
        var computedValue = getSliderThumbValue(boundedValue, stepSize, min, max);
        lastOnChangeValue.current = computedValue;
        onChangeCommitted && onChangeCommitted(computedValue, data);
    };
    var isPointerHidden = visibility === 'hover' && !isHovered || size === 'none';
    if (isDrag) {
        isPointerHidden = false;
    }
    return /*#__PURE__*/ React.createElement(Draggable, {
        nodeRef: nodeRef,
        axis: isVertical ? 'y' : 'x',
        bounds: computedBounds,
        grid: isVertical ? [
            1,
            stepSize
        ] : [
            stepSize,
            1
        ],
        onStart: onStart,
        onStop: onStop,
        onDrag: onDrag,
        position: dragPosition,
        disabled: disabled
    }, /*#__PURE__*/ React.createElement(HandlerStyled, {
        ref: combinedRef,
        style: {
            zIndex: zIndex
        },
        className: cx(isVertical && classes.verticalOrientation, valuePlacement === 'left' && classes.valuePlacementLeft),
        isLarge: size === 'large',
        isPointerHidden: isPointerHidden,
        onKeyDown: onKeyPress
    }, !isPointerHidden && /*#__PURE__*/ React.createElement(Thumb, _object_spread({
        tabIndex: tabIndex,
        min: min,
        max: max,
        value: value,
        disabled: disabled,
        orientation: orientation
    }, rest)), showCurrentValueCondition && /*#__PURE__*/ React.createElement(StyledValue, {
        isPointerHidden: isPointerHidden
    }, value)));
});
