import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { D as DateTime, I as Info } from './luxon-wpz4A-OQ.js';
import { createContext, useContext, forwardRef, useState, useEffect, useRef, useCallback, useMemo, useId } from 'react';
import { B as Button } from './Button-BNzCI47m.js';
import { S as SvgKeyboardArrowDown } from './keyboard_arrow_down-C8WQ38p1.js';
import { S as SvgKeyboardArrowUp } from './keyboard_arrow_up-CxzK6LAl.js';
import { S as SvgKeyboardArrowLeft } from './keyboard_arrow_left-CiE1n99w.js';
import { c as cx } from './index-De1g9FRV.js';
import { S as SvgKeyboardArrowRight } from './keyboard_arrow_right-DMloHg_F.js';
import { S as SrOnly } from './SrOnly-pnf8ajnh.js';
import { u as useSwipe } from './useSwipe-Cp-CJxLU.js';
import { G as Grid } from './Grid-ho1pGJ5L.js';
import { S as SelectCard } from './SelectCard-CMSG_ba1.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { u as useVirtualizer } from './index-DXeGMe23.js';
import { u as useOptionallyControlledState } from './useOptionallyControlledState-DbDuos5L.js';
import { u as usePrevious } from './usePrevious-Bvq-5auG.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-DjqeAJZ9.js';

import './Calendar.css';const CalendarContext = createContext(null);
function useCalendar() {
  const context = useContext(CalendarContext);
  if (!context) {
    throw new Error("useCalendar must be used within a <Calendar>");
  }
  return context;
}

const isSameDay = (d1, d2) => {
  if (!d1 || !d2) return void 0;
  try {
    if (d1.hasSame(d2, "month") && d1.hasSame(d2, "year") && d1.hasSame(d2, "day")) {
      return true;
    }
    return false;
  } catch {
    return false;
  }
};
const isSameMonth = (d1, d2) => {
  if (!d1 || !d2) return void 0;
  if (d1.hasSame(d2, "month") && d1.hasSame(d2, "year")) return true;
  return false;
};
const isUnavailableDate = (n, unavailable, timeZone) => {
  const tmpSet = /* @__PURE__ */ new Set();
  unavailable.dates?.forEach((date) => {
    tmpSet.add(toDateString(DateTime.fromISO(date, { zone: timeZone })));
  });
  if (unavailable.daysOfWeek?.has(n.weekday)) {
    return true;
  }
  const dateISO = n.toISO();
  if (!dateISO) return;
  return tmpSet.has(
    toDateString(DateTime.fromISO(dateISO, { zone: timeZone }))
  );
};
const isBeyondMinDate = (n, minDate) => minDate && minDate.toMillis() > n.toMillis();
const isBeyondMaxDate = (n, maxDate) => maxDate && maxDate.toMillis() < n.toMillis();
const normalizeDate = (date, defaultTimeZone) => {
  return DateTime.fromISO(date, { zone: defaultTimeZone }).startOf("day");
};
const toDateString = (date) => date.startOf("day").toISO();
function rangeUpdater(value, newDate, setValue, onSelection) {
  if (value.start && isSameDay(value.start, newDate) && !value.end) {
    setValue((prev) => {
      return { ...prev, end: newDate };
    });
    onSelection?.({
      value: {
        start: toDateString(value.start) ?? void 0,
        end: toDateString(newDate) ?? void 0
      }
    });
    return;
  }
  if (!value.start && !value.end || value.start && value.end || value.start && !value.end && value.start.startOf("day").toMillis() > newDate.startOf("day").toMillis()) {
    setValue({ start: newDate, end: null });
    onSelection?.({
      value: {
        start: toDateString(newDate) ?? void 0,
        end: void 0
      }
    });
    return;
  }
  if (value.start && !value.end && value.start.startOf("day").toMillis() < newDate.startOf("day").toMillis()) {
    setValue((prev) => {
      return { ...prev, end: newDate };
    });
    onSelection?.({
      value: {
        start: toDateString(value.start) ?? void 0,
        end: toDateString(newDate) ?? void 0
      }
    });
    return;
  }
  if (!value.start && value.end) {
    setValue((prev) => {
      return { ...prev, start: newDate };
    });
    onSelection?.({
      value: {
        start: toDateString(newDate) ?? void 0,
        end: toDateString(value.end) ?? void 0
      }
    });
    return;
  }
}
const getDateMetadata = (date, dateMetadata) => {
  if (!dateMetadata) return void 0;
  const dateString = date.toISODate();
  return dateString ? dateMetadata.get(dateString) : void 0;
};

const CalendarNow = forwardRef(
  (props, ref) => {
    const { onClick, onClickFixed, ...rest } = props;
    const {
      setFocusedDate,
      setSelectedMonth,
      setSelectedYear,
      value,
      setValue,
      defaultTimeZone,
      unavailable,
      onSelection,
      minDate,
      maxDate,
      controlled,
      range
    } = useCalendar();
    const nToday = DateTime.fromISO(DateTime.now().toISO(), {
      zone: defaultTimeZone
    }).startOf("day");
    const onClickHandler = (e) => {
      onClickFixed?.(e);
      setFocusedDate(nToday);
      setSelectedMonth(nToday.month);
      setSelectedYear(nToday.year);
      if (!range) {
        onSelection?.({
          value: toDateString(nToday) ?? void 0
        });
        if (!controlled) {
          setValue(nToday);
        }
        return;
      }
      rangeUpdater(value, nToday, setValue, onSelection);
    };
    const isDisabled = isBeyondMaxDate(nToday, maxDate) || isBeyondMinDate(nToday, minDate) || isUnavailableDate(nToday, unavailable, defaultTimeZone);
    return /* @__PURE__ */ jsx(
      Button,
      {
        ref,
        onClick: onClickHandler,
        appearance: "ghost",
        disabled: isDisabled,
        "data-anv": "calendar-now",
        size: "small",
        ...rest,
        children: "Today"
      }
    );
  }
);
CalendarNow.displayName = "CalendarNowButton";

const CalendarYearButton = forwardRef((props, ref) => {
  const { calendarSelectionState, ...rest } = props;
  const { selectedYear, locale } = useCalendar();
  const currentYear = DateTime.fromObject({ year: selectedYear }).setLocale(locale).toLocaleString({ year: "numeric" });
  return /* @__PURE__ */ jsx(
    Button,
    {
      ref,
      appearance: "ghost",
      size: "small",
      icon: {
        after: calendarSelectionState === "year" ? SvgKeyboardArrowUp : SvgKeyboardArrowDown
      },
      ...rest,
      children: currentYear
    }
  );
});
CalendarYearButton.displayName = "CalendarYearButton";

const calendar = "_calendar_vutdc_1";
const grid = "_grid_vutdc_18";
const header = "_header_vutdc_23";
const controller = "_controller_vutdc_46";
const spacer = "_spacer_vutdc_59";
const cell = "_cell_vutdc_74";
const weekday = "_weekday_vutdc_119";
const range = "_range_vutdc_162";
const overflow = "_overflow_vutdc_168";
const selected = "_selected_vutdc_172";
const pip = "_pip_vutdc_254";
const styles$1 = {
	calendar: calendar,
	grid: grid,
	header: header,
	controller: controller,
	"controller-button": "_controller-button_vutdc_55",
	spacer: spacer,
	"day-grid": "_day-grid_vutdc_63",
	cell: cell,
	weekday: weekday,
	"month-selection": "_month-selection_vutdc_133",
	"selection-checkbox": "_selection-checkbox_vutdc_133",
	"selection-card": "_selection-card_vutdc_143",
	"year-selector": "_year-selector_vutdc_155",
	"range-first": "_range-first_vutdc_162",
	"range-last": "_range-last_vutdc_162",
	range: range,
	overflow: overflow,
	selected: selected,
	"is-unavailable": "_is-unavailable_vutdc_181",
	"hover-last": "_hover-last_vutdc_206",
	"has-metadata": "_has-metadata_vutdc_249",
	pip: pip,
	"range-fill": "_range-fill_vutdc_267",
	"range-disabled": "_range-disabled_vutdc_278"
};

const CalendarPrev = forwardRef(
  (props, ref) => {
    const { onClick, className, ...rest } = props;
    const {
      focusedDate,
      setFocusedDate,
      minDate,
      setSelectedMonth,
      setSelectedYear
    } = useCalendar();
    const [disabled, setDisabled] = useState(false);
    useEffect(() => {
      setDisabled(
        minDate != null && focusedDate.minus({ month: 1 }).endOf("month") < minDate
      );
    }, [minDate, focusedDate]);
    const onClickHandler = (e) => {
      onClick?.(e);
      const targetMonth = focusedDate.minus({ month: 1 }).endOf("month");
      const targetDate = focusedDate.minus({ month: 1 });
      const isCrossingYearBoundary = focusedDate.month === 1 && targetDate.month === 12;
      if (minDate !== null) {
        if (targetDate.toMillis() >= minDate?.toMillis()) {
          setFocusedDate(targetDate);
          setSelectedMonth(targetDate.month);
          if (isCrossingYearBoundary) {
            setSelectedYear(targetDate.year);
          }
          return;
        }
        if (!isSameMonth(targetMonth, focusedDate)) {
          setFocusedDate(minDate);
          setSelectedMonth(minDate.month);
          if (isCrossingYearBoundary) {
            setSelectedYear(minDate.year);
          }
        }
        return;
      }
      setFocusedDate(targetDate);
      setSelectedMonth(targetDate.month);
      if (isCrossingYearBoundary) {
        setSelectedYear(targetDate.year);
      }
    };
    return /* @__PURE__ */ jsx(
      Button,
      {
        ref,
        onClick: onClickHandler,
        className: cx(styles$1["controller-button"], className),
        appearance: "ghost",
        size: "small",
        icon: SvgKeyboardArrowLeft,
        "data-anv": "calendar-prev",
        "aria-label": "Previous Month",
        ...rest,
        disabled
      }
    );
  }
);
CalendarPrev.displayName = "CalendarPrevButton";

const CalendarNext = forwardRef(
  (props, ref) => {
    const { onClick, className, ...rest } = props;
    const {
      focusedDate,
      setFocusedDate,
      maxDate,
      setSelectedMonth,
      setSelectedYear
    } = useCalendar();
    const [disabled, setDisabled] = useState(false);
    useEffect(() => {
      setDisabled(
        maxDate != null && focusedDate.plus({ month: 1 }).startOf("month") > maxDate
      );
    }, [maxDate, focusedDate]);
    const onClickHandler = (e) => {
      onClick?.(e);
      const targetMonth = focusedDate.plus({ month: 1 }).startOf("month");
      const targetDate = focusedDate.plus({ month: 1 });
      const isCrossingYearBoundary = focusedDate.month === 12 && targetDate.month === 1;
      if (maxDate !== null) {
        if (targetDate.toMillis() <= maxDate?.toMillis()) {
          setFocusedDate(targetDate);
          setSelectedMonth(targetDate.month);
          if (isCrossingYearBoundary) {
            setSelectedYear(targetDate.year);
          }
          return;
        }
        if (!isSameMonth(targetMonth, focusedDate)) {
          setFocusedDate(maxDate);
          setSelectedMonth(maxDate.month);
          if (isCrossingYearBoundary) {
            setSelectedYear(maxDate.year);
          }
        }
        return;
      }
      setFocusedDate(targetDate);
      setSelectedMonth(targetDate.month);
      if (isCrossingYearBoundary) {
        setSelectedYear(targetDate.year);
      }
    };
    return /* @__PURE__ */ jsx(
      Button,
      {
        onClick: onClickHandler,
        appearance: "ghost",
        size: "small",
        className: cx(styles$1["controller-button"], className),
        icon: SvgKeyboardArrowRight,
        "aria-label": "Next Month",
        "data-anv": "calendar-next",
        ref,
        ...rest,
        disabled
      }
    );
  }
);
CalendarNext.displayName = "CalendarNextButton";

const CalendarMonthButton = forwardRef((props, ref) => {
  const { calendarSelectionState, onClick, ...rest } = props;
  const { selectedMonth, locale } = useCalendar();
  const currentMonth = DateTime.fromObject({ month: selectedMonth }).setLocale(locale).toFormat("MMM");
  return /* @__PURE__ */ jsx(
    Button,
    {
      ref,
      appearance: "ghost",
      size: "small",
      onClick,
      icon: {
        after: calendarSelectionState === "month" ? SvgKeyboardArrowUp : SvgKeyboardArrowDown
      },
      ...rest,
      children: currentMonth
    }
  );
});
CalendarMonthButton.displayName = "CalendarMonthButton";

const CalendarDay = forwardRef(
  (props, ref) => {
    const { className, date, ...rest } = props;
    const context = useCalendar();
    const {
      disableAutofocus,
      value,
      setValue,
      focusedDate,
      setFocusedDate,
      hoveredDate,
      setHoveredDate,
      onSelection,
      locale,
      minDate,
      maxDate,
      unavailable,
      defaultTimeZone,
      controlled,
      id: uid,
      range,
      dateFormat,
      startDay,
      setSelectedMonth,
      setSelectedYear,
      dateMetadata
    } = context;
    const initialized = useRef(false);
    const futureDateSelection = useCallback(
      (targetDate) => {
        if (maxDate !== null && targetDate.toMillis() > maxDate?.toMillis()) {
          return;
        }
        if (isUnavailableDate(targetDate, unavailable, defaultTimeZone)) {
          let nextFocusDate = targetDate.plus({ days: 1 });
          for (let i = 0; i < 365; i++) {
            if (maxDate !== null && nextFocusDate.toMillis() > maxDate?.toMillis()) {
              break;
            }
            if (isUnavailableDate(nextFocusDate, unavailable, defaultTimeZone)) {
              nextFocusDate = nextFocusDate.plus({ days: 1 });
            } else {
              setFocusedDate(nextFocusDate);
              break;
            }
          }
          return;
        }
        setFocusedDate(targetDate);
        if (targetDate.month !== focusedDate.month) {
          setSelectedMonth(targetDate.month);
          if (targetDate.year !== focusedDate.year) {
            setSelectedYear(targetDate.year);
          }
        }
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps -- we don't need to re-render when the selected month or year changes
      [maxDate, setFocusedDate, defaultTimeZone, unavailable]
    );
    const pastDateSelection = (targetDate) => {
      if (minDate !== null && targetDate.toMillis() < minDate?.toMillis()) {
        return;
      }
      if (isUnavailableDate(targetDate, unavailable, defaultTimeZone)) {
        let prevFocusDate = targetDate.minus({ days: 1 });
        for (let i = 0; i < 365; i++) {
          if (minDate !== null && prevFocusDate.toMillis() < minDate?.toMillis()) {
            break;
          }
          if (isUnavailableDate(prevFocusDate, unavailable, defaultTimeZone)) {
            prevFocusDate = prevFocusDate.minus({ days: 1 });
          } else {
            setFocusedDate(prevFocusDate);
            break;
          }
        }
        return;
      }
      setFocusedDate(targetDate);
      if (targetDate.month !== focusedDate.month) {
        setSelectedMonth(targetDate.month);
        if (targetDate.year !== focusedDate.year) {
          setSelectedYear(targetDate.year);
        }
      }
    };
    const isSelectedDate = (date2, compareDate) => {
      if (!range) {
        return isSameDay(date2, value);
      }
      if (value.start && value.end) {
        return date2.toMillis() >= value.start.startOf("day").toMillis() && date2.toMillis() <= value.end.endOf("day").toMillis();
      }
      return isSameDay(date2, value.start);
    };
    const isRange = (date2) => {
      if (!range) {
        return false;
      }
      if (value.start && value.end) {
        return date2.toMillis() >= value.start.startOf("day").toMillis() && date2.toMillis() <= value.end.endOf("day").toMillis() && !isSameDay(value.start, date2) && !isSameDay(value.end, date2);
      }
      return false;
    };
    const onKeyDownHandler = (e) => {
      switch (e.code) {
        case "Space":
        case "Enter":
          e.preventDefault();
          if (!range) {
            if (!controlled) {
              setValue(isSameDay(value, focusedDate) ? null : focusedDate);
            }
            onSelection?.({
              value: isSameDay(value, focusedDate) ? void 0 : focusedDate.setZone(defaultTimeZone).startOf("day").toISO() ?? void 0
            });
            break;
          }
          rangeUpdater(value, focusedDate, setValue, onSelection);
          break;
        case "ArrowLeft":
          e.preventDefault();
          pastDateSelection(focusedDate.minus({ days: 1 }));
          break;
        case "ArrowRight":
          e.preventDefault();
          futureDateSelection(focusedDate.plus({ days: 1 }));
          break;
        case "ArrowUp":
          e.preventDefault();
          pastDateSelection(focusedDate.minus({ days: 7 }));
          break;
        case "ArrowDown":
          e.preventDefault();
          futureDateSelection(focusedDate.plus({ days: 7 }));
          break;
        case "PageUp":
          e.preventDefault();
          if (e.shiftKey) {
            pastDateSelection(focusedDate.minus({ years: 1 }));
            break;
          }
          pastDateSelection(focusedDate.minus({ months: 1 }));
          break;
        case "PageDown":
          e.preventDefault();
          if (e.shiftKey) {
            futureDateSelection(focusedDate.plus({ years: 1 }));
            break;
          }
          futureDateSelection(focusedDate.plus({ months: 1 }));
          break;
      }
    };
    let startDayIndex = 6;
    switch (startDay) {
      case "Monday":
        startDayIndex = 0;
        break;
      case "Sunday":
      default:
        startDayIndex = 6;
    }
    const weekdaysArr = [];
    for (let i = 0; i < 7; i++) {
      const dayIndex = (startDayIndex + i) % 7;
      weekdaysArr.push(Info.weekdays("narrow", { locale })[dayIndex]);
    }
    const firstDay = focusedDate.startOf("month");
    if (firstDay.weekday !== startDayIndex + 1) {
      for (let i = 1; i < 8; i++) {
        const prevDay = firstDay.minus({ days: i });
        if (prevDay.weekday === startDayIndex + 1) break;
      }
    }
    const onClickHandler = (d) => {
      setFocusedDate(d);
      if (!range) {
        onSelection?.({
          value: toDateString(d.setZone(defaultTimeZone)) ?? void 0
        });
        if (!controlled) {
          setValue(d);
        }
        return;
      }
      rangeUpdater(value, d, setValue, onSelection);
    };
    const onFocusHandler = (d) => {
      setHoveredDate(d);
    };
    const onBlurHandler = () => {
      setHoveredDate(void 0);
    };
    const onMouseEnterHandler = (d) => {
      setHoveredDate(d);
    };
    useEffect(() => {
      if (!initialized.current) {
        initialized.current = true;
        return;
      }
      if (!isSameDay(date, focusedDate)) return;
      requestAnimationFrame(() => {
        const dateId = `${uid}-${focusedDate.toISODate()}`;
        const targetElement = document.getElementById(dateId) || document.activeElement?.shadowRoot?.getElementById(dateId);
        const deepActiveEl = document.activeElement?.shadowRoot?.activeElement ?? document.activeElement;
        const isDayFocused = !!deepActiveEl?.id?.startsWith(`${uid}-`);
        if (!disableAutofocus || isDayFocused) {
          targetElement?.focus();
        }
      });
    }, [focusedDate, uid, disableAutofocus]);
    useEffect(() => {
      if (!isUnavailableDate(focusedDate, unavailable, defaultTimeZone)) return;
      futureDateSelection(focusedDate.plus({ days: 1 }));
    }, [focusedDate, futureDateSelection, defaultTimeZone, unavailable]);
    const isDisabled = !isSameMonth(date, focusedDate) || isBeyondMinDate(date, minDate) || isBeyondMaxDate(date, maxDate) || isUnavailableDate(date, unavailable, defaultTimeZone);
    const isUnavailable = isUnavailableDate(date, unavailable, defaultTimeZone);
    const hasMetadata = getDateMetadata(date, dateMetadata);
    const hoverRange = range && hoveredDate && value.start && !value.end && date.toMillis() > value.start.toMillis() && date.toMillis() <= hoveredDate.toMillis();
    const cellCx = cx(styles$1["cell"], {
      [styles$1["selected"]]: !isUnavailable && isSelectedDate(date),
      [styles$1["range-first"]]: range && value.start && (value.end || hoveredDate) && isSameDay(date, value.start),
      [styles$1["range-last"]]: range && (value.start && value.end && isSameDay(date, value.end) || hoverRange && isSameDay(date, hoveredDate)),
      [styles$1["range"]]: isRange(date) || hoverRange,
      [styles$1["is-unavailable"]]: isUnavailable,
      [styles$1["overflow"]]: !isSameMonth(date, focusedDate),
      [styles$1["hover-last"]]: hoverRange && isSameDay(date, hoveredDate),
      [styles$1["has-metadata"]]: hasMetadata
    });
    const isMinDate = minDate !== null && date.toMillis() <= minDate?.toMillis();
    const isMaxDate = maxDate !== null && date.toMillis() >= maxDate?.toMillis();
    return /* @__PURE__ */ jsxs("td", { role: "gridcell", ...rest, ref, children: [
      !isUnavailable && (isRange(date) || hoverRange) ? /* @__PURE__ */ jsx(
        "div",
        {
          role: "presentation",
          className: cx(styles$1["range-fill"], {
            [styles$1["range-disabled"]]: isDisabled,
            [styles$1["hover-last"]]: hoverRange && isSameDay(date, hoveredDate)
          })
        }
      ) : null,
      /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => onClickHandler(date),
          onFocus: () => onFocusHandler(date),
          onBlur: () => onBlurHandler(),
          className: cellCx,
          onKeyDown: onKeyDownHandler,
          onMouseEnter: () => onMouseEnterHandler(date),
          tabIndex: disableAutofocus ? -1 : isSameDay(date, focusedDate) ? 0 : -1,
          disabled: isDisabled ? true : void 0,
          "aria-label": `${date.toLocaleString(dateFormat)}${isSelectedDate(date) ? " selected" : ""}${hasMetadata ? `, ${hasMetadata}` : ""}${isMinDate ? ", You are on the first available date" : ""}${isMaxDate ? ", You are on the last available date" : ""}`,
          id: `${uid}-${date.toISODate()}`,
          children: [
            date.day,
            hasMetadata && /* @__PURE__ */ jsx("span", { className: styles$1["pip"], "aria-hidden": "true" })
          ]
        }
      )
    ] }, date.toISODate());
  }
);
CalendarDay.displayName = "CalendarDay";

const CalendarWeek = forwardRef(
  (props, ref) => {
    const { className, week, ...rest } = props;
    const context = useCalendar();
    const {
      focusedDate,
      setFocusedDate,
      locale,
      maxDate,
      unavailable,
      defaultTimeZone,
      id: uid,
      startDay
    } = context;
    const initialized = useRef(false);
    const futureDateSelection = useCallback(
      (targetDate) => {
        if (maxDate !== null && targetDate.toMillis() > maxDate?.toMillis()) {
          return;
        }
        if (isUnavailableDate(targetDate, unavailable, defaultTimeZone)) {
          let nextFocusDate = targetDate.plus({ days: 1 });
          for (let i = 0; i < 365; i++) {
            if (maxDate !== null && nextFocusDate.toMillis() > maxDate?.toMillis()) {
              break;
            }
            if (isUnavailableDate(nextFocusDate, unavailable, defaultTimeZone)) {
              nextFocusDate = nextFocusDate.plus({ days: 1 });
            } else {
              setFocusedDate(nextFocusDate);
              break;
            }
          }
          return;
        }
        setFocusedDate(targetDate);
      },
      [maxDate, setFocusedDate, defaultTimeZone, unavailable]
    );
    let startDayIndex = 6;
    switch (startDay) {
      case "Monday":
        startDayIndex = 0;
        break;
      case "Sunday":
      default:
        startDayIndex = 6;
    }
    const weekdaysArr = [];
    for (let i = 0; i < 7; i++) {
      const dayIndex = (startDayIndex + i) % 7;
      weekdaysArr.push(Info.weekdays("narrow", { locale })[dayIndex]);
    }
    const firstDay = focusedDate.startOf("month");
    if (firstDay.weekday !== startDayIndex + 1) {
      for (let i = 1; i < 8; i++) {
        const prevDay = firstDay.minus({ days: i });
        if (prevDay.weekday === startDayIndex + 1) break;
      }
    }
    useEffect(() => {
      if (!initialized.current) return;
      setTimeout(() => {
        const targetElement = document.getElementById(
          `${uid}-${focusedDate.toISODate()}`
        );
        targetElement?.focus();
      }, 100);
    }, [focusedDate, uid]);
    useEffect(() => {
      if (!isUnavailableDate(focusedDate, unavailable, defaultTimeZone)) return;
      futureDateSelection(focusedDate.plus({ days: 1 }));
    }, [focusedDate, futureDateSelection, defaultTimeZone, unavailable]);
    return /* @__PURE__ */ jsx("tr", { ...rest, ref, children: week.map((n) => {
      return /* @__PURE__ */ jsx(CalendarDay, { date: n }, n.toISODate());
    }) });
  }
);
CalendarWeek.displayName = "CalendarWeek";

const CalendarMonth = forwardRef(
  (props, ref) => {
    const { className, ...rest } = props;
    const context = useCalendar();
    const {
      value,
      focusedDate,
      setFocusedDate,
      setHoveredDate,
      locale,
      minDate,
      maxDate,
      unavailable,
      defaultTimeZone,
      id: uid,
      range,
      dateFormat,
      startDay
    } = context;
    const initialized = useRef(false);
    const ViewCX = cx(styles$1["grid"], className);
    const futureDateSelection = useCallback(
      (targetDate) => {
        if (maxDate !== null && targetDate.toMillis() > maxDate?.toMillis()) {
          return;
        }
        if (isUnavailableDate(targetDate, unavailable, defaultTimeZone)) {
          let nextFocusDate = targetDate.plus({ days: 1 });
          for (let i = 0; i < 365; i++) {
            if (maxDate !== null && nextFocusDate.toMillis() > maxDate?.toMillis()) {
              break;
            }
            if (isUnavailableDate(nextFocusDate, unavailable, defaultTimeZone)) {
              nextFocusDate = nextFocusDate.plus({ days: 1 });
            } else {
              setFocusedDate(nextFocusDate);
              break;
            }
          }
          return;
        }
        setFocusedDate(targetDate);
      },
      [maxDate, setFocusedDate, defaultTimeZone, unavailable]
    );
    let startDayIndex = 6;
    switch (startDay) {
      case "Monday":
        startDayIndex = 0;
        break;
      case "Sunday":
      default:
        startDayIndex = 6;
    }
    const weekdaysArr = [];
    for (let i = 0; i < 7; i++) {
      const dayIndex = (startDayIndex + i) % 7;
      weekdaysArr.push(Info.weekdays("narrow", { locale })[dayIndex]);
    }
    const firstDay = focusedDate.startOf("month");
    const lastDay = focusedDate.endOf("month");
    const monthArr = Array.from(new Array(firstDay.daysInMonth)).map((_, i) => {
      return firstDay.plus({ days: i });
    });
    const prevArr = [];
    if (firstDay.weekday !== startDayIndex + 1) {
      for (let i = 1; i < 8; i++) {
        const prevDay = firstDay.minus({ days: i });
        prevArr.push(prevDay);
        if (prevDay.weekday === startDayIndex + 1) break;
      }
    }
    prevArr.reverse();
    const nextArr = Array.from(new Array(14)).map((_, i) => {
      return lastDay.plus({ days: i + 1 });
    });
    const fullArr = [...prevArr, ...monthArr, ...nextArr];
    const splitArr = [...Array(Math.ceil(fullArr.length / 7))].map((_, i) => fullArr.slice(7 * i, 7 + 7 * i)).slice(0, 6);
    const onMouseLeaveHandler = () => {
      setHoveredDate(void 0);
    };
    const onSwipe = (dir) => {
      if (dir === "left") {
        const targetMonth = focusedDate.plus({ month: 1 });
        if (isBeyondMinDate(targetMonth, minDate) || isBeyondMaxDate(targetMonth, maxDate))
          return;
        setFocusedDate(targetMonth);
        return;
      }
      if (dir === "right") {
        const targetMonth = focusedDate.minus({ month: 1 });
        if (isBeyondMinDate(targetMonth, minDate) || isBeyondMaxDate(targetMonth, maxDate))
          return;
        setFocusedDate(targetMonth);
        return;
      }
    };
    const { direction, ...touchProps } = useSwipe(onSwipe);
    useEffect(() => {
      if (!initialized.current) return;
      setTimeout(() => {
        const targetElement = document.getElementById(
          `${uid}-${focusedDate.toISODate()}`
        );
        targetElement?.focus();
      }, 100);
    }, [focusedDate, uid]);
    useEffect(() => {
      if (!isUnavailableDate(focusedDate, unavailable, defaultTimeZone)) return;
      futureDateSelection(focusedDate.plus({ days: 1 }));
    }, [focusedDate, futureDateSelection, defaultTimeZone, unavailable]);
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs(
        "table",
        {
          ref,
          "data-anv": "calendar-month",
          onFocus: () => {
            initialized.current = true;
          },
          onBlur: () => {
            initialized.current = false;
          },
          className: ViewCX,
          onMouseLeave: onMouseLeaveHandler,
          role: "grid",
          ...rest,
          ...touchProps,
          children: [
            /* @__PURE__ */ jsxs("thead", { "aria-hidden": true, className: styles$1["weekdays"], children: [
              /* @__PURE__ */ jsx("tr", { children: weekdaysArr.map((weekday, i) => {
                return /* @__PURE__ */ jsx(
                  "th",
                  {
                    scope: "col",
                    className: styles$1["weekday"],
                    children: weekday
                  },
                  `${weekday}${i}`
                );
              }) }),
              /* @__PURE__ */ jsx("tr", { className: styles$1["spacer"], children: /* @__PURE__ */ jsx("td", { colSpan: 7 }) })
            ] }),
            /* @__PURE__ */ jsx(
              "tbody",
              {
                className: styles$1["day-grid"],
                children: splitArr.map((week, i) => {
                  return /* @__PURE__ */ jsx(CalendarWeek, { week }, i);
                })
              },
              focusedDate.startOf("month").toMillis()
            )
          ]
        }
      ),
      range && value ? /* @__PURE__ */ jsx(SrOnly, { "aria-live": "polite", children: `Range starts at ${value.start && value.start.toLocaleString(dateFormat)},  ${value.end ? `ends at ${value.end.toLocaleString(dateFormat)}` : "select an end date"}` }) : null
    ] });
  }
);
CalendarMonth.displayName = "CalendarMonth";

const styles = {
	"year-selector": "_year-selector_1jh12_1",
	"year-grid": "_year-grid_1jh12_17",
	"year-item": "_year-item_1jh12_25",
	"pseudo-focused": "_pseudo-focused_1jh12_29"
};

const useYearSelectorKeys = ({
  columns,
  scrollToYear,
  initialFocus,
  onSelect,
  onConfirm,
  pseudoFocused,
  setPseudoFocused,
  min,
  max,
  disabled,
  required
}) => {
  const listRef = useRef(null);
  useEffect(() => {
    const list = listRef.current;
    const handleKeyDown = (e) => {
      if (pseudoFocused === null) return;
      if ([
        "ArrowLeft",
        "ArrowRight",
        "ArrowUp",
        "ArrowDown",
        "Home",
        "PageUp",
        "PageDown",
        "Enter",
        " ",
        "Backspace",
        "Delete"
      ].includes(e.key)) {
        e.preventDefault();
        if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") {
          const newYear = e.key === "ArrowLeft" || e.key === "ArrowUp" ? pseudoFocused - 1 : pseudoFocused + 1;
          const clampedYear = Math.min(Math.max(newYear, min), max);
          scrollToYear(newYear, { focus: true });
          setPseudoFocused(newYear);
          if (!disabled) {
            onSelect(clampedYear);
          }
          return;
        }
        if (!required && (e.key === "Backspace" || e.key === "Delete")) {
          onSelect(null);
          return;
        }
        if (e.key === "PageUp" || e.key === "PageDown") {
          const newYear = e.key === "PageUp" ? min : max;
          scrollToYear(newYear, { focus: true });
          setPseudoFocused(newYear);
          if (!disabled) {
            onSelect(newYear);
          }
          return;
        }
        if (e.key === "Home") {
          scrollToYear(initialFocus, { focus: true });
          setPseudoFocused(initialFocus);
          if (!disabled) {
            onSelect(initialFocus);
          }
          return;
        }
        if (e.key === "Enter" || e.key === " ") {
          if (!disabled) {
            onConfirm();
          }
          return;
        }
      }
    };
    list?.addEventListener("keydown", handleKeyDown);
    return () => {
      list?.removeEventListener("keydown", handleKeyDown);
    };
  }, [
    pseudoFocused,
    columns,
    scrollToYear,
    onSelect,
    min,
    max,
    initialFocus,
    disabled,
    setPseudoFocused,
    required,
    onConfirm
  ]);
  return { listRef };
};

const YearItem = ({
  year,
  onChange,
  selected,
  pseudoFocused,
  disabled,
  onFocus,
  ...rest
}) => {
  return /* @__PURE__ */ jsx(
    SelectCard,
    {
      disabled,
      id: year,
      onChange: !disabled ? () => onChange(year) : () => {
      },
      onMouseDown: (e) => e.preventDefault(),
      checked: selected,
      checkboxProps: {
        tabIndex: -1,
        onFocus,
        ...pseudoFocused && { "data-interactive": "focus-visible" }
      },
      flexGrow: 1,
      className: cx(styles["year-item"], {
        [styles["pseudo-focused"]]: pseudoFocused
      }),
      "data-year": year,
      tabIndex: -1,
      ...rest,
      children: year
    }
  );
};

const DEFAULT_MIN = 1900;
const DEFAULT_MAX = 2200;
const currentYear = (/* @__PURE__ */ new Date()).getFullYear();
const YearSelector = forwardRef(
  ({
    min = DEFAULT_MIN,
    max = DEFAULT_MAX,
    value: valueProp,
    defaultValue: defaultValueProp,
    onChange,
    onConfirm,
    startingYear = currentYear,
    columns: columnsProp,
    className,
    required = false,
    disabled = false,
    ariaLabel = "Year selection",
    rootProps
  }, ref) => {
    const columns = Math.max(columnsProp ?? 2, 1);
    const [value, setValue] = useOptionallyControlledState({
      controlledValue: valueProp,
      defaultValue: defaultValueProp ?? null,
      onChange
    });
    const previousValue = usePrevious(value);
    const initialFocusYear = value ?? startingYear;
    const [pseudoFocused, setPseudoFocused] = useState(initialFocusYear);
    const handleChange = (year) => {
      if (!required && value === year) {
        setValue(null);
        return;
      }
      setValue(year);
      if (year !== null) {
        setPseudoFocused(year);
      }
    };
    const handleItemChange = (year) => {
      handleChange(year);
      onConfirm?.(year);
    };
    const gap = 12;
    const rowHeight = 58;
    const rowCount = Math.ceil((max - min + 1) / columns);
    const initialOffset = (initialFocusYear - min) * (rowHeight + gap) / columns + gap / 2;
    const rowVirtualizer = useVirtualizer({
      count: rowCount,
      getScrollElement: () => parentRef.current,
      estimateSize: () => rowHeight,
      gap,
      initialOffset,
      paddingEnd: gap / 2
    });
    const scrollToYear = useCallback(
      (year, { focus } = {}) => {
        const index = Math.floor((year - min) / columns);
        rowVirtualizer.scrollToIndex(index, { align: "center" });
        if (focus) {
          setPseudoFocused(year);
        }
      },
      [min, columns, rowVirtualizer, setPseudoFocused]
    );
    const parentRef = useRef(null);
    const { listRef } = useYearSelectorKeys({
      columns,
      scrollToYear,
      initialFocus: initialFocusYear,
      onSelect: handleChange,
      onConfirm: () => onConfirm?.(value),
      min,
      max,
      disabled,
      pseudoFocused,
      setPseudoFocused,
      required
    });
    useEffect(() => {
      if (value !== null && previousValue !== value) {
        scrollToYear(value, { focus: true });
      }
    }, [value, previousValue, scrollToYear, listRef]);
    const jointRef = useMergeRefs([parentRef, listRef, ref]);
    return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(
      "div",
      {
        ref: jointRef,
        "aria-label": ariaLabel,
        tabIndex: 0,
        className: cx(styles["year-selector"], className),
        role: "spinbutton",
        "aria-valuenow": value ?? void 0,
        "aria-valuemin": min,
        "aria-valuemax": max,
        "aria-valuetext": value ? `${value}` : "No year selected",
        "data-test": rowVirtualizer.options.paddingEnd,
        style: {
          maxHeight: `${rowVirtualizer.getTotalSize() + 8}px`
        },
        ...rootProps,
        children: /* @__PURE__ */ jsx(
          "div",
          {
            style: {
              height: `${rowVirtualizer.getTotalSize()}px`,
              width: "100%",
              position: "relative"
            },
            children: rowVirtualizer.getVirtualItems().map((virtualItem) => {
              const years = Array.from(
                { length: columns },
                (_, i) => virtualItem.index * columns + i + min
              );
              return /* @__PURE__ */ jsx(
                "div",
                {
                  "data-testid": "v-row",
                  className: styles["year-grid"],
                  style: {
                    transform: `translateY(${virtualItem.start}px)`,
                    gridTemplateColumns: `repeat(${columns}, 1fr)`
                  },
                  children: years.map((year) => {
                    if (year > max) return /* @__PURE__ */ jsx("div", {}, year);
                    return /* @__PURE__ */ jsx(
                      YearItem,
                      {
                        disabled,
                        year,
                        onChange: handleItemChange,
                        selected: value === year,
                        pseudoFocused: pseudoFocused === year,
                        onFocus: () => {
                          listRef.current?.focus();
                          setPseudoFocused(year);
                        }
                      },
                      year
                    );
                  })
                },
                virtualItem.key
              );
            })
          }
        )
      }
    ) });
  }
);
YearSelector.displayName = "YearSelector";

const CalendarMonthSelection = forwardRef(({ onMonthSelection, ...props }, ref) => {
  const { defaultTimeZone, maxDate, minDate, selectedMonth, selectedYear } = useCalendar();
  const monthSelectionRef = useRef(null);
  const combinedRef = useMergeRefs([ref, monthSelectionRef]);
  const currentDate = useMemo(
    () => DateTime.fromObject({ year: selectedYear, month: selectedMonth }).setZone(defaultTimeZone).startOf("day"),
    [defaultTimeZone, selectedYear, selectedMonth]
  );
  const dates = useMemo(
    () => Array.from({ length: 12 }, (_, i) => {
      const date = DateTime.fromObject({
        year: selectedYear,
        month: 1
      }).plus({
        month: i
      });
      const disabled = minDate && date < minDate && !date.hasSame(minDate, "month") || maxDate && date > maxDate && !date.hasSame(maxDate, "month");
      return {
        month: date.month,
        disabled: disabled ?? false
      };
    }),
    [maxDate, minDate, selectedYear]
  );
  const classes = cx(styles$1["month-selection"], props.className);
  const preventBlur = useCallback((e) => {
    e.preventDefault();
  }, []);
  const [focusedIndex, setFocusedIndex] = useState(selectedMonth - 1);
  useEffect(() => {
    if (minDate || maxDate) {
      let index = dates.findIndex(({ month }) => month === selectedMonth);
      while (dates[index].disabled && index < 11) {
        index++;
      }
      setFocusedIndex(index);
    } else {
      setFocusedIndex(selectedMonth - 1);
    }
  }, [selectedMonth, minDate, maxDate, dates]);
  const handleKeyDown = useCallback(
    (e) => {
      const target = e.target;
      const cards = monthSelectionRef.current?.querySelectorAll(
        "input[type='checkbox']"
      );
      if (!cards || cards.length === 0) {
        return;
      }
      const cardArray = Array.from(cards);
      const currentIndex = cardArray.indexOf(target);
      if (currentIndex === -1) return;
      const updateFocusedIndex = (index) => {
        e.preventDefault();
        cardArray[index].focus();
        setFocusedIndex(index);
      };
      let newIndex;
      switch (e.key) {
        case "ArrowLeft":
          newIndex = currentIndex > 0 ? currentIndex - 1 : 11;
          while (dates[newIndex].disabled) {
            newIndex = newIndex > 0 ? newIndex - 1 : 11;
          }
          updateFocusedIndex(newIndex);
          break;
        case "ArrowRight":
          newIndex = currentIndex < 11 ? currentIndex + 1 : 0;
          while (dates[newIndex].disabled) {
            newIndex = newIndex < 11 ? newIndex + 1 : 0;
          }
          updateFocusedIndex(newIndex);
          break;
        case "ArrowUp":
          if (currentIndex < 3) {
            newIndex = currentIndex + 9;
          } else {
            newIndex = currentIndex - 3;
          }
          while (dates[newIndex].disabled) {
            if (newIndex > 2) {
              newIndex -= 3;
            } else {
              newIndex += 9;
            }
          }
          updateFocusedIndex(newIndex);
          break;
        case "ArrowDown":
          if (currentIndex > 8) {
            newIndex = currentIndex - 9;
          } else {
            newIndex = currentIndex + 3;
          }
          while (dates[newIndex].disabled) {
            if (newIndex < 9) {
              newIndex += 3;
            } else {
              newIndex -= 9;
            }
          }
          updateFocusedIndex(newIndex);
          break;
        case "Enter":
        case " ":
          e.preventDefault();
          if (!dates[currentIndex].disabled) {
            onMonthSelection(dates[currentIndex].month);
          }
          break;
      }
    },
    [dates, onMonthSelection]
  );
  return /* @__PURE__ */ jsx(
    "div",
    {
      ref: combinedRef,
      "data-anv": "calendar-month-selection",
      className: classes,
      ...props,
      children: /* @__PURE__ */ jsx("div", { role: "grid", "aria-label": "Calendar month selection", children: /* @__PURE__ */ jsx(
        Grid,
        {
          templateColumns: "repeat(3, minmax(0, 1fr))",
          gap: 3,
          onKeyDown: handleKeyDown,
          role: "row",
          children: dates.map(({ month, disabled }, index) => /* @__PURE__ */ jsx("div", { role: "gridcell", children: /* @__PURE__ */ jsx(
            SelectCard,
            {
              id: month.toString(),
              disabled,
              onMouseDown: preventBlur,
              onChange: () => onMonthSelection(month),
              checked: selectedMonth === month && selectedYear === currentDate.year,
              checkboxProps: {
                className: styles$1["selection-checkbox"],
                tabIndex: focusedIndex === index ? 0 : -1
              },
              className: styles$1["selection-card"],
              children: DateTime.fromObject({ month }).toFormat("MMMM")
            }
          ) }, month.toString()))
        }
      ) })
    }
  );
});
CalendarMonthSelection.displayName = "CalendarMonthSelection";

const CalendarBetaPropsContext = createContext({});

const useCalendarBetaProps = () => {
  return useContext(CalendarBetaPropsContext);
};

const toolbarFocusStates = ["month", "year", "next", "prev", "now"];
const Calendar = Object.assign(
  forwardRef(function CalendarInner(props, ref) {
    const uid = useId();
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const {
      children,
      focusedDate: focusProp,
      defaultFocusedDate,
      locale = Intl.DateTimeFormat().resolvedOptions().locale,
      defaultTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone,
      startDay = "Sunday",
      minDate,
      maxDate,
      unavailable = {
        dates: [],
        daysOfWeek: []
      },
      id,
      style,
      value: iValue,
      defaultValue: iDefaultValue,
      onSelection,
      range,
      className,
      _disableAutofocus,
      _disableFocus,
      ...remainingProps
    } = componentProps;
    const { dateMetadata, onMonthView } = useCalendarBetaProps();
    const calendarRef = useRef(null);
    const combinedRef = useMergeRefs([ref, calendarRef]);
    const lastIValue = useRef(iValue);
    const yearButtonRef = useRef(null);
    const monthButtonRef = useRef(null);
    const headerRef = useRef(null);
    const [toolbarFocus, setToolbarFocus] = useState(toolbarFocusStates[0]);
    const [calendarWidth, setCalendarWidth] = useState(
      void 0
    );
    const [calendarSelectionState, setCalendarSelectionState] = useState("day");
    const visibleHeaderButtons = useMemo(() => {
      if (calendarSelectionState !== "day") {
        return toolbarFocusStates.slice(0, 2);
      }
      return toolbarFocusStates;
    }, [calendarSelectionState]);
    useEffect(() => {
      if (!calendarRef.current || style?.width != null) return;
      const resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
          const width = entry.contentRect.width;
          if (calendarSelectionState === "day" && width > 100) {
            setCalendarWidth(width);
          }
        }
      });
      resizeObserver.observe(calendarRef.current);
      return () => {
        resizeObserver.disconnect();
      };
    }, [calendarSelectionState, style?.width]);
    const styleCombined = {
      width: calendarWidth,
      ...style,
      ...layoutStyles
    };
    const classNameCombined = cx(styles$1["calendar"], className);
    const { nDate, nDefaultDate, nToday } = useMemo(
      () => ({
        nDate: iValue ? typeof iValue === "string" ? normalizeDate(iValue, defaultTimeZone) : {
          start: iValue.start ? normalizeDate(iValue.start, defaultTimeZone) : null,
          end: iValue.end ? normalizeDate(iValue.end, defaultTimeZone) : null
        } : null,
        nDefaultDate: iDefaultValue ? typeof iDefaultValue === "string" ? normalizeDate(iDefaultValue, defaultTimeZone) : {
          start: iDefaultValue.start ? normalizeDate(iDefaultValue.start, defaultTimeZone) : null,
          end: iDefaultValue?.end ? normalizeDate(iDefaultValue.end, defaultTimeZone) : null
        } : null,
        nToday: typeof iValue === "string" ? normalizeDate(DateTime.now().toISO(), defaultTimeZone) : {
          start: normalizeDate(DateTime.now().toISO(), defaultTimeZone),
          end: normalizeDate(DateTime.now().toISO(), defaultTimeZone)
        }
      }),
      [iValue, iDefaultValue, defaultTimeZone]
    );
    const [value, setValue] = useState(nDate ?? nDefaultDate ?? nToday);
    const getInitialDate = useMemo(() => {
      if (defaultFocusedDate) {
        return normalizeDate(defaultFocusedDate, defaultTimeZone);
      }
      if (iDefaultValue) {
        const date = typeof iDefaultValue === "string" ? normalizeDate(iDefaultValue, defaultTimeZone) : normalizeDate(
          iDefaultValue.start ?? iDefaultValue.end ?? "",
          defaultTimeZone
        );
        return date;
      }
      if (!DateTime.isDateTime(nDate) && !DateTime.isDateTime(nDefaultDate) && !DateTime.isDateTime(nToday)) {
        return nDate?.start ?? nDefaultDate?.start ?? nToday?.start;
      }
      return nDate ?? nDefaultDate ?? nToday;
    }, [
      defaultFocusedDate,
      iDefaultValue,
      nDate,
      nDefaultDate,
      nToday,
      defaultTimeZone
    ]);
    const initialDate = getInitialDate ?? DateTime.now();
    const [focusedDate, setFocusedDate] = useState(initialDate);
    const [hoveredDate, setHoveredDate] = useState();
    const [selectedMonth, setSelectedMonth] = useState(
      initialDate.month
    );
    const [selectedYear, setSelectedYear] = useState(
      initialDate.year
    );
    const currentVisibleMonth = useMemo(() => {
      return {
        year: focusedDate?.year ?? selectedYear,
        month: focusedDate?.month ?? selectedMonth
      };
    }, [focusedDate?.month, focusedDate?.year, selectedYear, selectedMonth]);
    useEffect(
      () => onMonthView?.(currentVisibleMonth),
      // eslint-disable-next-line react-hooks/exhaustive-deps -- omit onMonthView from deps because we don't want to trigger infinite re-renders
      [currentVisibleMonth]
    );
    useEffect(() => {
      if (!focusProp && !defaultFocusedDate) return;
      if (focusProp) {
        setFocusedDate(normalizeDate(focusProp, defaultTimeZone));
      } else if (defaultFocusedDate) {
        setFocusedDate(normalizeDate(defaultFocusedDate, defaultTimeZone));
        setSelectedMonth(
          normalizeDate(defaultFocusedDate, defaultTimeZone).month
        );
        setSelectedYear(
          normalizeDate(defaultFocusedDate, defaultTimeZone).year
        );
      }
    }, [focusProp, defaultFocusedDate]);
    useEffect(() => {
      if (!iValue) {
        lastIValue.current = iValue;
        return;
      }
      if (typeof iValue === "string") {
        setValue(normalizeDate(iValue, defaultTimeZone));
        setFocusedDate(normalizeDate(iValue, defaultTimeZone));
      } else if (iValue.end && (typeof lastIValue.current !== "object" || lastIValue?.current?.end !== iValue.end)) {
        setValue({
          start: iValue.start ? normalizeDate(iValue.start, defaultTimeZone) : null,
          end: iValue.end ? normalizeDate(iValue.end, defaultTimeZone) : null
        });
        setFocusedDate(normalizeDate(iValue.end, defaultTimeZone));
      } else if (iValue.start && (typeof lastIValue.current !== "object" || lastIValue?.current?.start !== iValue.start)) {
        setFocusedDate(normalizeDate(iValue.start, defaultTimeZone));
      }
      lastIValue.current = iValue;
    }, [iValue]);
    const normalizedMinDate = useMemo(
      () => minDate ? normalizeDate(minDate, defaultTimeZone) : null,
      [minDate, defaultTimeZone]
    );
    const normalizedMaxDate = useMemo(
      () => maxDate ? normalizeDate(maxDate, defaultTimeZone) : null,
      [maxDate, defaultTimeZone]
    );
    const dateMetadataMap = useMemo(() => {
      if (!dateMetadata) return void 0;
      return new Map(dateMetadata.map((item) => [item.date, item.context]));
    }, [dateMetadata]);
    const providerValue = useMemo(() => {
      const format = {
        weekday: "long",
        month: "long",
        day: "2-digit",
        year: "numeric"
      };
      return {
        disableAutofocus: _disableAutofocus ?? false,
        focusedDate,
        setFocusedDate,
        selectedMonth,
        setSelectedMonth,
        selectedYear,
        setSelectedYear,
        hoveredDate,
        setHoveredDate,
        value,
        setValue,
        defaultTimeZone,
        id: id ?? uid,
        onSelection,
        controlled: !!iValue,
        range,
        minDate: normalizedMinDate,
        maxDate: normalizedMaxDate,
        unavailable: {
          dates: new Set(unavailable.dates),
          daysOfWeek: new Set(unavailable.daysOfWeek)
        },
        locale,
        dateFormat: format,
        startDay,
        dateMetadata: dateMetadataMap
      };
    }, [
      focusedDate,
      selectedMonth,
      selectedYear,
      hoveredDate,
      id,
      locale,
      normalizedMaxDate,
      normalizedMinDate,
      iValue,
      onSelection,
      range,
      defaultTimeZone,
      uid,
      unavailable,
      value,
      startDay,
      dateMetadataMap,
      _disableAutofocus
    ]);
    const handleHeaderKeyDown = useCallback(
      (e) => {
        switch (e.key) {
          case "ArrowDown": {
            e.preventDefault();
            if (calendarSelectionState === "day") {
              const focusedDayId = `${id ?? uid}-${focusedDate?.toISODate()}`;
              const root = e.currentTarget.getRootNode() ?? document;
              root.getElementById(focusedDayId)?.focus();
            }
            break;
          }
          case "ArrowLeft":
            e.preventDefault();
            setToolbarFocus((previousToolbarFocus) => {
              const newToolbarFocus = previousToolbarFocus === visibleHeaderButtons[0] ? visibleHeaderButtons[visibleHeaderButtons.length - 1] : visibleHeaderButtons[visibleHeaderButtons.indexOf(previousToolbarFocus) - 1] ?? visibleHeaderButtons[visibleHeaderButtons.length - 1];
              const button = headerRef.current?.querySelector(
                `[data-calendar-header-button-name="${newToolbarFocus}"]`
              );
              if (button && "focus" in button && typeof button.focus === "function") {
                button.focus();
              }
              return newToolbarFocus;
            });
            break;
          case "ArrowRight":
            e.preventDefault();
            setToolbarFocus((previousToolbarFocus) => {
              const newToolbarFocus = previousToolbarFocus === visibleHeaderButtons[visibleHeaderButtons.length - 1] ? visibleHeaderButtons[0] : visibleHeaderButtons[visibleHeaderButtons.indexOf(previousToolbarFocus) + 1] ?? visibleHeaderButtons[0];
              const button = headerRef.current?.querySelector(
                `[data-calendar-header-button-name="${newToolbarFocus}"]`
              );
              if (button && "focus" in button && typeof button.focus === "function") {
                button.focus();
              }
              return newToolbarFocus;
            });
        }
      },
      [visibleHeaderButtons, calendarSelectionState, focusedDate, id, uid]
    );
    const handleMonthSelection = useCallback(
      (month) => {
        monthButtonRef.current?.focus();
        setToolbarFocus(toolbarFocusStates[0]);
        setSelectedMonth(month);
        setFocusedDate(
          DateTime.fromObject(
            {
              year: focusedDate?.year ?? 1,
              month,
              day: 1
            },
            { zone: defaultTimeZone }
          ).startOf("day")
        );
        setCalendarSelectionState("day");
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [focusedDate]
    );
    const handleYearSelection = useCallback(
      (year) => {
        if (year === null) return;
        yearButtonRef.current?.focus();
        setToolbarFocus(toolbarFocusStates[1]);
        setSelectedYear(year);
        setFocusedDate(
          DateTime.fromObject(
            {
              year,
              month: focusedDate?.month ?? 1,
              day: 1
            },
            { zone: defaultTimeZone }
          ).startOf("day")
        );
        setCalendarSelectionState("day");
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [focusedDate?.month]
    );
    return /* @__PURE__ */ jsx(CalendarContext.Provider, { value: providerValue, children: /* @__PURE__ */ jsxs(
      "div",
      {
        ref: combinedRef,
        id: id ?? uid,
        style: styleCombined,
        className: classNameCombined,
        "data-anv": "calendar",
        ...remainingProps,
        children: [
          /* @__PURE__ */ jsx("div", { className: styles$1["header"], children: /* @__PURE__ */ jsxs(
            "span",
            {
              ref: headerRef,
              "aria-label": "Calendar navigation",
              role: "toolbar",
              tabIndex: -1,
              onKeyDown: handleHeaderKeyDown,
              className: styles$1["controller"],
              children: [
                /* @__PURE__ */ jsx(
                  CalendarMonthButton,
                  {
                    ref: monthButtonRef,
                    tabIndex: _disableFocus ? -1 : toolbarFocus === toolbarFocusStates[0] ? 0 : -1,
                    "data-calendar-header-button": true,
                    "data-calendar-header-button-name": toolbarFocusStates[0],
                    calendarSelectionState,
                    onClick: () => {
                      setCalendarSelectionState(
                        (prev) => prev === "month" ? "day" : "month"
                      );
                      setToolbarFocus(toolbarFocusStates[0]);
                    }
                  }
                ),
                /* @__PURE__ */ jsx(
                  CalendarYearButton,
                  {
                    ref: yearButtonRef,
                    tabIndex: _disableFocus ? -1 : toolbarFocus === toolbarFocusStates[1] ? 0 : -1,
                    "data-calendar-header-button": true,
                    "data-calendar-header-button-name": toolbarFocusStates[1],
                    calendarSelectionState,
                    onClick: () => {
                      setCalendarSelectionState(
                        (prev) => prev === "year" ? "day" : "year"
                      );
                      setToolbarFocus(toolbarFocusStates[1]);
                    }
                  }
                ),
                calendarSelectionState === "day" && /* @__PURE__ */ jsxs(Fragment, { children: [
                  /* @__PURE__ */ jsx(
                    CalendarPrev,
                    {
                      tabIndex: _disableFocus ? -1 : toolbarFocus === toolbarFocusStates[2] ? 0 : -1,
                      "data-calendar-header-button": true,
                      "data-calendar-header-button-name": toolbarFocusStates[2],
                      onClick: () => setToolbarFocus(toolbarFocusStates[2])
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    CalendarNext,
                    {
                      tabIndex: _disableFocus ? -1 : toolbarFocus === toolbarFocusStates[3] ? 0 : -1,
                      "data-calendar-header-button": true,
                      "data-calendar-header-button-name": toolbarFocusStates[3],
                      onClick: () => setToolbarFocus(toolbarFocusStates[3])
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    CalendarNow,
                    {
                      tabIndex: _disableFocus ? -1 : toolbarFocus === toolbarFocusStates[4] ? 0 : -1,
                      "data-calendar-header-button": true,
                      "data-calendar-header-button-name": toolbarFocusStates[4],
                      onClickFixed: () => setToolbarFocus(toolbarFocusStates[4])
                    }
                  )
                ] })
              ]
            }
          ) }),
          calendarSelectionState === "day" && /* @__PURE__ */ jsx(CalendarMonth, {}),
          calendarSelectionState === "month" && /* @__PURE__ */ jsx(CalendarMonthSelection, { onMonthSelection: handleMonthSelection }),
          calendarSelectionState === "year" && // Wrapper div provides some manual offsetting to account for internal padding of the year selector
          /* @__PURE__ */ jsx("div", { className: styles$1["year-selector"], children: /* @__PURE__ */ jsx(
            YearSelector,
            {
              onConfirm: handleYearSelection,
              required: true,
              defaultValue: selectedYear,
              min: normalizedMinDate?.year,
              max: normalizedMaxDate?.year
            }
          ) })
        ]
      }
    ) });
  }),
  {
    /**
     * Calendar.Now component for navigating to today's date.
     *
     * Features:
     * - Quick navigation to current date
     * - Accessible button with proper ARIA labels
     * - Integrates with calendar context
     * - Data tracking integration for analytics
     *
     * @example
     * <Calendar.Now />
     */
    Now: CalendarNow,
    /**
     * Calendar.Month component for displaying the month grid.
     *
     * Features:
     * - Displays calendar days in a table format
     * - Handles day selection and navigation
     * - Supports range selection mode
     * - Accessible with proper ARIA attributes
     * - Data tracking integration for analytics
     *
     * @example
     * <Calendar.Month />
     */
    Month: CalendarMonth,
    /**
     * Calendar.Next component for navigating to the next month.
     *
     * Features:
     * - Navigation to next month
     * - Accessible button with proper ARIA labels
     * - Integrates with calendar context
     * - Data tracking integration for analytics
     *
     * @example
     * <Calendar.Next />
     */
    Next: CalendarNext,
    /**
     * Calendar.Prev component for navigating to the previous month.
     *
     * Features:
     * - Navigation to previous month
     * - Accessible button with proper ARIA labels
     * - Integrates with calendar context
     * - Data tracking integration for analytics
     *
     * @example
     * <Calendar.Prev />
     */
    Prev: CalendarPrev,
    /**
     * Calendar.MonthButton component for switching to month selection view.
     *
     * Features:
     * - Switches calendar to month selection mode
     * - Accessible button with proper ARIA labels
     * - Integrates with calendar context
     * - Data tracking integration for analytics
     *
     * @example
     * <Calendar.MonthButton />
     */
    MonthButton: CalendarMonthButton,
    /**
     * Calendar.YearButton component for switching to year selection view.
     *
     * Features:
     * - Switches calendar to year selection mode
     * - Accessible button with proper ARIA labels
     * - Integrates with calendar context
     * - Data tracking integration for analytics
     *
     * @example
     * <Calendar.YearButton />
     */
    YearButton: CalendarYearButton
  }
);
Calendar.displayName = "Calendar";

export { CalendarBetaPropsContext as C, Calendar as a, CalendarNow as b, CalendarYearButton as c, CalendarPrev as d, CalendarNext as e, CalendarMonthButton as f, CalendarMonth as g, useCalendarBetaProps as u };
//# sourceMappingURL=Calendar-CekTYzdT.js.map
