'use strict';

const React = require('react');
const DateLib = require('./classes/DateLib.cjs');
const createGetModifiers = require('./helpers/createGetModifiers.cjs');
const getClassNamesForModifiers = require('./helpers/getClassNamesForModifiers.cjs');
const getComponents = require('./helpers/getComponents.cjs');
const getDataAttributes = require('./helpers/getDataAttributes.cjs');
const getDefaultClassNames = require('./helpers/getDefaultClassNames.cjs');
const getFormatters = require('./helpers/getFormatters.cjs');
const getLabels = require('./helpers/getLabels.cjs');
const getMonthOptions = require('./helpers/getMonthOptions.cjs');
const getStyleForModifiers = require('./helpers/getStyleForModifiers.cjs');
const getWeekdays = require('./helpers/getWeekdays.cjs');
const getYearOptions = require('./helpers/getYearOptions.cjs');
const noonDateLib = require('./noonDateLib.cjs');
const UI = require('./UI.cjs');
const useAnimation = require('./useAnimation.cjs');
const useCalendar = require('./useCalendar.cjs');
const useDayPicker = require('./useDayPicker.cjs');
const useFocus = require('./useFocus.cjs');
const useSelection = require('./useSelection.cjs');
const convertMatchersToTimeZone = require('./utils/convertMatchersToTimeZone.cjs');
const rangeIncludesDate = require('./utils/rangeIncludesDate.cjs');
const toTimeZone = require('./utils/toTimeZone.cjs');
const typeguards = require('./utils/typeguards.cjs');
const enUS = require('./locale/en-US.cjs');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }

const React__default = /*#__PURE__*/_interopDefaultCompat(React);

/**
 * Renders the DayPicker calendar component.
 *
 * @param initialProps - The props for the DayPicker component.
 * @returns The rendered DayPicker component.
 * @group DayPicker
 * @see https://daypicker.dev
 */
function DayPicker(initialProps) {
    let props = initialProps;
    const timeZone = props.timeZone;
    if (timeZone) {
        props = {
            ...initialProps,
            timeZone,
        };
        if (props.today) {
            props.today = toTimeZone.toTimeZone(props.today, timeZone);
        }
        if (props.month) {
            props.month = toTimeZone.toTimeZone(props.month, timeZone);
        }
        if (props.defaultMonth) {
            props.defaultMonth = toTimeZone.toTimeZone(props.defaultMonth, timeZone);
        }
        if (props.startMonth) {
            props.startMonth = toTimeZone.toTimeZone(props.startMonth, timeZone);
        }
        if (props.endMonth) {
            props.endMonth = toTimeZone.toTimeZone(props.endMonth, timeZone);
        }
        if (props.mode === "single" && props.selected) {
            props.selected = toTimeZone.toTimeZone(props.selected, timeZone);
        }
        else if (props.mode === "multiple" && props.selected) {
            props.selected = props.selected?.map((date) => toTimeZone.toTimeZone(date, timeZone));
        }
        else if (props.mode === "range" && props.selected) {
            props.selected = {
                from: props.selected.from
                    ? toTimeZone.toTimeZone(props.selected.from, timeZone)
                    : props.selected.from,
                to: props.selected.to
                    ? toTimeZone.toTimeZone(props.selected.to, timeZone)
                    : props.selected.to,
            };
        }
        if (props.disabled !== undefined) {
            props.disabled = convertMatchersToTimeZone.convertMatchersToTimeZone(props.disabled, timeZone);
        }
        if (props.hidden !== undefined) {
            props.hidden = convertMatchersToTimeZone.convertMatchersToTimeZone(props.hidden, timeZone);
        }
        if (props.modifiers) {
            const nextModifiers = {};
            Object.keys(props.modifiers).forEach((key) => {
                nextModifiers[key] = convertMatchersToTimeZone.convertMatchersToTimeZone(props.modifiers?.[key], timeZone);
            });
            props.modifiers = nextModifiers;
        }
    }
    const { components, formatters, labels, dateLib, locale, classNames } = React.useMemo(() => {
        const locale = { ...enUS.enUS, ...props.locale };
        const weekStartsOn = props.broadcastCalendar ? 1 : props.weekStartsOn;
        const noonOverrides = props.noonSafe && props.timeZone
            ? noonDateLib.createNoonOverrides(props.timeZone, {
                weekStartsOn,
                locale,
            })
            : undefined;
        const overrides = props.dateLib && noonOverrides
            ? { ...noonOverrides, ...props.dateLib }
            : (props.dateLib ?? noonOverrides);
        const dateLib = new DateLib.DateLib({
            locale,
            weekStartsOn,
            firstWeekContainsDate: props.firstWeekContainsDate,
            useAdditionalWeekYearTokens: props.useAdditionalWeekYearTokens,
            useAdditionalDayOfYearTokens: props.useAdditionalDayOfYearTokens,
            timeZone: props.timeZone,
            numerals: props.numerals,
        }, overrides);
        return {
            dateLib,
            components: getComponents.getComponents(props.components),
            formatters: getFormatters.getFormatters(props.formatters),
            labels: getLabels.getLabels(props.labels, dateLib.options),
            locale,
            classNames: { ...getDefaultClassNames.getDefaultClassNames(), ...props.classNames },
        };
    }, [
        props.locale,
        props.broadcastCalendar,
        props.weekStartsOn,
        props.firstWeekContainsDate,
        props.useAdditionalWeekYearTokens,
        props.useAdditionalDayOfYearTokens,
        props.timeZone,
        props.numerals,
        props.dateLib,
        props.noonSafe,
        props.components,
        props.formatters,
        props.labels,
        props.classNames,
    ]);
    if (!props.today) {
        props = { ...props, today: dateLib.today() };
    }
    const { captionLayout, mode, navLayout, numberOfMonths = 1, onDayBlur, onDayClick, onDayFocus, onDayKeyDown, onDayMouseEnter, onDayMouseLeave, onNextClick, onPrevClick, showWeekNumber, styles, } = props;
    const { formatCaption, formatDay, formatMonthDropdown, formatWeekNumber, formatWeekNumberHeader, formatWeekdayName, formatYearDropdown, } = formatters;
    const calendar = useCalendar.useCalendar(props, dateLib);
    const { days, months, navStart, navEnd, previousMonth, nextMonth, goToMonth, } = calendar;
    const getModifiers = createGetModifiers.createGetModifiers(days, props, navStart, navEnd, dateLib);
    const { isSelected, select, selected: selectedValue, } = useSelection.useSelection(props, dateLib) ?? {};
    const { blur, focused, isFocusTarget, moveFocus, setFocused } = useFocus.useFocus(props, calendar, getModifiers, isSelected ?? (() => false), dateLib);
    const { labelDayButton, labelGridcell, labelGrid, labelMonthDropdown, labelNav, labelPrevious, labelNext, labelWeekday, labelWeekNumber, labelWeekNumberHeader, labelYearDropdown, } = labels;
    const weekdays = React.useMemo(() => getWeekdays.getWeekdays(dateLib, props.ISOWeek, props.broadcastCalendar, props.today), [dateLib, props.ISOWeek, props.broadcastCalendar, props.today]);
    const isInteractive = mode !== undefined || onDayClick !== undefined;
    const handlePreviousClick = React.useCallback(() => {
        if (!previousMonth)
            return;
        goToMonth(previousMonth);
        onPrevClick?.(previousMonth);
    }, [previousMonth, goToMonth, onPrevClick]);
    const handleNextClick = React.useCallback(() => {
        if (!nextMonth)
            return;
        goToMonth(nextMonth);
        onNextClick?.(nextMonth);
    }, [goToMonth, nextMonth, onNextClick]);
    const handleDayClick = React.useCallback((day, m) => (e) => {
        e.preventDefault();
        e.stopPropagation();
        setFocused(day);
        if (m.disabled) {
            return;
        }
        select?.(day.date, m, e);
        onDayClick?.(day.date, m, e);
    }, [select, onDayClick, setFocused]);
    const handleDayFocus = React.useCallback((day, m) => (e) => {
        setFocused(day);
        onDayFocus?.(day.date, m, e);
    }, [onDayFocus, setFocused]);
    const handleDayBlur = React.useCallback((day, m) => (e) => {
        blur();
        onDayBlur?.(day.date, m, e);
    }, [blur, onDayBlur]);
    const handleDayKeyDown = React.useCallback((day, modifiers) => (e) => {
        const keyMap = {
            ArrowLeft: [
                e.shiftKey ? "month" : "day",
                props.dir === "rtl" ? "after" : "before",
            ],
            ArrowRight: [
                e.shiftKey ? "month" : "day",
                props.dir === "rtl" ? "before" : "after",
            ],
            ArrowDown: [e.shiftKey ? "year" : "week", "after"],
            ArrowUp: [e.shiftKey ? "year" : "week", "before"],
            PageUp: [e.shiftKey ? "year" : "month", "before"],
            PageDown: [e.shiftKey ? "year" : "month", "after"],
            Home: ["startOfWeek", "before"],
            End: ["endOfWeek", "after"],
        };
        if (keyMap[e.key]) {
            e.preventDefault();
            e.stopPropagation();
            const [moveBy, moveDir] = keyMap[e.key];
            moveFocus(moveBy, moveDir);
        }
        onDayKeyDown?.(day.date, modifiers, e);
    }, [moveFocus, onDayKeyDown, props.dir]);
    const handleDayMouseEnter = React.useCallback((day, modifiers) => (e) => {
        onDayMouseEnter?.(day.date, modifiers, e);
    }, [onDayMouseEnter]);
    const handleDayMouseLeave = React.useCallback((day, modifiers) => (e) => {
        onDayMouseLeave?.(day.date, modifiers, e);
    }, [onDayMouseLeave]);
    const handleMonthChange = React.useCallback((date) => (e) => {
        const selectedMonth = Number(e.target.value);
        const month = dateLib.setMonth(dateLib.startOfMonth(date), selectedMonth);
        goToMonth(month);
    }, [dateLib, goToMonth]);
    const handleYearChange = React.useCallback((date) => (e) => {
        const selectedYear = Number(e.target.value);
        const month = dateLib.setYear(dateLib.startOfMonth(date), selectedYear);
        goToMonth(month);
    }, [dateLib, goToMonth]);
    const { className, style } = React.useMemo(() => ({
        className: [classNames[UI.UI.Root], props.className]
            .filter(Boolean)
            .join(" "),
        style: { ...styles?.[UI.UI.Root], ...props.style },
    }), [classNames, props.className, props.style, styles]);
    const dataAttributes = getDataAttributes.getDataAttributes(props);
    const rootElRef = React.useRef(null);
    useAnimation.useAnimation(rootElRef, Boolean(props.animate), {
        classNames,
        months,
        focused,
        dateLib,
    });
    const contextValue = {
        dayPickerProps: props,
        selected: selectedValue,
        select: select,
        isSelected,
        months,
        nextMonth,
        previousMonth,
        goToMonth,
        getModifiers,
        components,
        classNames,
        styles,
        labels,
        formatters,
    };
    return (React__default.createElement(useDayPicker.dayPickerContext.Provider, { value: contextValue },
        React__default.createElement(components.Root, { rootRef: props.animate ? rootElRef : undefined, className: className, style: style, dir: props.dir, id: props.id, lang: props.lang, nonce: props.nonce, title: props.title, role: props.role, "aria-label": props["aria-label"], "aria-labelledby": props["aria-labelledby"], ...dataAttributes },
            React__default.createElement(components.Months, { className: classNames[UI.UI.Months], style: styles?.[UI.UI.Months] },
                !props.hideNavigation && !navLayout && (React__default.createElement(components.Nav, { "data-animated-nav": props.animate ? "true" : undefined, className: classNames[UI.UI.Nav], style: styles?.[UI.UI.Nav], "aria-label": labelNav(), onPreviousClick: handlePreviousClick, onNextClick: handleNextClick, previousMonth: previousMonth, nextMonth: nextMonth })),
                months.map((calendarMonth, displayIndex) => {
                    return (React__default.createElement(components.Month, { "data-animated-month": props.animate ? "true" : undefined, className: classNames[UI.UI.Month], style: styles?.[UI.UI.Month], 
                        // biome-ignore lint/suspicious/noArrayIndexKey: breaks animation
                        key: displayIndex, displayIndex: displayIndex, calendarMonth: calendarMonth },
                        navLayout === "around" &&
                            !props.hideNavigation &&
                            displayIndex === 0 && (React__default.createElement(components.PreviousMonthButton, { type: "button", className: classNames[UI.UI.PreviousMonthButton], tabIndex: previousMonth ? undefined : -1, "aria-disabled": previousMonth ? undefined : true, "aria-label": labelPrevious(previousMonth), onClick: handlePreviousClick, "data-animated-button": props.animate ? "true" : undefined },
                            React__default.createElement(components.Chevron, { disabled: previousMonth ? undefined : true, className: classNames[UI.UI.Chevron], orientation: props.dir === "rtl" ? "right" : "left" }))),
                        React__default.createElement(components.MonthCaption, { "data-animated-caption": props.animate ? "true" : undefined, className: classNames[UI.UI.MonthCaption], style: styles?.[UI.UI.MonthCaption], calendarMonth: calendarMonth, displayIndex: displayIndex }, captionLayout?.startsWith("dropdown") ? (React__default.createElement(components.DropdownNav, { className: classNames[UI.UI.Dropdowns], style: styles?.[UI.UI.Dropdowns] },
                            (() => {
                                const monthControl = captionLayout === "dropdown" ||
                                    captionLayout === "dropdown-months" ? (React__default.createElement(components.MonthsDropdown, { key: "month", className: classNames[UI.UI.MonthsDropdown], "aria-label": labelMonthDropdown(), classNames: classNames, components: components, disabled: Boolean(props.disableNavigation), onChange: handleMonthChange(calendarMonth.date), options: getMonthOptions.getMonthOptions(calendarMonth.date, navStart, navEnd, formatters, dateLib), style: styles?.[UI.UI.Dropdown], value: dateLib.getMonth(calendarMonth.date) })) : (React__default.createElement("span", { key: "month" }, formatMonthDropdown(calendarMonth.date, dateLib)));
                                const yearControl = captionLayout === "dropdown" ||
                                    captionLayout === "dropdown-years" ? (React__default.createElement(components.YearsDropdown, { key: "year", className: classNames[UI.UI.YearsDropdown], "aria-label": labelYearDropdown(dateLib.options), classNames: classNames, components: components, disabled: Boolean(props.disableNavigation), onChange: handleYearChange(calendarMonth.date), options: getYearOptions.getYearOptions(navStart, navEnd, formatters, dateLib, Boolean(props.reverseYears)), style: styles?.[UI.UI.Dropdown], value: dateLib.getYear(calendarMonth.date) })) : (React__default.createElement("span", { key: "year" }, formatYearDropdown(calendarMonth.date, dateLib)));
                                const controls = dateLib.getMonthYearOrder() === "year-first"
                                    ? [yearControl, monthControl]
                                    : [monthControl, yearControl];
                                return controls;
                            })(),
                            React__default.createElement("span", { role: "status", "aria-live": "polite", style: {
                                    border: 0,
                                    clip: "rect(0 0 0 0)",
                                    height: "1px",
                                    margin: "-1px",
                                    overflow: "hidden",
                                    padding: 0,
                                    position: "absolute",
                                    width: "1px",
                                    whiteSpace: "nowrap",
                                    wordWrap: "normal",
                                } }, formatCaption(calendarMonth.date, dateLib.options, dateLib)))) : (React__default.createElement(components.CaptionLabel, { className: classNames[UI.UI.CaptionLabel], role: "status", "aria-live": "polite" }, formatCaption(calendarMonth.date, dateLib.options, dateLib)))),
                        navLayout === "around" &&
                            !props.hideNavigation &&
                            displayIndex === numberOfMonths - 1 && (React__default.createElement(components.NextMonthButton, { type: "button", className: classNames[UI.UI.NextMonthButton], tabIndex: nextMonth ? undefined : -1, "aria-disabled": nextMonth ? undefined : true, "aria-label": labelNext(nextMonth), onClick: handleNextClick, "data-animated-button": props.animate ? "true" : undefined },
                            React__default.createElement(components.Chevron, { disabled: nextMonth ? undefined : true, className: classNames[UI.UI.Chevron], orientation: props.dir === "rtl" ? "left" : "right" }))),
                        displayIndex === numberOfMonths - 1 &&
                            navLayout === "after" &&
                            !props.hideNavigation && (React__default.createElement(components.Nav, { "data-animated-nav": props.animate ? "true" : undefined, className: classNames[UI.UI.Nav], style: styles?.[UI.UI.Nav], "aria-label": labelNav(), onPreviousClick: handlePreviousClick, onNextClick: handleNextClick, previousMonth: previousMonth, nextMonth: nextMonth })),
                        React__default.createElement(components.MonthGrid, { role: "grid", "aria-multiselectable": mode === "multiple" || mode === "range", "aria-label": labelGrid(calendarMonth.date, dateLib.options, dateLib) ||
                                undefined, className: classNames[UI.UI.MonthGrid], style: styles?.[UI.UI.MonthGrid] },
                            !props.hideWeekdays && (React__default.createElement(components.Weekdays, { "data-animated-weekdays": props.animate ? "true" : undefined, className: classNames[UI.UI.Weekdays], style: styles?.[UI.UI.Weekdays] },
                                showWeekNumber && (React__default.createElement(components.WeekNumberHeader, { "aria-label": labelWeekNumberHeader(dateLib.options), className: classNames[UI.UI.WeekNumberHeader], style: styles?.[UI.UI.WeekNumberHeader], scope: "col" }, formatWeekNumberHeader())),
                                weekdays.map((weekday) => (React__default.createElement(components.Weekday, { "aria-label": labelWeekday(weekday, dateLib.options, dateLib), className: classNames[UI.UI.Weekday], key: String(weekday), style: styles?.[UI.UI.Weekday], scope: "col" }, formatWeekdayName(weekday, dateLib.options, dateLib)))))),
                            React__default.createElement(components.Weeks, { "data-animated-weeks": props.animate ? "true" : undefined, className: classNames[UI.UI.Weeks], style: styles?.[UI.UI.Weeks] }, calendarMonth.weeks.map((week) => {
                                return (React__default.createElement(components.Week, { className: classNames[UI.UI.Week], key: week.weekNumber, style: styles?.[UI.UI.Week], week: week },
                                    showWeekNumber && (React__default.createElement(components.WeekNumber, { week: week, style: styles?.[UI.UI.WeekNumber], "aria-label": labelWeekNumber(week.weekNumber, {
                                            locale,
                                        }), className: classNames[UI.UI.WeekNumber], scope: "row", role: "rowheader" }, formatWeekNumber(week.weekNumber, dateLib))),
                                    week.days.map((day) => {
                                        const { date } = day;
                                        const modifiers = getModifiers(day);
                                        modifiers[UI.DayFlag.focused] =
                                            !modifiers.hidden &&
                                                Boolean(focused?.isEqualTo(day));
                                        modifiers[UI.SelectionState.selected] =
                                            isSelected?.(date) || modifiers.selected;
                                        if (typeguards.isDateRange(selectedValue)) {
                                            // add range modifiers
                                            const { from, to } = selectedValue;
                                            modifiers[UI.SelectionState.range_start] = Boolean(from && to && dateLib.isSameDay(date, from));
                                            modifiers[UI.SelectionState.range_end] = Boolean(from && to && dateLib.isSameDay(date, to));
                                            modifiers[UI.SelectionState.range_middle] =
                                                rangeIncludesDate.rangeIncludesDate(selectedValue, date, true, dateLib);
                                        }
                                        const style = getStyleForModifiers.getStyleForModifiers(modifiers, styles, props.modifiersStyles);
                                        const className = getClassNamesForModifiers.getClassNamesForModifiers(modifiers, classNames, props.modifiersClassNames);
                                        const ariaLabel = !isInteractive && !modifiers.hidden
                                            ? labelGridcell(date, modifiers, dateLib.options, dateLib)
                                            : undefined;
                                        return (React__default.createElement(components.Day, { key: `${day.isoDate}_${day.displayMonthId}`, day: day, modifiers: modifiers, className: className.join(" "), style: style, role: "gridcell", "aria-selected": modifiers.selected || undefined, "aria-label": ariaLabel, "data-day": day.isoDate, "data-month": day.outside ? day.dateMonthId : undefined, "data-selected": modifiers.selected || undefined, "data-disabled": modifiers.disabled || undefined, "data-hidden": modifiers.hidden || undefined, "data-outside": day.outside || undefined, "data-focused": modifiers.focused || undefined, "data-today": modifiers.today || undefined }, !modifiers.hidden && isInteractive ? (React__default.createElement(components.DayButton, { className: classNames[UI.UI.DayButton], style: styles?.[UI.UI.DayButton], type: "button", day: day, modifiers: modifiers, disabled: (!modifiers.focused &&
                                                modifiers.disabled) ||
                                                undefined, "aria-disabled": (modifiers.focused &&
                                                modifiers.disabled) ||
                                                undefined, tabIndex: isFocusTarget(day) ? 0 : -1, "aria-label": labelDayButton(date, modifiers, dateLib.options, dateLib), onClick: handleDayClick(day, modifiers), onBlur: handleDayBlur(day, modifiers), onFocus: handleDayFocus(day, modifiers), onKeyDown: handleDayKeyDown(day, modifiers), onMouseEnter: handleDayMouseEnter(day, modifiers), onMouseLeave: handleDayMouseLeave(day, modifiers) }, formatDay(date, dateLib.options, dateLib))) : (!modifiers.hidden &&
                                            formatDay(day.date, dateLib.options, dateLib))));
                                    })));
                            })))));
                })),
            props.footer && (React__default.createElement(components.Footer, { className: classNames[UI.UI.Footer], style: styles?.[UI.UI.Footer], role: "status", "aria-live": "polite" }, props.footer)))));
}

exports.DayPicker = DayPicker;
