"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "CalendarMonths", {
    enumerable: true,
    get: function() {
        return CalendarMonths;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _hooks = require("../../hooks");
const _Calendartokens = require("../../Calendar.tokens");
const _utils = require("../../utils");
const _DateStructureItem = require("../DateStructureItem/DateStructureItem");
const _CalendarMonthsstyles = require("./CalendarMonths.styles");
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 CalendarMonths = ({ date: currentDate, value, selectIndexes, eventList, disabledList, min, max, outerRefs, isDouble, isSecond, hoveredMonth, onChangeMonth, onHoverMonth, onSetSelected, onTriggerEventTooltip, onKeyDown, locale })=>{
    const minDate = min ? new Date(min.getFullYear(), min.getMonth(), 1) : undefined;
    const maxDate = max ? new Date(max.getFullYear(), max.getMonth() + 1, 0) : undefined;
    const [months, selected] = (0, _hooks.useMonths)({
        date: currentDate,
        value,
        eventList,
        disabledList,
        min: minDate,
        max: maxDate,
        locale
    });
    const selectedRef = (0, _react.useRef)(selected);
    const onSetSelectedRef = (0, _react.useRef)(onSetSelected);
    const noopRef = (0, _react.useRef)(null);
    const offset = isSecond ? _utils.ROW_MONTH_STEP : 0;
    const monthItemTokens = {
        [`${_Calendartokens.innerTokens.dateStructureFontFamily}`]: `var(${_Calendartokens.tokens.calendarMonthFontFamily})`,
        [`${_Calendartokens.innerTokens.dateStructureFontSize}`]: `var(${_Calendartokens.tokens.calendarMonthFontSize})`,
        [`${_Calendartokens.innerTokens.dateStructureFontWeight}`]: `var(${_Calendartokens.tokens.calendarMonthFontWeight})`,
        [`${_Calendartokens.innerTokens.dateStructureFontLineHeight}`]: `var(${_Calendartokens.tokens.calendarMonthFontLineHeight})`,
        [`${_Calendartokens.innerTokens.dateStructureFontLetterSpacing}`]: `var(${_Calendartokens.tokens.calendarMonthFontLetterSpacing})`,
        [`${_Calendartokens.innerTokens.dateStructureFontStyle}`]: `var(${_Calendartokens.tokens.calendarMonthFontStyle})`,
        [`${_Calendartokens.innerTokens.dateStructureSelectedFontWeight}`]: `var(${_Calendartokens.tokens.calendarMonthSelectedFontWeight})`,
        [`${_Calendartokens.innerTokens.dateStructureBorderRadius}`]: `var(${_Calendartokens.tokens.calendarMonthItemBorderRadius})`
    };
    const getSelectedDate = (0, _react.useCallback)((event)=>{
        const { day, monthIndex, year } = event.currentTarget.dataset;
        const selectedDate = {
            day: Number(day),
            monthIndex: Number(monthIndex),
            year: Number(year)
        };
        if (!(0, _utils.canSelectDate)(selectedDate, value, disabledList)) {
            return;
        }
        return selectedDate;
    }, [
        disabledList,
        value
    ]);
    const handleOnChangeMonth = (0, _react.useCallback)((i, j)=>(event)=>{
            /**
             * нужно вызвать stopImmediatePropagation для случаев, когда
             * обработчик события onClick навешивается снаружи.
             * Как, например, в компоненте Popup
             */ event.nativeEvent.stopImmediatePropagation();
            const selectedDate = getSelectedDate(event);
            if (!selectedDate) {
                return;
            }
            onChangeMonth(selectedDate, [
                i + offset,
                j
            ]);
            if ((0, _utils.isSelectProcess)(value)) {
                onHoverMonth?.(undefined);
            }
        }, [
        getSelectedDate,
        onChangeMonth,
        offset,
        value,
        onHoverMonth
    ]);
    const handleOnHoverMonth = (0, _react.useCallback)((event)=>{
        const selectedDate = getSelectedDate(event);
        const isSelectedDone = Array.isArray(value) && value[0] && value[1];
        if (!selectedDate || !Array.isArray(value) || isSelectedDone) {
            return;
        }
        onHoverMonth?.(selectedDate);
    }, [
        getSelectedDate,
        onHoverMonth,
        value
    ]);
    const handleMouseOutGrid = ()=>{
        onHoverMonth?.(undefined);
        onTriggerEventTooltip?.(noopRef, []);
    };
    const getRefs = (0, _react.useCallback)((element, i, j)=>{
        if (!outerRefs.current[i + offset]) {
            outerRefs.current[i + offset] = [];
        }
        outerRefs.current[i + offset][j] = element;
    }, [
        offset,
        outerRefs
    ]);
    (0, _react.useEffect)(()=>{
        if (selectedRef.current) {
            onSetSelectedRef.current?.(selectedRef.current);
        }
    }, []);
    return /*#__PURE__*/ _react.default.createElement(_CalendarMonthsstyles.StyledCalendarMonths, {
        role: "grid",
        "aria-labelledby": "id-grid-label",
        onKeyDown: onKeyDown,
        onMouseLeave: handleMouseOutGrid
    }, months.map((month, i)=>/*#__PURE__*/ _react.default.createElement(_react.Fragment, {
            key: i
        }, month.map(({ monthName, monthIndex, isSelected, isCurrent, monthFullName, date, events, isOutOfMinMaxRange, inRange, disabled, disabledArrowKey, disabledDates }, j)=>{
            return /*#__PURE__*/ _react.default.createElement(_DateStructureItem.DateStructureItem, {
                ref: (element)=>getRefs(element, i, j),
                style: monthItemTokens,
                eventList: events,
                disabled: disabled,
                day: date.day,
                year: date.year,
                monthIndex: monthIndex,
                isFocused: i + offset === selectIndexes?.[0] && j === selectIndexes?.[1] && !isOutOfMinMaxRange,
                isSelected: isSelected,
                isCurrent: isCurrent,
                isDouble: isDouble,
                isHovered: (0, _utils.isSameDay)(date, hoveredMonth),
                inRange: (0, _utils.getInRange)(value, date, hoveredMonth, inRange),
                sideInRange: (0, _utils.getSideInRange)(value, date, hoveredMonth, isSelected),
                onClick: disabled ? undefined : handleOnChangeMonth(i, j),
                onMouseOver: disabled ? undefined : handleOnHoverMonth,
                onTriggerEventTooltip: onTriggerEventTooltip,
                key: `StyledMonth-${i}-${j}`,
                role: "gridcell",
                "aria-label": monthFullName,
                disabledArrowKey: disabledArrowKey,
                disabledMonths: disabledDates,
                isDayInCurrentMonth: true
            }, monthName);
        }))));
};
