'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var cls = require('classnames');
var reducer = require('../store/reducer.js');
var types = require('../store/types.js');
var CalendarBase_styles = require('../CalendarBase/CalendarBase.styles.js');
var Calendar_tokens = require('../Calendar.tokens.js');
var base = require('./variations/_view/base.js');
var base$1 = require('./variations/_size/base.js');
var base$2 = require('./variations/_tooltip-size/base.js');
var CalendarDouble_styles = require('./CalendarDouble.styles.js');
var useForkRef = require('../../../hooks/useForkRef.js');
var useCalendarNavigation = require('../hooks/useCalendarNavigation.js');
var useKeyNavigation = require('../hooks/useKeyNavigation.js');
var useCalendarDateChange = require('../hooks/useCalendarDateChange.js');
var CalendarHeader = require('../ui/CalendarHeader/CalendarHeader.js');
var CalendarDays = require('../ui/CalendarDays/CalendarDays.js');
var CalendarMonths = require('../ui/CalendarMonths/CalendarMonths.js');
var CalendarQuarters = require('../ui/CalendarQuarters/CalendarQuarters.js');
var CalendarYears = require('../ui/CalendarYears/CalendarYears.js');
var EventTooltip_styles = require('../ui/EventTooltip/EventTooltip.styles.js');
var calendarRangeHelper = require('../utils/calendarRangeHelper.js');
var constants = require('../utils/constants.js');
var calendarGridHelper = require('../utils/calendarGridHelper.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);
var cls__default = /*#__PURE__*/_interopDefault(cls);

var _StyledSeparator, _StyledSeparator2, _StyledSeparator3, _StyledSeparator4;
var _excluded = ["className", "value", "focusedDate", "min", "max", "renderFromDate", "includeEdgeDates", "type", "eventTooltipOptions", "eventList", "disabledList", "eventMonthList", "disabledMonthList", "eventQuarterList", "disabledQuarterList", "eventYearList", "disabledYearList", "locale", "stretched", "onChangeValue"];
/**
 * Компонент двойного календаря.
 */
var calendarDoubleRoot = function calendarDoubleRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (_ref, outerRootRef) {
    var className = _ref.className,
      externalValue = _ref.value,
      focusedDate = _ref.focusedDate,
      minDate = _ref.min,
      maxDate = _ref.max,
      renderFromDate = _ref.renderFromDate,
      includeEdgeDates = _ref.includeEdgeDates,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'Days' : _ref$type,
      eventTooltipOptions = _ref.eventTooltipOptions,
      eventList = _ref.eventList,
      disabledList = _ref.disabledList,
      eventMonthList = _ref.eventMonthList,
      disabledMonthList = _ref.disabledMonthList,
      eventQuarterList = _ref.eventQuarterList,
      disabledQuarterList = _ref.disabledQuarterList,
      eventYearList = _ref.eventYearList,
      disabledYearList = _ref.disabledYearList,
      _ref$locale = _ref.locale,
      locale = _ref$locale === void 0 ? 'ru' : _ref$locale,
      stretched = _ref.stretched,
      onChangeValue = _ref.onChangeValue,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(_ref, _excluded);
    var _useMemo = React.useMemo(function () {
        return Array.isArray(externalValue) ? externalValue : [externalValue];
      }, [externalValue]),
      _useMemo2 = _rollupPluginBabelHelpers.slicedToArray(_useMemo, 2),
      firstValue = _useMemo2[0],
      secondValue = _useMemo2[1];
    var value = focusedDate || secondValue || firstValue;
    var isSingleMode = !Array.isArray(externalValue);
    var _useState = React.useState(externalValue),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      internalValue = _useState2[0],
      setInternalValue = _useState2[1];
    var _useState3 = React.useState(externalValue),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      prevExternalForSelection = _useState4[0],
      setPrevExternalForSelection = _useState4[1];
    if (calendarRangeHelper.isValueUpdate(externalValue, prevExternalForSelection)) {
      setInternalValue(externalValue);
      setPrevExternalForSelection(externalValue);
    }
    var _useState5 = React.useState(),
      _useState6 = _rollupPluginBabelHelpers.slicedToArray(_useState5, 2),
      hoveredItem = _useState6[0],
      setHoveredItem = _useState6[1];
    var _useState7 = React.useState(type),
      _useState8 = _rollupPluginBabelHelpers.slicedToArray(_useState7, 2),
      prevType = _useState8[0],
      setPrevType = _useState8[1];
    var _useState9 = React.useState(value),
      _useState0 = _rollupPluginBabelHelpers.slicedToArray(_useState9, 2),
      prevValue = _useState0[0],
      setPrevValue = _useState0[1];
    var _useState1 = React.useState(0),
      _useState10 = _rollupPluginBabelHelpers.slicedToArray(_useState1, 2),
      outOfRangeKey = _useState10[0],
      setOutOfRangeKey = _useState10[1];
    var _useState11 = React.useState([]),
      _useState12 = _rollupPluginBabelHelpers.slicedToArray(_useState11, 2),
      eventNodes = _useState12[0],
      setEventNodes = _useState12[1];
    var eventTooltipTargetRef = React.useRef(null);
    var rootRef = React.useRef(null);
    var innerRootRef = useForkRef.useForkRef(rootRef, outerRootRef);
    var min = minDate && new Date(minDate);
    var max = maxDate && new Date(maxDate);
    if (min) {
      min.setHours(0, 0, 0, 0);
    }
    if (max) {
      max.setHours(23, 59, 59, 999);
    }
    var _useReducer = React.useReducer(reducer.reducer, reducer.getInitialState(value, min, renderFromDate, type, true)),
      _useReducer2 = _rollupPluginBabelHelpers.slicedToArray(_useReducer, 2),
      state = _useReducer2[0],
      dispatch = _useReducer2[1];
    var date = state.date,
      calendarState = state.calendarState,
      startYear = state.startYear,
      size = state.size;
    var _useState13 = React.useState(date),
      _useState14 = _rollupPluginBabelHelpers.slicedToArray(_useState13, 2),
      firstDate = _useState14[0],
      setFirstDate = _useState14[1];
    var _useState15 = React.useState(date),
      _useState16 = _rollupPluginBabelHelpers.slicedToArray(_useState15, 2),
      secondDate = _useState16[0],
      setSecondDate = _useState16[1];
    var _useCalendarNavigatio = useCalendarNavigation.useCalendarNavigation({
        calendarState: calendarState,
        date: date,
        dispatch: dispatch
      }),
      handleNext = _useCalendarNavigatio.handleNext,
      handlePrev = _useCalendarNavigatio.handlePrev;
    var _useKeyNavigation = useKeyNavigation.useKeyNavigation({
        isDouble: true,
        size: size,
        calendarState: calendarState,
        onNext: handleNext,
        onPrev: handlePrev
      }),
      _useKeyNavigation2 = _rollupPluginBabelHelpers.slicedToArray(_useKeyNavigation, 5),
      selectIndexes = _useKeyNavigation2[0],
      onKeyDown = _useKeyNavigation2[1],
      onSelectIndexes = _useKeyNavigation2[2],
      outerRefs = _useKeyNavigation2[3],
      isOutOfRange = _useKeyNavigation2[4];
    var handleOnChangeValue = React.useCallback(function (newDay, dateInfo) {
      if (isSingleMode && externalValue == null) {
        setInternalValue(newDay);
      }
      onChangeValue === null || onChangeValue === void 0 || onChangeValue(newDay, dateInfo);
    }, [onChangeValue, isSingleMode, externalValue]);
    var _useCalendarDateChang = useCalendarDateChange.useCalendarDateChange({
        type: type,
        onChangeValue: handleOnChangeValue,
        onSelectIndexes: onSelectIndexes,
        dispatch: dispatch
      }),
      handleOnChangeDay = _useCalendarDateChang.handleOnChangeDay,
      handleOnChangeMonth = _useCalendarDateChang.handleOnChangeMonth,
      handleOnChangeQuarter = _useCalendarDateChang.handleOnChangeQuarter,
      handleOnChangeYear = _useCalendarDateChang.handleOnChangeYear,
      handleUpdateCalendarState = _useCalendarDateChang.handleUpdateCalendarState;
    var updateSecondDate = function updateSecondDate() {
      if (calendarState === types.CalendarState.Days) {
        var _getNextDate = calendarGridHelper.getNextDate(date.year, date.monthIndex),
          _getNextDate2 = _rollupPluginBabelHelpers.slicedToArray(_getNextDate, 2),
          nextYear = _getNextDate2[0],
          nextMonthIndex = _getNextDate2[1];
        setSecondDate({
          year: nextYear,
          monthIndex: nextMonthIndex,
          day: date.day
        });
      }
      if (calendarState === types.CalendarState.Months || calendarState === types.CalendarState.Quarters) {
        setSecondDate({
          year: date.year + 1,
          monthIndex: date.monthIndex,
          day: date.day
        });
      }
      if (calendarState === types.CalendarState.Years) {
        setSecondDate({
          year: startYear + constants.YEAR_RENDER_COUNT,
          monthIndex: date.monthIndex,
          day: date.day
        });
      }
    };
    var getBoundaryDates = function getBoundaryDates() {
      // NOTE: Если установить индекс дня равным "0", то берется последнее число предыдущего месяца
      if (calendarState === types.CalendarState.Days) {
        return [new Date(firstDate.year, firstDate.monthIndex, 1), new Date(secondDate.year, secondDate.monthIndex + 1, 0)];
      }
      if (calendarState === types.CalendarState.Months || calendarState === types.CalendarState.Quarters) {
        return [new Date(firstDate.year, 0), new Date(secondDate.year, 12, 0)];
      }
      var endVisibleYear = startYear + constants.YEAR_RENDER_COUNT * 2 - 1;
      return [new Date(startYear, 0), new Date(endVisibleYear, 11)];
    };

    // Изменяем ключ каждый раз как пытаемся перейти на даты которые находятся за пределами min/max ограничений.
    // Это необходимо для того чтобы screen-reader корректно озвучивал уведомление aria-live="assertive"
    // о том что нет доступных дат
    var handleKeyDown = React.useCallback(function (event) {
      setOutOfRangeKey(function (previousState) {
        return Number(!previousState);
      });
      onKeyDown(event);
    }, [onKeyDown]);
    var handleTriggerEventTooltip = function handleTriggerEventTooltip(structureRef, events) {
      if (structureRef !== null && structureRef !== void 0 && structureRef.current && events !== null && events !== void 0 && events.length) {
        eventTooltipTargetRef.current = structureRef.current;
        setEventNodes(events);
      } else if (eventTooltipTargetRef.current !== null) {
        eventTooltipTargetRef.current = null;
        setEventNodes([]);
      }
    };
    var tooltipContent = function tooltipContent() {
      var TooltipBodyWrapper = eventTooltipOptions === null || eventTooltipOptions === void 0 ? void 0 : eventTooltipOptions.bodyWrapper;
      if (!TooltipBodyWrapper) {
        return eventNodes;
      }
      return /*#__PURE__*/React__default.default.createElement(TooltipBodyWrapper, null, eventNodes);
    };
    React.useEffect(function () {
      if (prevType !== calendarState) {
        dispatch({
          type: types.ActionType.UPDATE_CALENDAR_STATE,
          payload: {
            calendarState: calendarState,
            size: reducer.sizeMap[calendarState]["double"]
          }
        });
        setPrevType(calendarState);
      }
    }, [calendarState]);
    React.useEffect(function () {
      if (prevType !== type) {
        dispatch({
          type: types.ActionType.UPDATE_CALENDAR_STATE,
          payload: {
            calendarState: type,
            size: reducer.sizeMap[type]["double"]
          }
        });
        setPrevType(type);
      }
    }, [type]);
    React.useEffect(function () {
      if (value && prevValue && calendarRangeHelper.isValueUpdate(value, prevValue) || value && !prevValue) {
        var _getBoundaryDates = getBoundaryDates(),
          _getBoundaryDates2 = _rollupPluginBabelHelpers.slicedToArray(_getBoundaryDates, 2),
          minVisibleDate = _getBoundaryDates2[0],
          maxVisibleDate = _getBoundaryDates2[1];
        if (focusedDate || value > maxVisibleDate || value < minVisibleDate) {
          dispatch({
            type: types.ActionType.UPDATE_DATE,
            payload: {
              value: value
            }
          });
        }
      }
      if (!value && !prevValue) {
        dispatch({
          type: types.ActionType.UPDATE_DATE,
          payload: {
            value: renderFromDate || min || new Date()
          }
        });
      }
      setPrevValue(value);
    }, [value]);
    React.useEffect(function () {
      setFirstDate(date);
      updateSecondDate();
    }, [date, calendarState]);
    return /*#__PURE__*/React__default.default.createElement(Root, _rollupPluginBabelHelpers.extends({
      ref: innerRootRef,
      className: cls__default.default(className, _rollupPluginBabelHelpers.defineProperty({}, Calendar_tokens.classes.stretched, stretched)),
      "aria-label": constants.I18N.selectDate[locale],
      eventTooltipSize: eventTooltipOptions === null || eventTooltipOptions === void 0 ? void 0 : eventTooltipOptions.size
    }, rest), isOutOfRange && /*#__PURE__*/React__default.default.createElement(CalendarBase_styles.IsOutOfRange, {
      key: outOfRangeKey,
      "aria-atomic": "true",
      role: "alert",
      "aria-live": "assertive",
      "aria-relevant": "additions"
    }, "\u0414\u0430\u043B\u0435\u0435 \u043D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445 \u0434\u0430\u0442."), /*#__PURE__*/React__default.default.createElement(CalendarHeader.CalendarHeader, {
      isDouble: true,
      size: rest.size,
      firstDate: firstDate,
      secondDate: secondDate,
      startYear: startYear,
      type: calendarState,
      onPrev: handlePrev,
      onNext: handleNext,
      onUpdateCalendarState: handleUpdateCalendarState,
      locale: locale
    }), /*#__PURE__*/React__default.default.createElement(CalendarDouble_styles.StyledWrapper, null, calendarState === types.CalendarState.Days && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(CalendarDays.CalendarDays, {
      value: internalValue,
      date: firstDate,
      min: min,
      max: max,
      eventList: eventList,
      disabledList: disabledList,
      includeEdgeDates: includeEdgeDates,
      hoveredDay: hoveredItem,
      selectIndexes: selectIndexes,
      onChangeDay: handleOnChangeDay,
      onHoverDay: setHoveredItem,
      onSetSelected: onSelectIndexes,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      locale: locale,
      isDouble: true
    }), _StyledSeparator || (_StyledSeparator = /*#__PURE__*/React__default.default.createElement(CalendarDouble_styles.StyledSeparator, null)), /*#__PURE__*/React__default.default.createElement(CalendarDays.CalendarDays, {
      value: internalValue,
      date: secondDate,
      min: min,
      max: max,
      eventList: eventList,
      disabledList: disabledList,
      includeEdgeDates: includeEdgeDates,
      hoveredDay: hoveredItem,
      selectIndexes: selectIndexes,
      onChangeDay: handleOnChangeDay,
      onHoverDay: setHoveredItem,
      onSetSelected: onSelectIndexes,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      locale: locale,
      isDouble: true,
      isSecond: true
    })), calendarState === types.CalendarState.Months && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(CalendarMonths.CalendarMonths, {
      value: internalValue,
      date: firstDate,
      min: min,
      max: max,
      eventList: eventMonthList,
      disabledList: disabledMonthList,
      hoveredMonth: hoveredItem,
      selectIndexes: selectIndexes,
      onChangeMonth: handleOnChangeMonth,
      onSetSelected: onSelectIndexes,
      onHoverMonth: setHoveredItem,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      locale: locale,
      isDouble: true
    }), _StyledSeparator2 || (_StyledSeparator2 = /*#__PURE__*/React__default.default.createElement(CalendarDouble_styles.StyledSeparator, null)), /*#__PURE__*/React__default.default.createElement(CalendarMonths.CalendarMonths, {
      value: internalValue,
      date: secondDate,
      min: min,
      max: max,
      eventList: eventMonthList,
      disabledList: disabledMonthList,
      hoveredMonth: hoveredItem,
      selectIndexes: selectIndexes,
      onChangeMonth: handleOnChangeMonth,
      onSetSelected: onSelectIndexes,
      onHoverMonth: setHoveredItem,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      locale: locale,
      isDouble: true,
      isSecond: true
    })), calendarState === types.CalendarState.Quarters && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(CalendarQuarters.CalendarQuarters, {
      value: internalValue,
      date: firstDate,
      min: min,
      max: max,
      eventList: eventQuarterList,
      disabledList: disabledQuarterList,
      hoveredQuarter: hoveredItem,
      selectIndexes: selectIndexes,
      onChangeQuarter: handleOnChangeQuarter,
      onSetSelected: onSelectIndexes,
      onHoverQuarter: setHoveredItem,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      isDouble: true
    }), _StyledSeparator3 || (_StyledSeparator3 = /*#__PURE__*/React__default.default.createElement(CalendarDouble_styles.StyledSeparator, null)), /*#__PURE__*/React__default.default.createElement(CalendarQuarters.CalendarQuarters, {
      value: internalValue,
      date: secondDate,
      min: min,
      max: max,
      eventList: eventQuarterList,
      disabledList: disabledQuarterList,
      hoveredQuarter: hoveredItem,
      selectIndexes: selectIndexes,
      onChangeQuarter: handleOnChangeQuarter,
      onSetSelected: onSelectIndexes,
      onHoverQuarter: setHoveredItem,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      isDouble: true,
      isSecond: true
    })), calendarState === types.CalendarState.Years && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(CalendarYears.CalendarYears, {
      value: internalValue,
      date: firstDate,
      startYear: startYear,
      selectIndexes: selectIndexes,
      min: min,
      max: max,
      eventList: eventYearList,
      disabledList: disabledYearList,
      hoveredYear: hoveredItem,
      onChangeYear: handleOnChangeYear,
      onSetSelected: onSelectIndexes,
      onHoverYear: setHoveredItem,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      isDouble: true
    }), _StyledSeparator4 || (_StyledSeparator4 = /*#__PURE__*/React__default.default.createElement(CalendarDouble_styles.StyledSeparator, null)), /*#__PURE__*/React__default.default.createElement(CalendarYears.CalendarYears, {
      value: internalValue,
      date: secondDate,
      startYear: startYear + constants.YEAR_RENDER_COUNT,
      selectIndexes: selectIndexes,
      min: min,
      max: max,
      eventList: eventYearList,
      disabledList: disabledYearList,
      hoveredYear: hoveredItem,
      onChangeYear: handleOnChangeYear,
      onSetSelected: onSelectIndexes,
      onHoverYear: setHoveredItem,
      onTriggerEventTooltip: handleTriggerEventTooltip,
      onKeyDown: handleKeyDown,
      outerRefs: outerRefs,
      isDouble: true,
      isSecond: true
    }))), eventTooltipTargetRef.current && (eventNodes === null || eventNodes === void 0 ? void 0 : eventNodes.length) && /*#__PURE__*/React__default.default.createElement(EventTooltip_styles.EventTooltip, _rollupPluginBabelHelpers.extends({
      opened: Boolean(eventNodes === null || eventNodes === void 0 ? void 0 : eventNodes.length),
      target: eventTooltipTargetRef,
      frame: rootRef,
      text: tooltipContent(),
      trigger: "hover"
    }, eventTooltipOptions)));
  });
};
var calendarDoubleConfig = {
  name: 'CalendarDouble',
  tag: 'div',
  layout: calendarDoubleRoot,
  base: CalendarDouble_styles.StyledCalendar,
  variations: {
    view: {
      css: base.base
    },
    size: {
      css: base$1.base
    },
    eventTooltipSize: {
      css: base$2.base
    }
  },
  defaults: {
    view: 'primary',
    size: 'm',
    eventTooltipSizeCSS: 'm'
  }
};

exports.calendarDoubleConfig = calendarDoubleConfig;
exports.calendarDoubleRoot = calendarDoubleRoot;
