"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "CalendarYears", {
    enumerable: true,
    get: function() {
        return CalendarYears;
    }
});
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 _CalendarYearsstyles = require("./CalendarYears.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 CalendarYears = ({ date: currentDate, value, startYear, selectIndexes, eventList, disabledList, min, max, outerRefs, isDouble, isSecond, hoveredYear, onChangeYear, onHoverYear, onSetSelected, onTriggerEventTooltip, onKeyDown })=>{
    const minDate = min ? new Date(min.getFullYear(), 0, 1) : undefined;
    const maxDate = max ? new Date(max.getFullYear(), 11, 31) : undefined;
    const [years, selected] = (0, _hooks.useYears)({
        date: currentDate,
        value,
        startYear,
        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_YEAR_STEP : 0;
    const yearItemTokens = {
        [`${_Calendartokens.innerTokens.dateStructureFontFamily}`]: `var(${_Calendartokens.tokens.calendarYearFontFamily})`,
        [`${_Calendartokens.innerTokens.dateStructureFontSize}`]: `var(${_Calendartokens.tokens.calendarYearFontSize})`,
        [`${_Calendartokens.innerTokens.dateStructureFontWeight}`]: `var(${_Calendartokens.tokens.calendarYearFontWeight})`,
        [`${_Calendartokens.innerTokens.dateStructureFontLineHeight}`]: `var(${_Calendartokens.tokens.calendarYearFontLineHeight})`,
        [`${_Calendartokens.innerTokens.dateStructureFontLetterSpacing}`]: `var(${_Calendartokens.tokens.calendarYearFontLetterSpacing})`,
        [`${_Calendartokens.innerTokens.dateStructureFontStyle}`]: `var(${_Calendartokens.tokens.calendarYearFontStyle})`,
        [`${_Calendartokens.innerTokens.dateStructureSelectedFontWeight}`]: `var(${_Calendartokens.tokens.calendarYearSelectedFontWeight})`,
        [`${_Calendartokens.innerTokens.dateStructureBorderRadius}`]: `var(${_Calendartokens.tokens.calendarYearItemBorderRadius})`
    };
    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 handleOnChangeYear = (0, _react.useCallback)((i, j)=>(event)=>{
            /**
             * нужно вызвать stopImmediatePropagation для случаев, когда
             * обработчик события onClick навешивается снаружи.
             * Как, например, в компоненте Popup
             */ event.nativeEvent.stopImmediatePropagation();
            const selectedDate = getSelectedDate(event);
            if (!selectedDate) {
                return;
            }
            onChangeYear(selectedDate, [
                i + offset,
                j
            ]);
            if ((0, _utils.isSelectProcess)(value)) {
                onHoverYear?.(undefined);
            }
        }, [
        getSelectedDate,
        onChangeYear,
        offset,
        value,
        onHoverYear
    ]);
    const handleOnHoverYear = (0, _react.useCallback)((event)=>{
        const selectedDate = getSelectedDate(event);
        const isSelectedDone = Array.isArray(value) && value[0] && value[1];
        if (!selectedDate || !Array.isArray(value) || isSelectedDone) {
            return;
        }
        onHoverYear?.(selectedDate);
    }, [
        getSelectedDate,
        onHoverYear,
        value
    ]);
    const handleMouseOutGrid = ()=>{
        onHoverYear?.(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;
    }, [
        outerRefs
    ]);
    (0, _react.useEffect)(()=>{
        if (selectedRef.current) {
            onSetSelectedRef.current?.(selectedRef.current);
        }
    }, []);
    return /*#__PURE__*/ _react.default.createElement(_CalendarYearsstyles.StyledCalendarYears, {
        role: "grid",
        "aria-labelledby": "id-grid-label",
        onKeyDown: onKeyDown,
        onMouseLeave: handleMouseOutGrid
    }, years.map((year, i)=>/*#__PURE__*/ _react.default.createElement(_react.Fragment, {
            key: i
        }, year.map(({ yearValue, isSelected, isCurrent, date, events, isOutOfMinMaxRange, inRange, disabled, disabledArrowKey, disabledDates }, j)=>{
            return /*#__PURE__*/ _react.default.createElement(_DateStructureItem.DateStructureItem, {
                ref: (element)=>getRefs(element, i, j),
                style: yearItemTokens,
                eventList: events,
                disabled: disabled,
                day: date.day,
                year: yearValue,
                monthIndex: date.monthIndex,
                isFocused: i + offset === selectIndexes?.[0] && j === selectIndexes?.[1] && !isOutOfMinMaxRange,
                isSelected: isSelected,
                isCurrent: isCurrent,
                isDouble: isDouble,
                isHovered: (0, _utils.isSameDay)(date, hoveredYear),
                inRange: (0, _utils.getInRange)(value, date, hoveredYear, inRange),
                sideInRange: (0, _utils.getSideInRange)(value, date, hoveredYear, isSelected),
                onClick: disabled ? undefined : handleOnChangeYear(i, j),
                onMouseOver: disabled ? undefined : handleOnHoverYear,
                onTriggerEventTooltip: onTriggerEventTooltip,
                key: `StyledYear-${i}-${j}`,
                role: "gridcell",
                "data-year": yearValue,
                "data-month-index": date.monthIndex,
                "data-day": date.day,
                "aria-label": String(yearValue),
                disabledArrowKey: disabledArrowKey,
                disabledMonths: disabledDates,
                isDayInCurrentMonth: true
            }, yearValue);
        }))));
};
