"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get calendarBaseConfig () {
        return calendarBaseConfig;
    },
    get calendarBaseRoot () {
        return calendarBaseRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _classnames = /*#__PURE__*/ _interop_require_default(require("classnames"));
const _hooks = require("../../../hooks");
const _reducer = require("../store/reducer");
const _types = require("../store/types");
const _utils = require("../utils");
const _hooks1 = require("../hooks");
const _ui = require("../ui");
const _Calendartokens = require("../Calendar.tokens");
const _base = require("./variations/_view/base");
const _base1 = require("./variations/_size/base");
const _base2 = require("./variations/_tooltip-size/base");
const _CalendarBasestyles = require("./CalendarBase.styles");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const calendarBaseRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ className, value: externalValue, focusedDate, min: minDate, max: maxDate, renderFromDate, includeEdgeDates, type = 'Days', eventTooltipOptions, eventList, disabledList, eventMonthList, disabledMonthList, eventQuarterList, disabledQuarterList, eventYearList, disabledYearList, locale = 'ru', stretched, onChangeValue, ...rest }, outerRootRef)=>{
        const [firstValue, secondValue] = (0, _react.useMemo)(()=>Array.isArray(externalValue) ? externalValue : [
                externalValue
            ], [
            externalValue
        ]);
        const value = focusedDate || secondValue || firstValue;
        const isSingleMode = !Array.isArray(externalValue);
        const [internalValue, setInternalValue] = (0, _react.useState)(externalValue);
        const [prevExternalForSelection, setPrevExternalForSelection] = (0, _react.useState)(externalValue);
        if ((0, _utils.isValueUpdate)(externalValue, prevExternalForSelection)) {
            setInternalValue(externalValue);
            setPrevExternalForSelection(externalValue);
        }
        const [hoveredItem, setHoveredItem] = (0, _react.useState)();
        const [prevType, setPrevType] = (0, _react.useState)(type);
        const [prevValue, setPrevValue] = (0, _react.useState)(value);
        const [outOfRangeKey, setOutOfRangeKey] = (0, _react.useState)(0);
        const [eventNodes, setEventNodes] = (0, _react.useState)([]);
        const eventTooltipTargetRef = (0, _react.useRef)(null);
        const rootRef = (0, _react.useRef)(null);
        const innerRootRef = (0, _hooks.useForkRef)(rootRef, outerRootRef);
        const min = minDate && new Date(minDate);
        const max = maxDate && new Date(maxDate);
        if (min) {
            min.setHours(0, 0, 0, 0);
        }
        if (max) {
            max.setHours(23, 59, 59, 999);
        }
        const renderFrom = renderFromDate && new Date(renderFromDate);
        const [state, dispatch] = (0, _react.useReducer)(_reducer.reducer, (0, _reducer.getInitialState)(value, min, renderFrom, type));
        const { date, calendarState, startYear, size } = state;
        const { handleNext, handlePrev } = (0, _hooks1.useCalendarNavigation)({
            calendarState,
            date,
            dispatch
        });
        const [selectIndexes, onKeyDown, onSelectIndexes, outerRefs, isOutOfRange] = (0, _hooks1.useKeyNavigation)({
            size,
            calendarState,
            onNext: handleNext,
            onPrev: handlePrev
        });
        const handleOnChangeValue = (0, _react.useCallback)((newDay, dateInfo)=>{
            if (isSingleMode && externalValue == null) {
                setInternalValue(newDay);
            }
            onChangeValue?.(newDay, dateInfo);
        }, [
            onChangeValue,
            isSingleMode,
            externalValue
        ]);
        const { handleOnChangeDay, handleOnChangeMonth, handleOnChangeQuarter, handleOnChangeYear, handleUpdateCalendarState } = (0, _hooks1.useCalendarDateChange)({
            type,
            onChangeValue: handleOnChangeValue,
            onSelectIndexes,
            dispatch
        });
        // Изменяем ключ каждый раз как пытаемся перейти на даты которые находятся за пределами min/max ограничений.
        // Это необходимо для того чтобы screen-reader корректно озвучивал уведомление aria-live="assertive"
        // о том что нет доступных дат
        const handleKeyDown = (0, _react.useCallback)((event)=>{
            setOutOfRangeKey((previousState)=>Number(!previousState));
            onKeyDown(event);
        }, [
            onKeyDown
        ]);
        const handleTriggerEventTooltip = (structureRef, events)=>{
            if (structureRef?.current && events?.length) {
                eventTooltipTargetRef.current = structureRef.current;
                setEventNodes(events);
            } else if (eventTooltipTargetRef.current !== null) {
                eventTooltipTargetRef.current = null;
                setEventNodes([]);
            }
        };
        const tooltipContent = ()=>{
            const TooltipBodyWrapper = eventTooltipOptions?.bodyWrapper;
            if (!TooltipBodyWrapper) {
                return eventNodes;
            }
            return /*#__PURE__*/ _react.default.createElement(TooltipBodyWrapper, null, eventNodes);
        };
        (0, _react.useEffect)(()=>{
            if (prevType !== calendarState) {
                dispatch({
                    type: _types.ActionType.UPDATE_CALENDAR_STATE,
                    payload: {
                        calendarState,
                        size: _reducer.sizeMap[calendarState].single
                    }
                });
                setPrevType(calendarState);
            }
        }, [
            calendarState
        ]);
        (0, _react.useEffect)(()=>{
            if (prevType !== type) {
                dispatch({
                    type: _types.ActionType.UPDATE_CALENDAR_STATE,
                    payload: {
                        calendarState: type,
                        size: _reducer.sizeMap[type].single
                    }
                });
                setPrevType(type);
            }
        }, [
            type
        ]);
        (0, _react.useEffect)(()=>{
            if (value && prevValue && (0, _utils.isValueUpdate)(value, prevValue) || value && !prevValue) {
                dispatch({
                    type: _types.ActionType.UPDATE_DATE,
                    payload: {
                        value
                    }
                });
            }
            if (!value && !prevValue) {
                dispatch({
                    type: _types.ActionType.UPDATE_DATE,
                    payload: {
                        value: renderFrom || min || new Date()
                    }
                });
            }
            setPrevValue(value);
        }, [
            value
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, {
            ref: innerRootRef,
            className: (0, _classnames.default)(className, {
                [_Calendartokens.classes.stretched]: stretched
            }),
            "aria-label": _utils.I18N.selectDate[locale],
            eventTooltipSize: eventTooltipOptions?.size,
            ...rest
        }, isOutOfRange && /*#__PURE__*/ _react.default.createElement(_CalendarBasestyles.IsOutOfRange, {
            key: outOfRangeKey,
            "aria-atomic": "true",
            role: "alert",
            "aria-live": "assertive",
            "aria-relevant": "additions"
        }, "Далее нет доступных дат."), /*#__PURE__*/ _react.default.createElement(_ui.CalendarHeader, {
            size: rest.size,
            firstDate: date,
            startYear: startYear,
            type: calendarState,
            onPrev: handlePrev,
            onNext: handleNext,
            onUpdateCalendarState: handleUpdateCalendarState,
            locale: locale
        }), calendarState === _types.CalendarState.Days && /*#__PURE__*/ _react.default.createElement(_ui.CalendarDays, {
            value: internalValue,
            date: date,
            min: min,
            max: max,
            eventList: eventList,
            disabledList: disabledList,
            includeEdgeDates: includeEdgeDates,
            hoveredDay: hoveredItem,
            selectIndexes: selectIndexes,
            onChangeDay: handleOnChangeDay,
            onSetSelected: onSelectIndexes,
            onHoverDay: setHoveredItem,
            onTriggerEventTooltip: handleTriggerEventTooltip,
            onKeyDown: handleKeyDown,
            outerRefs: outerRefs,
            locale: locale
        }), calendarState === _types.CalendarState.Months && /*#__PURE__*/ _react.default.createElement(_ui.CalendarMonths, {
            value: internalValue,
            date: date,
            min: min,
            max: max,
            eventList: eventMonthList,
            disabledList: disabledMonthList,
            hoveredMonth: hoveredItem,
            selectIndexes: selectIndexes,
            onChangeMonth: handleOnChangeMonth,
            onSetSelected: onSelectIndexes,
            onHoverMonth: setHoveredItem,
            onTriggerEventTooltip: handleTriggerEventTooltip,
            onKeyDown: onKeyDown,
            outerRefs: outerRefs,
            locale: locale
        }), calendarState === _types.CalendarState.Quarters && /*#__PURE__*/ _react.default.createElement(_ui.CalendarQuarters, {
            value: internalValue,
            date: date,
            min: min,
            max: max,
            eventList: eventQuarterList,
            disabledList: disabledQuarterList,
            hoveredQuarter: hoveredItem,
            selectIndexes: selectIndexes,
            onChangeQuarter: handleOnChangeQuarter,
            onSetSelected: onSelectIndexes,
            onHoverQuarter: setHoveredItem,
            onTriggerEventTooltip: handleTriggerEventTooltip,
            onKeyDown: onKeyDown,
            outerRefs: outerRefs
        }), calendarState === _types.CalendarState.Years && /*#__PURE__*/ _react.default.createElement(_ui.CalendarYears, {
            value: internalValue,
            date: date,
            startYear: startYear,
            selectIndexes: selectIndexes,
            min: min,
            max: max,
            eventList: eventYearList,
            disabledList: disabledYearList,
            hoveredYear: hoveredItem,
            onChangeYear: handleOnChangeYear,
            onSetSelected: onSelectIndexes,
            onHoverYear: setHoveredItem,
            onTriggerEventTooltip: handleTriggerEventTooltip,
            onKeyDown: onKeyDown,
            outerRefs: outerRefs
        }), eventTooltipTargetRef.current && eventNodes?.length && /*#__PURE__*/ _react.default.createElement(_ui.EventTooltip, {
            opened: Boolean(eventNodes?.length),
            target: eventTooltipTargetRef,
            frame: rootRef,
            isFocusTrapped: false,
            text: tooltipContent(),
            trigger: "hover",
            ...eventTooltipOptions
        }));
    });
const calendarBaseConfig = {
    name: 'CalendarBase',
    tag: 'div',
    layout: calendarBaseRoot,
    base: _CalendarBasestyles.StyledCalendar,
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        },
        eventTooltipSize: {
            css: _base2.base
        }
    },
    defaults: {
        view: 'primary',
        size: 'm',
        eventTooltipSizeCSS: 'm'
    }
};
