"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "CalendarQuarters", {
    enumerable: true,
    get: function() {
        return CalendarQuarters;
    }
});
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 _CalendarQuartersstyles = require("./CalendarQuarters.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 CalendarQuarters = ({ date: currentDate, value, selectIndexes, eventList, disabledList, min, max, outerRefs, isDouble, isSecond, hoveredQuarter, onChangeQuarter, onHoverQuarter, onSetSelected, onTriggerEventTooltip, onKeyDown })=>{
    const minDate = min ? new Date(min.getFullYear(), min.getMonth(), 1) : undefined;
    const maxDate = max ? new Date(max.getFullYear(), max.getMonth() + 1, 0) : undefined;
    const [quarters, selected] = (0, _hooks.useQuarters)({
        date: currentDate,
        value,
        eventList,
        disabledList,
        min: minDate,
        max: maxDate
    });
    const selectedRef = (0, _react.useRef)(selected);
    const onSetSelectedRef = (0, _react.useRef)(onSetSelected);
    const noopRef = (0, _react.useRef)(null);
    const offset = isSecond ? _utils.ROW_QUARTER_STEP : 0;
    const quarterItemTokens = {
        [`${_Calendartokens.innerTokens.dateStructureFontFamily}`]: `var(${_Calendartokens.tokens.calendarQuarterFontFamily})`,
        [`${_Calendartokens.innerTokens.dateStructureFontSize}`]: `var(${_Calendartokens.tokens.calendarQuarterFontSize})`,
        [`${_Calendartokens.innerTokens.dateStructureFontWeight}`]: `var(${_Calendartokens.tokens.calendarQuarterFontWeight})`,
        [`${_Calendartokens.innerTokens.dateStructureFontLineHeight}`]: `var(${_Calendartokens.tokens.calendarQuarterFontLineHeight})`,
        [`${_Calendartokens.innerTokens.dateStructureFontLetterSpacing}`]: `var(${_Calendartokens.tokens.calendarQuarterFontLetterSpacing})`,
        [`${_Calendartokens.innerTokens.dateStructureFontStyle}`]: `var(${_Calendartokens.tokens.calendarQuarterFontStyle})`,
        [`${_Calendartokens.innerTokens.dateStructureSelectedFontWeight}`]: `var(${_Calendartokens.tokens.calendarQuarterSelectedFontWeight})`,
        [`${_Calendartokens.innerTokens.dateStructureBorderRadius}`]: `var(${_Calendartokens.tokens.calendarQuarterItemBorderRadius})`
    };
    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 handleOnChangeQuarter = (0, _react.useCallback)((i, j, quarterName)=>(event)=>{
            /**
             * нужно вызвать stopImmediatePropagation для случаев, когда
             * обработчик события onClick навешивается снаружи.
             * Как, например, в компоненте Popup
             */ event.nativeEvent.stopImmediatePropagation();
            const selectedDate = getSelectedDate(event);
            if (!selectedDate) {
                return;
            }
            onChangeQuarter(selectedDate, [
                i + offset,
                j
            ], quarterName);
            if ((0, _utils.isSelectProcess)(value)) {
                onHoverQuarter?.(undefined);
            }
        }, [
        getSelectedDate,
        onChangeQuarter,
        offset,
        value,
        onHoverQuarter
    ]);
    const handleOnHoverQuarter = (0, _react.useCallback)((event)=>{
        const selectedDate = getSelectedDate(event);
        const isSelectedDone = Array.isArray(value) && value[0] && value[1];
        if (!selectedDate || !Array.isArray(value) || isSelectedDone) {
            return;
        }
        onHoverQuarter?.(selectedDate);
    }, [
        getSelectedDate,
        onHoverQuarter,
        value
    ]);
    const handleMouseOutGrid = ()=>{
        onHoverQuarter?.(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(_CalendarQuartersstyles.StyledCalendarQuarters, {
        role: "grid",
        "aria-labelledby": "id-grid-label",
        onKeyDown: onKeyDown,
        onMouseLeave: handleMouseOutGrid
    }, quarters.map((quarter, i)=>/*#__PURE__*/ _react.default.createElement(_react.Fragment, {
            key: i
        }, quarter.map(({ quarterName, isSelected, isCurrent, date, events, isOutOfMinMaxRange, inRange, disabled, disabledArrowKey, disabledDates }, j)=>{
            return /*#__PURE__*/ _react.default.createElement(_DateStructureItem.DateStructureItem, {
                ref: (element)=>getRefs(element, i, j),
                style: quarterItemTokens,
                eventList: events,
                disabled: disabled,
                day: date.day,
                year: date.year,
                monthIndex: date.monthIndex,
                isFocused: i + offset === selectIndexes?.[0] && j === selectIndexes?.[1] && !isOutOfMinMaxRange,
                isSelected: isSelected,
                isCurrent: isCurrent,
                isDouble: isDouble,
                isHovered: (0, _utils.isSameDay)(date, hoveredQuarter),
                inRange: (0, _utils.getInRange)(value, date, hoveredQuarter, inRange),
                sideInRange: (0, _utils.getSideInRange)(value, date, hoveredQuarter, isSelected),
                onClick: disabled ? undefined : handleOnChangeQuarter(i, j, String(quarterName)),
                onMouseOver: disabled ? undefined : handleOnHoverQuarter,
                onTriggerEventTooltip: onTriggerEventTooltip,
                key: `StyledQuarter-${i}-${j}`,
                role: "gridcell",
                "aria-label": quarterName,
                disabledArrowKey: disabledArrowKey,
                disabledMonths: disabledDates,
                isDayInCurrentMonth: true
            }, quarterName);
        }))));
};
