"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;exports.__esModule = true;exports.DateRangePickerDataTids = exports.DateRangePicker = void 0;var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));var _taggedTemplateLiteralLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteralLoose"));var _react = _interopRequireWildcard(require("react"));

var _MobilePopup = require("../../internal/MobilePopup");
var _useLocaleForControl = require("../../lib/locale/useLocaleForControl");
var _Emotion = require("../../lib/theming/Emotion");

var _ThemeContext = require("../../lib/theming/ThemeContext");

var _CommonWrapper = require("../../internal/CommonWrapper");

var _Calendar = require("../Calendar");
var _Popup = require("../../internal/Popup");
var _DateInput = require("../DateInput");
var _comparison = require("../../lib/date/comparison");

var _ZIndex = require("../../internal/ZIndex");

var _rootNode = require("../../lib/rootNode");
var _getMenuPositions = require("../../lib/getMenuPositions");
var _Button = require("../Button");
var _ResponsiveLayout = require("../ResponsiveLayout");
var _InternalDate = require("../../lib/date/InternalDate");
var _InternalDateGetter = require("../../lib/date/InternalDateGetter");
var _ArrowAUp16Light = require("../../internal/icons2022/ArrowAUpIcon/ArrowAUp16Light");
var _NativeDateInput = require("../../internal/NativeDateInput");
var _forwardRefAndName = require("../../lib/forwardRefAndName");
var _locale = require("../../lib/locale");
var _client = require("../../lib/client");

var _DateRangePicker = require("./DateRangePicker.styles");
var _DateRangePickerSeparator = require("./DateRangePickerSeparator");

var _DateRangePickerContext = require("./DateRangePickerContext");

var _DateRangePickerInput = require("./DateRangePickerInput");
var _DateRangePickerTheme = require("./DateRangePickerTheme");
var _locale2 = require("./locale");
var _validateDateRangePicker = require("./helpers/validateDateRangePicker");
var _getStateForValue = require("./helpers/getStateForValue");var _templateObject, _templateObject2;

var DateRangePickerDataTids = exports.DateRangePickerDataTids = {
  root: 'DateRangePicker__root',
  start: 'DateRangePicker__start',
  end: 'DateRangePicker__end',
  popup: 'DateRangePicker__popup',
  calendar: 'DateRangePicker__calendar',
  todayButton: 'DateRangePicker__todayButton',
  startOptionalButton: 'DateRangePicker__startOptionalButton',
  endOptionalButton: 'DateRangePicker__endOptionalButton',
  mobileStart: 'DateRangePicker__mobileStart',
  mobileEnd: 'DateRangePicker__mobileEnd',
  rangeStart: 'DateRangePicker__rangeStart',
  rangeEnd: 'DateRangePicker__rangeEnd'
};

var DayDateAttribute = 'data-date-range-picker-day';






































var DateRangePicker = exports.DateRangePicker = Object.assign(
  {
    Start: _DateRangePickerInput.DateRangePickerStart,
    End: _DateRangePickerInput.DateRangePickerEnd,
    Separator: _DateRangePickerSeparator.DateRangePickerSeparator,
    validate: _validateDateRangePicker.validateDateRangePicker
  },
  (0, _forwardRefAndName.forwardRefAndName)('DateRangePicker', function (props, ref) {
    var _useResponsiveLayout = (0, _ResponsiveLayout.useResponsiveLayout)(),isMobile = _useResponsiveLayout.isMobile;
    var locale = (0, _useLocaleForControl.useLocaleForControl)('DateRangePicker', _locale2.DateRangePickerLocaleHelper);

    var _useState = (0, _react.useState)(),startValue = _useState[0],setStartValue = _useState[1];
    var _useState2 = (0, _react.useState)(false),startOptional = _useState2[0],setStartOptional = _useState2[1];
    var _useState3 = (0, _react.useState)(false),startDisabled = _useState3[0],setStartDisabled = _useState3[1];

    var _useState4 = (0, _react.useState)(),endValue = _useState4[0],setEndValue = _useState4[1];
    var _useState5 = (0, _react.useState)(false),endOptional = _useState5[0],setEndOptional = _useState5[1];
    var _useState6 = (0, _react.useState)(false),endDisabled = _useState6[0],setEndDisabled = _useState6[1];

    var _useState7 = (0, _react.useState)(''),minDate = _useState7[0],setMinDate = _useState7[1];
    var _useState8 = (0, _react.useState)(''),maxDate = _useState8[0],setMaxDate = _useState8[1];

    var _useState9 = (0, _react.useState)(null),hoveredDay = _useState9[0],setHoveredDay = _useState9[1];
    var _useState10 = (0, _react.useState)(false),showCalendar = _useState10[0],setShowCalendar = _useState10[1];
    var _useState11 = (0, _react.useState)(null),focusInput = _useState11[0],setFocusInput = _useState11[1];

    var dateRangePickerRef = (0, _react.useRef)(null);
    var calendarRef = (0, _react.useRef)(null);
    var startRef = (0, _react.useRef)(null);
    var endRef = (0, _react.useRef)(null);
    var mobileStartRef = (0, _react.useRef)(null);
    var mobileEndRef = (0, _react.useRef)(null);
    var mobileNativeStartRef = (0, _react.useRef)(null);
    var mobileNativeEndRef = (0, _react.useRef)(null);
    var isCalendarOpen = !startDisabled && !endDisabled && showCalendar;

    var updateDateRangeValues = function updateDateRangeValues(value) {if (value === void 0) {value = '';}
      var currentValues = {
        currentStart: startValue,
        currentEnd: endValue,
        minDate: minDate,
        maxDate: maxDate
      };
      var updatedState = (0, _getStateForValue.getStateForValue)(focusInput, value, currentValues);

      setStartValue(updatedState.start);
      setEndValue(updatedState.end);

      if (updatedState.isOpen && updatedState.focus) {
        focus(updatedState.focus);
      }

      if (!updatedState.isOpen) {
        close();
      }
    };

    var open = function open(inputType) {if (inputType === void 0) {inputType = 'start';}
      setFocusInput(inputType);
      setShowCalendar(true);
    };

    var close = function close() {
      setShowCalendar(false);
      setHoveredDay(null);
    };

    var focus = function focus(inputType) {if (inputType === void 0) {inputType = 'start';}
      setFocusInput(inputType);
    };

    var setEmpty = function setEmpty(type) {
      switch (type) {
        case 'start':
          setStartValue('');
          focus('end');
          break;

        case 'end':
          setEndValue('');
          close();
          break;
      }
    };

    (0, _react.useImperativeHandle)(
      ref,
      function () {return {
          open: open,
          close: close,
          scrollToMonth: function scrollToMonth(month, year) {var _calendarRef$current;
            (_calendarRef$current = calendarRef.current) == null || _calendarRef$current.scrollToMonth == null || _calendarRef$current.scrollToMonth(month, year);
          },
          getRootNode: function getRootNode() {return dateRangePickerRef.current;}
        };},
      []
    );

    (0, _react.useLayoutEffect)(function () {
      if (!focusInput) {
        return;
      }

      // fix DateInput flushSync warning in React 18
      setTimeout(function () {var _currentFieldRef$curr4;
        var isStart = focusInput === 'start';
        var currentFieldRef;

        // Mobile Native Picker
        if (isMobile && props.useMobileNativeDatePicker) {
          currentFieldRef = isStart ? mobileNativeStartRef : mobileNativeEndRef;
          if (_client.isIOS) {var _currentFieldRef$curr;
            (_currentFieldRef$curr = currentFieldRef.current) == null || _currentFieldRef$curr.focus();
          } else {var _currentFieldRef$curr2;
            // Android open native datepicker only via click
            (_currentFieldRef$curr2 = currentFieldRef.current) == null || _currentFieldRef$curr2.click();
          }
          return;
        }

        // Mobile
        if (isMobile) {var _currentFieldRef$curr3;
          currentFieldRef = isStart ? mobileStartRef : mobileEndRef;
          (_currentFieldRef$curr3 = currentFieldRef.current) == null || _currentFieldRef$curr3.focus();
          return;
        }

        // Desktop
        currentFieldRef = isStart ? startRef : endRef;
        (_currentFieldRef$curr4 = currentFieldRef.current) == null || _currentFieldRef$curr4.focus();
      });
    }, [focusInput]);

    var dateRangePickerContextProps = {
      startValue: startValue,
      startOptional: startOptional,
      startDisabled: startDisabled,
      endValue: endValue,
      endOptional: endOptional,
      endDisabled: endDisabled,
      minDate: minDate,
      maxDate: maxDate,
      size: props.size,
      setStartValue: setStartValue,
      setStartOptional: setStartOptional,
      setStartDisabled: setStartDisabled,
      setEndValue: setEndValue,
      setEndOptional: setEndOptional,
      setEndDisabled: setEndDisabled,
      setMinDate: setMinDate,
      setMaxDate: setMaxDate,
      setFocusInput: setFocusInput,
      open: open,
      close: close,
      dateRangePickerRef: dateRangePickerRef,
      startRef: startRef,
      endRef: endRef
    };

    var renderCalendar = function renderCalendar(theme, widthAuto) {var _cx;if (widthAuto === void 0) {widthAuto = false;}return /*#__PURE__*/(
        _react.default.createElement(_locale.LocaleContext.Provider, {
          value: {
            locale: {
              Calendar: {
                months: locale.months,
                dayCellChooseDateAriaLabel: locale.dayCellChooseDateAriaLabel,
                selectMonthAriaLabel: locale.selectMonthAriaLabel,
                selectYearAriaLabel: locale.selectYearAriaLabel,
                selectChosenAriaLabel: locale.selectChosenAriaLabel
              }
            }
          } }, /*#__PURE__*/

        _react.default.createElement(_Calendar.Calendar, {
          value: focusInput === 'start' ? startValue : endValue,
          minDate: minDate,
          maxDate: maxDate,
          renderDay: function renderDay(dayProps) {return renderCalendarRange(dayProps, theme, props.renderDay);},
          onValueChange: function onValueChange(value) {return updateDateRangeValues(value);},
          ref: calendarRef,
          onMonthChange: props.onMonthChange,
          className: (0, _Emotion.cx)((_cx = {}, _cx[_DateRangePicker.styles.calendarWidthAuto()] = widthAuto, _cx)) }
        )
        ));};


    var renderMobileCalendar = function renderMobileCalendar(theme) {var _cx2, _cx3;return /*#__PURE__*/(
        _react.default.createElement(_MobilePopup.MobilePopup, {
          opened: true,
          headerChildComponent: /*#__PURE__*/
          _react.default.createElement("div", { className: (0, _Emotion.cx)(_DateRangePicker.styles.root(theme), _DateRangePicker.styles.inputWrapperWidthFull()) }, /*#__PURE__*/
          _react.default.createElement(_DateInput.DateInput, {
            withIcon: true,
            value: startValue,
            width: "auto",
            size: "medium",
            className: (0, _Emotion.cx)((_cx2 = {}, _cx2[_DateRangePicker.styles.inputVisuallyFocus(theme)] = focusInput === 'start', _cx2)),
            disabled: startDisabled,
            onValueChange: setStartValue,
            onFocus: function onFocus() {return setFocusInput('start');},
            ref: mobileStartRef,
            "data-tid": DateRangePickerDataTids.mobileStart }
          ), /*#__PURE__*/
          _react.default.createElement(DateRangePicker.Separator, null), /*#__PURE__*/
          _react.default.createElement(_DateInput.DateInput, {
            withIcon: true,
            value: endValue,
            width: "auto",
            size: "medium",
            className: (0, _Emotion.cx)((_cx3 = {}, _cx3[_DateRangePicker.styles.inputVisuallyFocus(theme)] = focusInput === 'end', _cx3)),
            disabled: endDisabled,
            onValueChange: setEndValue,
            onFocus: function onFocus() {return setFocusInput('end');},
            ref: mobileEndRef,
            "data-tid": DateRangePickerDataTids.mobileEnd }
          )
          ),

          onCloseRequest: function onCloseRequest() {return close();},
          footerChildComponent: renderButtons() }, /*#__PURE__*/

        _react.default.createElement(_ThemeContext.ThemeContext.Provider, { value: (0, _DateRangePickerTheme.getMobileDateRangePickerTheme)(theme) },
        renderCalendar(theme, true)
        )
        ));};


    var getAnchorElement = function getAnchorElement() {
      var menuAnchorElement = props.menuAnchorElement;
      if (menuAnchorElement === 'focused') {
        return (0, _rootNode.getRootNode)(focusInput === 'start' ? startRef.current : endRef.current);
      }

      if ( /*#__PURE__*/_react.default.isValidElement(menuAnchorElement)) {
        return menuAnchorElement;
      }

      if (menuAnchorElement && typeof menuAnchorElement === 'object' && 'current' in menuAnchorElement) {
        return (0, _rootNode.getRootNode)(menuAnchorElement.current);
      }

      return (0, _rootNode.getRootNode)(startRef.current) || (0, _rootNode.getRootNode)(endRef.current) || (0, _rootNode.getRootNode)(dateRangePickerRef.current);
    };

    var renderDesktopCalendar = function renderDesktopCalendar(theme) {return /*#__PURE__*/(
        _react.default.createElement(_Popup.Popup, {
          opened: true,
          hasShadow: true,
          priority: _ZIndex.ZIndex.priorities.PopupMenu,
          positions: (0, _getMenuPositions.getMenuPositions)(props.menuPos, props.menuAlign),
          "data-tid": DateRangePickerDataTids.root,
          anchorElement: getAnchorElement(),
          margin: parseInt(theme.datePickerMenuOffsetY) }, /*#__PURE__*/

        _react.default.createElement("div", {
          className: _DateRangePicker.styles.calendarWrapper(theme),
          onMouseDown: function onMouseDown(e) {return e.preventDefault();},
          onMouseMove: handleCalendarRangeMouseMove },

        renderCalendar(theme),
        renderButtons()
        )
        ));};


    var renderButtons = function renderButtons() {
      var today = new _InternalDate.InternalDate(locale).
      setComponents(_InternalDateGetter.InternalDateGetter.getTodayComponents()).
      toString({ withPad: true, withSeparator: true });

      var hasOptionalButtons = startOptional || endOptional;
      return /*#__PURE__*/(
        _react.default.createElement("div", { className: (0, _Emotion.cx)(_DateRangePicker.styles.buttonWrap()) },
        hasOptionalButtons && /*#__PURE__*/
        _react.default.createElement(_react.default.Fragment, null,
        focusInput === 'start' && startOptional && /*#__PURE__*/
        _react.default.createElement(_Button.Button, {
          width: "100%",
          "data-tid": DateRangePickerDataTids.startOptionalButton,
          onClick: function onClick() {return setEmpty('start');} },

        locale.startDateEmpty
        ),

        focusInput === 'end' && endOptional && /*#__PURE__*/
        _react.default.createElement(_Button.Button, {
          width: "100%",
          "data-tid": DateRangePickerDataTids.endOptionalButton,
          onClick: function onClick() {return setEmpty('end');} },

        locale.endDateEmpty
        )

        ),


        props.enableTodayLink && /*#__PURE__*/
        _react.default.createElement(_Button.Button, {
          icon: /*#__PURE__*/_react.default.createElement(_ArrowAUp16Light.ArrowAUpIcon16Light, null),
          "aria-label": locale.todayAriaLabel,
          "data-tid": DateRangePickerDataTids.todayButton,
          onClick: function onClick() {return updateDateRangeValues(today);} },

        !hasOptionalButtons && locale.today
        )

        ));

    };

    var renderMobileNativeDateInput = function renderMobileNativeDateInput() {return /*#__PURE__*/(
        _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/
        _react.default.createElement(_NativeDateInput.NativeDateInput, {
          value: startValue,
          minDate: minDate,
          maxDate: maxDate,
          onValueChange: setStartValue,
          disabled: startDisabled,
          ref: mobileNativeStartRef }
        ), /*#__PURE__*/
        _react.default.createElement(_NativeDateInput.NativeDateInput, {
          value: endValue,
          minDate: minDate,
          maxDate: maxDate,
          onValueChange: setEndValue,
          disabled: endDisabled,
          ref: mobileNativeEndRef }
        )
        ));};


    return /*#__PURE__*/(
      _react.default.createElement(_ThemeContext.ThemeContext.Consumer, null,
      function (theme) {return /*#__PURE__*/(
          _react.default.createElement(_ThemeContext.ThemeContext.Provider, { value: (0, _DateRangePickerTheme.getDateRangePickerTheme)(theme) }, /*#__PURE__*/
          _react.default.createElement(_DateRangePickerContext.DateRangePickerContext.Provider, { value: dateRangePickerContextProps }, /*#__PURE__*/
          _react.default.createElement(_CommonWrapper.CommonWrapper, props, /*#__PURE__*/
          _react.default.createElement("div", {
            className: (0, _Emotion.cx)(
              _DateRangePicker.styles.root(theme),
              _DateRangePicker.styles.inputWrapperWidth(theme), (0,
              _Emotion.css)(_templateObject || (_templateObject = (0, _taggedTemplateLiteralLoose2.default)(["\n                      font-size: ", ";\n                    "])),
              (0, _DateRangePicker.getFontSize)(theme, props.size))

            ),
            role: "group",
            "aria-describedby": props['aria-describedby'],
            "aria-label": props['aria-label'],
            "aria-labelledby": props['aria-labelledby'],
            "data-tid": DateRangePickerDataTids.root,
            ref: dateRangePickerRef,
            style: { width: props.width } },

          props.children,

          props.useMobileNativeDatePicker && isMobile ?
          renderMobileNativeDateInput() :
          isCalendarOpen && (isMobile ? renderMobileCalendar(theme) : renderDesktopCalendar(theme))
          )
          )
          )
          ));}

      ));


    // Use parent mousemove event instead each CalendarDay's mouseenter / mouseover
    function handleCalendarRangeMouseMove(e) {
      if (!startValue && !endValue) {
        return;
      }

      var hoveredElement = e.target;
      if (!hoveredElement.hasAttribute(DayDateAttribute) && hoveredDay === null) {
        return;
      }

      var date = String(hoveredElement == null ? void 0 : hoveredElement.getAttribute(DayDateAttribute)) || null;
      setHoveredDay(date);
    }

    function renderCalendarRange(
    props,
    t,
    renderDayFn)
    {var _extends2, _cx4;
      var day = props.date;

      var isDayFirst = startValue === day;
      var isDayLast = endValue === day;
      var isDayInPeriod = Boolean(startValue && endValue && (0, _comparison.isBetween)(day, startValue, endValue));

      var hasHoveredDay = hoveredDay !== null;
      var isDayInHoveredPeriod =
      hasHoveredDay &&
      Boolean(
        focusInput === 'start' && endValue && (0, _comparison.isBetween)(day, hoveredDay, endValue) ||
        focusInput === 'end' && startValue && (0, _comparison.isBetween)(day, startValue, hoveredDay)
      );

      var hasLeftRoundings;
      var hasRightRoundings;

      if (hasHoveredDay) {
        var isDayBeforeFirstInPeriod = startValue ? (0, _comparison.isLess)(hoveredDay, startValue) : endValue;
        var isDayAfterLastInPeriod = endValue ? (0, _comparison.isGreater)(hoveredDay, endValue) : startValue;

        if (isDayFirst && ((0, _comparison.isGreaterOrEqual)(hoveredDay, startValue) || focusInput === 'end')) {
          hasLeftRoundings = true;
        }

        if (isDayLast && ((0, _comparison.isLessOrEqual)(hoveredDay, endValue) || focusInput === 'start')) {
          hasRightRoundings = true;
        }

        var isDayHovered = hoveredDay === day;
        if (isDayHovered) {
          if (isDayBeforeFirstInPeriod) {
            hasLeftRoundings = true;
          }

          if (isDayAfterLastInPeriod) {
            hasRightRoundings = true;
          }
        }
      } else {
        if (isDayFirst) {
          hasLeftRoundings = true;
        }

        if (isDayLast) {
          hasRightRoundings = true;
        }
      }

      var renderDayProps = (0, _extends3.default)({},
      props, (_extends2 = {}, _extends2[
      DayDateAttribute] = props.date, _extends2));


      var dataTid = null;
      if (isDayFirst) {
        dataTid = DateRangePickerDataTids.rangeStart;
      } else if (isDayLast) {
        dataTid = DateRangePickerDataTids.rangeEnd;
      }

      return /*#__PURE__*/(
        _react.default.createElement("div", {
          className: (0, _Emotion.cx)(
            _DateRangePicker.styles.rangeCalendarDay(), (0,
            _Emotion.css)(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteralLoose2.default)(["\n              background: ", ";\n              border-top-left-radius: ", ";\n              border-bottom-left-radius: ", ";\n              border-top-right-radius: ", ";\n              border-bottom-right-radius: ", ";\n            "])),
            isDayInPeriod && t.rangeCalendarCellBg,
            hasLeftRoundings && t.calendarCellBorderRadius,
            hasLeftRoundings && t.calendarCellBorderRadius,
            hasRightRoundings && t.calendarCellBorderRadius,
            hasRightRoundings && t.calendarCellBorderRadius), (_cx4 = {}, _cx4[


            _DateRangePicker.styles.rangeCalendarDayEnd(t)] = isDayFirst || isDayLast, _cx4[
            _DateRangePicker.styles.rangeCalendarDayHoverInPeriod(t)] = isDayInPeriod, _cx4[
            _DateRangePicker.styles.rangeCalendarDayInHoveredPeriod(t)] = isDayInHoveredPeriod, _cx4)

          ),
          "data-tid": dataTid },

        renderDayFn ? renderDayFn(renderDayProps) : /*#__PURE__*/_react.default.createElement(_Calendar.CalendarDay, renderDayProps)
        ));

    }
  })
);