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, { useState, useCallback, useMemo, forwardRef, useEffect, useReducer, useRef } from "react";
import cls from "classnames";
import { useForkRef } from "../../../hooks";
import { YEAR_RENDER_COUNT, getNextDate, isValueUpdate, I18N } from "../utils";
import { useKeyNavigation, useCalendarNavigation, useCalendarDateChange } from "../hooks";
import { CalendarDays, CalendarHeader, CalendarMonths, CalendarQuarters, CalendarYears, EventTooltip } from "../ui";
import { getInitialState, reducer, sizeMap } from "../store/reducer";
import { ActionType, CalendarState } from "../store/types";
import { IsOutOfRange } from "../CalendarBase/CalendarBase.styles";
import { classes } from "../Calendar.tokens";
import { base as viewCSS } from "./variations/_view/base";
import { base as sizeCSS } from "./variations/_size/base";
import { base as eventTooltipSizeCSS } from "./variations/_tooltip-size/base";
import { StyledCalendar, StyledSeparator, StyledWrapper } from "./CalendarDouble.styles";
/**
 * Компонент двойного календаря.
 */ export var calendarDoubleRoot = function calendarDoubleRoot(Root) {
    return /*#__PURE__*/ forwardRef(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), className = _ref2.className, externalValue = _ref2.value, minDate = _ref2.min, maxDate = _ref2.max, renderFromDate = _ref2.renderFromDate, includeEdgeDates = _ref2.includeEdgeDates, _ref_type = _ref2.type, type = _ref_type === void 0 ? 'Days' : _ref_type, eventTooltipOptions = _ref2.eventTooltipOptions, eventList = _ref2.eventList, disabledList = _ref2.disabledList, eventMonthList = _ref2.eventMonthList, disabledMonthList = _ref2.disabledMonthList, eventQuarterList = _ref2.eventQuarterList, disabledQuarterList = _ref2.disabledQuarterList, eventYearList = _ref2.eventYearList, disabledYearList = _ref2.disabledYearList, _ref_locale = _ref2.locale, locale = _ref_locale === void 0 ? 'ru' : _ref_locale, stretched = _ref2.stretched, onChangeValue = _ref2.onChangeValue, rest = _object_without_properties(_ref2, [
            "className",
            "value",
            "min",
            "max",
            "renderFromDate",
            "includeEdgeDates",
            "type",
            "eventTooltipOptions",
            "eventList",
            "disabledList",
            "eventMonthList",
            "disabledMonthList",
            "eventQuarterList",
            "disabledQuarterList",
            "eventYearList",
            "disabledYearList",
            "locale",
            "stretched",
            "onChangeValue"
        ]), _rest1 = _sliced_to_array(_rest, 1), outerRootRef = _rest1[0];
        var _useMemo = _sliced_to_array(useMemo(function() {
            return Array.isArray(externalValue) ? externalValue : [
                externalValue
            ];
        }, [
            externalValue
        ]), 2), firstValue = _useMemo[0], secondValue = _useMemo[1];
        var value = secondValue || firstValue;
        var _useState = _sliced_to_array(useState(), 2), hoveredItem = _useState[0], setHoveredItem = _useState[1];
        var _useState1 = _sliced_to_array(useState(type), 2), prevType = _useState1[0], setPrevType = _useState1[1];
        var _useState2 = _sliced_to_array(useState(value), 2), prevValue = _useState2[0], setPrevValue = _useState2[1];
        var _useState3 = _sliced_to_array(useState(0), 2), outOfRangeKey = _useState3[0], setOutOfRangeKey = _useState3[1];
        var _useState4 = _sliced_to_array(useState([]), 2), eventNodes = _useState4[0], setEventNodes = _useState4[1];
        var eventTooltipTargetRef = useRef(null);
        var rootRef = useRef(null);
        var innerRootRef = useForkRef(rootRef, outerRootRef);
        var min = minDate && new Date(minDate);
        var max = maxDate && new Date(maxDate);
        if (min) {
            min.setHours(0, 0, 0);
        }
        if (max) {
            max.setHours(23, 59, 59);
        }
        var _useReducer = _sliced_to_array(useReducer(reducer, getInitialState(value, min, renderFromDate, type, true)), 2), state = _useReducer[0], dispatch = _useReducer[1];
        var date = state.date, calendarState = state.calendarState, startYear = state.startYear, size = state.size;
        var _useState5 = _sliced_to_array(useState(date), 2), firstDate = _useState5[0], setFirstDate = _useState5[1];
        var _useState6 = _sliced_to_array(useState(date), 2), secondDate = _useState6[0], setSecondDate = _useState6[1];
        var _useCalendarNavigation = useCalendarNavigation({
            calendarState: calendarState,
            date: date,
            dispatch: dispatch
        }), handleNext = _useCalendarNavigation.handleNext, handlePrev = _useCalendarNavigation.handlePrev;
        var _useKeyNavigation = _sliced_to_array(useKeyNavigation({
            isDouble: true,
            size: size,
            calendarState: calendarState,
            onNext: handleNext,
            onPrev: handlePrev
        }), 5), selectIndexes = _useKeyNavigation[0], onKeyDown = _useKeyNavigation[1], onSelectIndexes = _useKeyNavigation[2], outerRefs = _useKeyNavigation[3], isOutOfRange = _useKeyNavigation[4];
        var _useCalendarDateChange = useCalendarDateChange({
            type: type,
            onChangeValue: onChangeValue,
            onSelectIndexes: onSelectIndexes,
            dispatch: dispatch
        }), handleOnChangeDay = _useCalendarDateChange.handleOnChangeDay, handleOnChangeMonth = _useCalendarDateChange.handleOnChangeMonth, handleOnChangeQuarter = _useCalendarDateChange.handleOnChangeQuarter, handleOnChangeYear = _useCalendarDateChange.handleOnChangeYear, handleUpdateCalendarState = _useCalendarDateChange.handleUpdateCalendarState;
        var updateSecondDate = function updateSecondDate() {
            if (calendarState === CalendarState.Days) {
                var _getNextDate = _sliced_to_array(getNextDate(date.year, date.monthIndex), 2), nextYear = _getNextDate[0], nextMonthIndex = _getNextDate[1];
                setSecondDate({
                    year: nextYear,
                    monthIndex: nextMonthIndex,
                    day: date.day
                });
            }
            if (calendarState === CalendarState.Months || calendarState === CalendarState.Quarters) {
                setSecondDate({
                    year: date.year + 1,
                    monthIndex: date.monthIndex,
                    day: date.day
                });
            }
            if (calendarState === CalendarState.Years) {
                setSecondDate({
                    year: startYear + YEAR_RENDER_COUNT,
                    monthIndex: date.monthIndex,
                    day: date.day
                });
            }
        };
        var getBoundaryDates = function getBoundaryDates() {
            // NOTE: Если установить индекс дня равным "0", то берется последнее число предыдущего месяца
            if (calendarState === CalendarState.Days) {
                return [
                    new Date(firstDate.year, firstDate.monthIndex, 1),
                    new Date(secondDate.year, secondDate.monthIndex + 1, 0)
                ];
            }
            if (calendarState === CalendarState.Months || calendarState === CalendarState.Quarters) {
                return [
                    new Date(firstDate.year, 0),
                    new Date(secondDate.year, 12, 0)
                ];
            }
            var endVisibleYear = startYear + YEAR_RENDER_COUNT * 2 - 1;
            return [
                new Date(startYear, 0),
                new Date(endVisibleYear, 11)
            ];
        };
        // Изменяем ключ каждый раз как пытаемся перейти на даты которые находятся за пределами min/max ограничений.
        // Это необходимо для того чтобы screen-reader корректно озвучивал уведомление aria-live="assertive"
        // о том что нет доступных дат
        var handleKeyDown = useCallback(function(event) {
            setOutOfRangeKey(function(previousState) {
                return Number(!previousState);
            });
            onKeyDown(event);
        }, [
            onKeyDown
        ]);
        var handleTriggerEventTooltip = function handleTriggerEventTooltip(structureRef, events) {
            if ((structureRef === null || structureRef === void 0 ? void 0 : structureRef.current) && (events === null || events === void 0 ? 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.createElement(TooltipBodyWrapper, null, eventNodes);
        };
        useEffect(function() {
            if (prevType !== calendarState) {
                dispatch({
                    type: ActionType.UPDATE_CALENDAR_STATE,
                    payload: {
                        calendarState: calendarState,
                        size: sizeMap[calendarState].double
                    }
                });
                setPrevType(calendarState);
            }
        }, [
            calendarState
        ]);
        useEffect(function() {
            if (prevType !== type) {
                dispatch({
                    type: ActionType.UPDATE_CALENDAR_STATE,
                    payload: {
                        calendarState: type,
                        size: sizeMap[type].double
                    }
                });
                setPrevType(type);
            }
        }, [
            type
        ]);
        useEffect(function() {
            if (value && prevValue && isValueUpdate(value, prevValue) || value && !prevValue) {
                var _getBoundaryDates = _sliced_to_array(getBoundaryDates(), 2), minVisibleDate = _getBoundaryDates[0], maxVisibleDate = _getBoundaryDates[1];
                if (value > maxVisibleDate || value < minVisibleDate) {
                    dispatch({
                        type: ActionType.UPDATE_DATE,
                        payload: {
                            value: value
                        }
                    });
                }
            }
            if (!value && !prevValue) {
                dispatch({
                    type: ActionType.UPDATE_DATE,
                    payload: {
                        value: renderFromDate || min || new Date()
                    }
                });
            }
            setPrevValue(value);
        }, [
            value
        ]);
        useEffect(function() {
            setFirstDate(date);
            updateSecondDate();
        }, [
            date,
            calendarState
        ]);
        return /*#__PURE__*/ React.createElement(Root, _object_spread({
            ref: innerRootRef,
            className: cls(className, _define_property({}, classes.stretched, stretched)),
            "aria-label": I18N.selectDate[locale],
            eventTooltipSize: eventTooltipOptions === null || eventTooltipOptions === void 0 ? void 0 : eventTooltipOptions.size
        }, rest), isOutOfRange && /*#__PURE__*/ React.createElement(IsOutOfRange, {
            key: outOfRangeKey,
            "aria-atomic": "true",
            role: "alert",
            "aria-live": "assertive",
            "aria-relevant": "additions"
        }, "Далее нет доступных дат."), /*#__PURE__*/ React.createElement(CalendarHeader, {
            isDouble: true,
            size: rest.size,
            firstDate: firstDate,
            secondDate: secondDate,
            startYear: startYear,
            type: calendarState,
            onPrev: handlePrev,
            onNext: handleNext,
            onUpdateCalendarState: handleUpdateCalendarState,
            locale: locale
        }), /*#__PURE__*/ React.createElement(StyledWrapper, null, calendarState === CalendarState.Days && /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(CalendarDays, {
            value: externalValue,
            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
        }), /*#__PURE__*/ React.createElement(StyledSeparator, null), /*#__PURE__*/ React.createElement(CalendarDays, {
            value: externalValue,
            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 === CalendarState.Months && /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(CalendarMonths, {
            value: externalValue,
            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
        }), /*#__PURE__*/ React.createElement(StyledSeparator, null), /*#__PURE__*/ React.createElement(CalendarMonths, {
            value: externalValue,
            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 === CalendarState.Quarters && /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(CalendarQuarters, {
            value: externalValue,
            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
        }), /*#__PURE__*/ React.createElement(StyledSeparator, null), /*#__PURE__*/ React.createElement(CalendarQuarters, {
            value: externalValue,
            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 === CalendarState.Years && /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(CalendarYears, {
            value: externalValue,
            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
        }), /*#__PURE__*/ React.createElement(StyledSeparator, null), /*#__PURE__*/ React.createElement(CalendarYears, {
            value: externalValue,
            date: secondDate,
            startYear: startYear + 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.createElement(EventTooltip, _object_spread({
            opened: Boolean(eventNodes === null || eventNodes === void 0 ? void 0 : eventNodes.length),
            target: eventTooltipTargetRef,
            frame: rootRef,
            text: tooltipContent(),
            trigger: "hover"
        }, eventTooltipOptions)));
    });
};
export var calendarDoubleConfig = {
    name: 'CalendarDouble',
    tag: 'div',
    layout: calendarDoubleRoot,
    base: StyledCalendar,
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        },
        eventTooltipSize: {
            css: eventTooltipSizeCSS
        }
    },
    defaults: {
        view: 'primary',
        size: 'm',
        eventTooltipSizeCSS: 'm'
    }
};
