function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { 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 _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(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(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { getKnobSize } from '../Slider/utils';
import { RangeSliderTrack } from './RangeSliderTrack';
import { SliderTrackHighlight } from '../Slider/SliderTrackHighlight';
import { isFunction, isNumber } from '../../common/utils';
import SliderKnobHandler from './SliderKnobHandler';
import { KnobType } from './constants';
import { clamp, percentToValue, roundValueToStep, valueToPercent } from './utils';
var Container = styled.div.withConfig({
  displayName: "RangeSlider__Container",
  componentId: "sc-omt3f0-0"
})(["display:flex;align-items:center;height:", ";margin:0 ", ";"], function (p) {
  return "".concat(getKnobSize(p.$variant), "px");
}, function (p) {
  return "".concat(getKnobSize(p.$variant) / 2, "px");
});
var getDefaultKnob = function getDefaultKnob(min, max, low, high) {
  if (isNumber(low) && isNumber(high) && low === high) {
    var distanceToMin = Math.abs(low - min);
    var distanceToMax = Math.abs(max - high);
    if (distanceToMax > distanceToMin) {
      return KnobType.HIGH;
    }
  }
  return KnobType.LOW;
};
var RangeSlider = function RangeSlider(_ref) {
  var defaultHighValue = _ref.defaultHighValue,
    defaultLowValue = _ref.defaultLowValue,
    disabledProp = _ref.disabled,
    max = _ref.max,
    min = _ref.min,
    onChange = _ref.onChange,
    readOnly = _ref.readOnly,
    sliderColor = _ref.sliderColor,
    step = _ref.step,
    _ref$variant = _ref.variant,
    variant = _ref$variant === void 0 ? 'big' : _ref$variant;
  var trackRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    initialized = _useState2[0],
    setInitialized = _useState2[1];
  var _useState3 = useState(getDefaultKnob(min, max, defaultLowValue, defaultHighValue)),
    _useState4 = _slicedToArray(_useState3, 2),
    activeHandle = _useState4[0],
    setActiveHandle = _useState4[1];
  var disabled = disabledProp || min > max || step <= 0 || !isNumber(defaultLowValue) || !isNumber(defaultHighValue) || defaultLowValue > defaultHighValue;
  useEffect(function () {
    if (!initialized) {
      setInitialized(true);
    }
  }, [initialized]);
  var lowHandleRef = useRef(null);
  var highHandleRef = useRef(null);
  var _useState5 = useState(isNumber(defaultLowValue) ? defaultLowValue : min || 0),
    _useState6 = _slicedToArray(_useState5, 2),
    lowValue = _useState6[0],
    setLowValue = _useState6[1];
  var minTrackPercent = valueToPercent(lowValue, min, max);
  var _useState7 = useState(isNumber(defaultHighValue) ? defaultHighValue : max || 0),
    _useState8 = _slicedToArray(_useState7, 2),
    highValue = _useState8[0],
    setHighValue = _useState8[1];
  var maxTrackPercent = valueToPercent(highValue, min, max);
  var updateValue = function updateValue(newValue) {
    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : KnobType.LOW;
    switch (type) {
      case KnobType.LOW:
        if (newValue > highValue) {
          return;
        }
        setLowValue(newValue);
        if (isFunction(onChange)) {
          onChange({
            low: newValue,
            high: highValue
          });
        }
        break;
      case KnobType.HIGH:
        if (newValue < lowValue) {
          return;
        }
        setHighValue(newValue);
        if (isFunction(onChange)) {
          onChange({
            low: lowValue,
            high: newValue
          });
        }
        break;
      default:
        break;
    }
  };
  var handleTrackClick = function handleTrackClick(event) {
    var pointerPosition = event.clientX;
    if (!disabled && !readOnly) {
      if (!trackRef.current || !pointerPosition) {
        return null;
      }
      var _trackRef$current$get = trackRef.current.getBoundingClientRect(),
        left = _trackRef$current$get.left,
        width = _trackRef$current$get.width;
      var diff = pointerPosition - left;
      var percent = diff / width;
      var newValue = percentToValue(percent, min, max);
      var difflowValue = Math.abs(newValue - lowValue);
      var diffhighValue = Math.abs(newValue - highValue);
      var newValueRounded = roundValueToStep(newValue, step, difflowValue < diffhighValue ? lowValue : highValue);
      var clampedValue = clamp(newValueRounded, min, max);
      if (clampedValue !== null) {
        if (difflowValue < diffhighValue || clampedValue < lowValue) {
          var _lowHandleRef$current;
          updateValue(clampedValue, KnobType.LOW);
          (_lowHandleRef$current = lowHandleRef.current) === null || _lowHandleRef$current === void 0 || _lowHandleRef$current.focus();
        } else if (difflowValue > diffhighValue || clampedValue > highValue) {
          var _highHandleRef$curren;
          updateValue(clampedValue, KnobType.HIGH);
          (_highHandleRef$curren = highHandleRef.current) === null || _highHandleRef$curren === void 0 || _highHandleRef$curren.focus();
        }
      }
    }
    return null;
  };
  return React.createElement(Container, {
    $disabled: disabled,
    $sliderColor: sliderColor,
    $variant: variant,
    onMouseDown: handleTrackClick,
    ref: trackRef,
    tabIndex: -1
  }, React.createElement(RangeSliderTrack, {
    variant: variant,
    sliderColor: sliderColor,
    readOnly: readOnly,
    disabled: disabled
  }, React.createElement(SliderTrackHighlight, {
    disabled: disabled,
    sliderColor: sliderColor,
    startValue: minTrackPercent,
    value: maxTrackPercent,
    variant: variant
  }), !readOnly && React.createElement(React.Fragment, null, React.createElement(SliderKnobHandler, {
    disabled: disabled,
    handleRef: lowHandleRef,
    knobType: KnobType.LOW,
    max: max,
    min: min,
    onChange: function onChange(value) {
      if (value <= highValue) {
        updateValue(value, KnobType.LOW);
      }
    },
    readOnly: readOnly,
    setActiveHandle: setActiveHandle,
    sliderColor: sliderColor,
    step: step,
    trackRef: trackRef,
    value: lowValue,
    variant: variant,
    zIndex: activeHandle === KnobType.LOW ? 2 : 1
  }), React.createElement(SliderKnobHandler, {
    disabled: disabled,
    handleRef: highHandleRef,
    knobType: KnobType.HIGH,
    max: max,
    min: min,
    onChange: function onChange(value) {
      if (value >= lowValue) {
        updateValue(value, KnobType.HIGH);
      }
    },
    readOnly: readOnly,
    setActiveHandle: setActiveHandle,
    sliderColor: sliderColor,
    step: step,
    trackRef: trackRef,
    value: highValue,
    variant: variant,
    zIndex: activeHandle === KnobType.HIGH ? 2 : 1
  }))));
};
export default RangeSlider;