import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { forwardRef, useRef, useImperativeHandle, useMemo, useEffect, useState, useCallback } from 'react';
import { I as Icon } from './Icon-BMMbp40n.js';
import { F as Flex } from './Flex-DOUtHiPi.js';
import { S as SvgCheck } from './check-Cf67OWrZ.js';
import { c as cx } from './index-De1g9FRV.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-CB_zHDbW.js';
import { P as Popover, u as useMergeRefs } from './AiMark-B1-M3ZgP.js';
import { g as maskitoUpdateElement, m as maskitoDateOptionsGenerator, a as maskitoWithPlaceholder, h as maskitoTransform, u as useMaskito } from './index.esm-C2ZhC_8d.js';
import { m as makeZeroShortcutPreprocessor } from './makeZeroShortcutPreprocessor-CxsiGTRW.js';
import { t as textFieldStyles } from './TextField.module-MRVo1X9H.js';
import { S as Spinner } from './Spinner-lPMo68yW.js';
import { u as usePrevious } from './usePrevious-Bvq-5auG.js';
import { m as mergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { u as useOptionallyControlledState } from './useOptionallyControlledState-DbDuos5L.js';
import { u as useFocusWithin } from './useFocusWithin-hi77jsrB.js';

import './YearlessDateInputWithPicker.css';const children = "_children_157fd_93";
const styles = {
	"picker-list": "_picker-list_157fd_1",
	"picker-list-option": "_picker-list-option_157fd_19",
	children: children};

const PickerListOption = forwardRef((props, ref) => {
  const {
    className,
    children,
    onClick,
    item,
    isSelected,
    onSelectionChange,
    alignItems,
    justifyItems,
    alignContent,
    justifyContent,
    placeItems,
    placeContent,
    ...rest
  } = props;
  const disabled = item.disabled || false;
  const handleSelection = () => {
    if (disabled) return;
    if (isSelected) {
      onSelectionChange(void 0);
    } else {
      onSelectionChange(item);
    }
  };
  const onClickHandler = (e) => {
    onClick?.(e);
    handleSelection();
  };
  const onKeyDownHandler = (e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      handleSelection();
    }
  };
  const PickerListOptionClassNames = cx(
    styles["picker-list-option"],
    className
  );
  return /* @__PURE__ */ jsxs(
    "li",
    {
      className: PickerListOptionClassNames,
      "data-anv": "picker-list-option",
      role: "option",
      "aria-disabled": disabled,
      "aria-selected": isSelected,
      "data-item-label": item.label,
      onClick: onClickHandler,
      onKeyDown: onKeyDownHandler,
      tabIndex: -1,
      ref,
      ...rest,
      children: [
        /* @__PURE__ */ jsx(
          Flex,
          {
            className: styles["children"],
            grow: 1,
            shrink: 1,
            alignItems,
            justifyItems,
            alignContent,
            justifyContent,
            placeItems,
            placeContent,
            children: children || item.label
          }
        ),
        /* @__PURE__ */ jsx(
          Icon,
          {
            "aria-hidden": true,
            svg: SvgCheck,
            inherit: true,
            className: styles["Icon"],
            style: { opacity: isSelected ? 1 : 0 }
          }
        )
      ]
    }
  );
});
PickerListOption.displayName = "PickerListOption";

const PickerList = forwardRef(
  (props, ref) => {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const {
      className,
      items,
      onSelectionChange,
      selected: selectedProp,
      style,
      ...rest
    } = componentProps;
    const listRef = useRef(null);
    const scrollToItem = (label, behavior = "smooth") => {
      const listElement = listRef.current;
      const itemElement = listElement?.querySelector(
        `li[data-item-label="${label}"]`
      );
      if (listElement && itemElement) {
        const itemTop = itemElement.offsetTop;
        const itemHeight = itemElement.offsetHeight;
        const listHeight = listElement.clientHeight;
        const targetScrollTop = itemTop - listHeight / 2 + itemHeight / 2;
        const maxScrollTop = listElement.scrollHeight - listHeight;
        const clampedScrollTop = Math.max(
          0,
          Math.min(targetScrollTop, maxScrollTop)
        );
        listElement.scrollTo({
          top: clampedScrollTop,
          behavior
        });
      }
    };
    const scrollToValue = (value, behavior = "smooth") => {
      const item = items.find((item2) => item2.value === value);
      if (item) {
        scrollToItem(item.label, behavior);
      }
    };
    useImperativeHandle(ref, () => ({
      scrollToItem,
      scrollToValue
    }));
    const handleSelectionChange = (item) => {
      onSelectionChange?.(item);
    };
    const PickerListClassNames = cx(styles["picker-list"], className);
    const styleCombined = {
      ...style,
      ...layoutStyles
    };
    return /* @__PURE__ */ jsx(
      "ul",
      {
        role: "listbox",
        style: styleCombined,
        className: PickerListClassNames,
        "data-anv": "picker-list",
        ref: listRef,
        ...rest,
        tabIndex: -1,
        children: items.map((item) => /* @__PURE__ */ jsx(
          PickerListOption,
          {
            item,
            isSelected: selectedProp?.value === item.value,
            onSelectionChange: handleSelectionChange
          },
          item.label
        ))
      }
    );
  }
);
PickerList.displayName = "PickerList";

function validateYearlessDate({
  value,
  constraints
}) {
  const { required, unavailable, minDate, maxDate } = constraints;
  if (!value || !value?.day && !value?.month) {
    return required ? false : true;
  }
  if (value.day === null || value.month === null) {
    return false;
  }
  if (unavailable?.dates?.some(
    (d) => d.day === value.day && d.month === value.month
  )) {
    return false;
  }
  const minDateMonth = minDate?.month ?? 1;
  const minDateDay = minDate?.day ?? 1;
  const maxDateMonth = maxDate?.month ?? 12;
  const maxDateDay = maxDate?.day ?? 31;
  if (value.month < minDateMonth || // Earlier month
  value.month === minDateMonth && value.day < minDateDay) {
    return false;
  }
  if (value.month > maxDateMonth || // Later month
  value.month === maxDateMonth && value.day > maxDateDay) {
    return false;
  }
  return true;
}
function getMonthNames({
  locale,
  format
}) {
  const formatFn = new Intl.DateTimeFormat(locale, { month: format }).format;
  return [...Array(12).keys()].map(
    (m) => formatFn(new Date(Date.UTC(2021, (m + 1) % 12)))
  );
}
function parseInputValue(value, mode, removePlaceholder) {
  const valueMinusPlaceholder = removePlaceholder(value);
  const [segment1, segment2] = valueMinusPlaceholder.split("/");
  const incompleteFirstSegment = segment1?.length !== 2;
  const incompleteSecondSegment = segment2?.length !== 2;
  if (mode === "dd/mm") {
    return {
      value: {
        day: incompleteFirstSegment ? null : parseInt(segment1),
        month: incompleteSecondSegment ? null : parseInt(segment2)
      },
      isInputValid: !incompleteFirstSegment && !incompleteSecondSegment,
      isInputEmpty: valueMinusPlaceholder === ""
    };
  }
  return {
    value: {
      day: incompleteSecondSegment ? null : parseInt(segment2),
      month: incompleteFirstSegment ? null : parseInt(segment1)
    },
    isInputValid: !incompleteFirstSegment && !incompleteSecondSegment,
    isInputEmpty: valueMinusPlaceholder === ""
  };
}
function swapMode(inputString, previousMode, mode) {
  const { day, month } = divideSegments(inputString, previousMode);
  return stringifyYearlessDate(day, month, mode);
}
function divideSegments(value, mode) {
  const [segment1, segment2] = value.split("/");
  if (mode === "dd/mm") {
    return { day: segment1, month: segment2 };
  }
  return { day: segment2, month: segment1 };
}
function stringifyYearlessDate(day, month, mode) {
  const dd = (day ?? "__").toString().padStart(2, "0");
  const mm = (month ?? "__").toString().padStart(2, "0");
  if (mode === "dd/mm") {
    return `${dd}/${mm}`;
  }
  return `${mm}/${dd}`;
}
function getDaysInMonth(month) {
  return new Date(2024, month, 0).getDate();
}
function getInvalidMonthsForDay(day) {
  const invalidMonths = [];
  for (let month = 1; month <= 12; month++) {
    const daysInMonth = getDaysInMonth(month);
    if (day > daysInMonth) {
      invalidMonths.push(month);
    }
  }
  return invalidMonths;
}

const dateFieldYearlessStyles = {
	"scrolling-container": "_scrolling-container_er1xu_1"
};

function YearlessDateSelectionPopover({
  children,
  popoverRef,
  popoverContentRef,
  month,
  day,
  onMonthChange,
  onDayChange,
  onClose,
  mode,
  onFocus,
  onBlur
}) {
  const monthListboxRef = useRef(null);
  const dayListboxRef = useRef(null);
  const months = useMemo(() => {
    return getMonthNames({ locale: "en-US", format: "short" }).map(
      (name, index) => ({
        label: name,
        value: index + 1
      })
    );
  }, []);
  const days = useMemo(() => {
    return Array.from({ length: 31 }, (_, i) => ({
      label: `${i + 1}`,
      value: i + 1
    }));
  }, []);
  const invalidDays = useMemo(() => {
    if (!month) {
      return [];
    }
    const daysInMonth = getDaysInMonth(month);
    return Array.from(
      { length: 31 - daysInMonth },
      (_, i) => daysInMonth + i + 1
    );
  }, [month]);
  const invalidMonths = useMemo(() => {
    if (!day) {
      return [];
    }
    return getInvalidMonthsForDay(day);
  }, [day]);
  const scrollToSelectedOption = (value, ref, behavior = "smooth") => {
    if (value && ref.current) {
      ref.current.scrollToValue(value, behavior);
    }
  };
  useEffect(() => {
    scrollToSelectedOption(month, monthListboxRef, "smooth");
  }, [month]);
  useEffect(() => {
    scrollToSelectedOption(day, dayListboxRef, "smooth");
  }, [day]);
  const handleMonthChange = (selected) => {
    if (selected?.value) {
      onMonthChange?.(selected.value);
      if (day && invalidDays.includes(day)) {
        onDayChange?.(null);
      }
    }
  };
  const handleDayChange = (selected) => {
    if (selected?.value) {
      onDayChange?.(selected.value);
      if (month && invalidMonths.includes(month)) {
        onMonthChange?.(null);
      }
    }
  };
  const monthPicker = /* @__PURE__ */ jsx(
    PickerList,
    {
      ref: monthListboxRef,
      items: months.map((item) => ({
        ...item,
        disabled: invalidMonths.includes(item.value)
      })),
      selected: months.find((m) => m.value === month),
      style: { maxHeight: "240px", overflow: "auto" },
      className: dateFieldYearlessStyles["scrolling-container"],
      onSelectionChange: handleMonthChange
    }
  );
  const dayPicker = /* @__PURE__ */ jsx(
    PickerList,
    {
      ref: dayListboxRef,
      items: days.map((item) => ({
        ...item,
        disabled: invalidDays.includes(item.value)
      })),
      selected: days.find((d) => d.value === day),
      className: dateFieldYearlessStyles["scrolling-container"],
      onSelectionChange: handleDayChange
    }
  );
  return /* @__PURE__ */ jsxs(
    Popover,
    {
      ref: popoverRef,
      placement: "bottom-start",
      role: "listbox",
      onClose,
      onOpenAnimationStart: () => {
        scrollToSelectedOption(month, monthListboxRef, "instant");
        scrollToSelectedOption(day, dayListboxRef, "instant");
      },
      children: [
        /* @__PURE__ */ jsx(Popover.Trigger, { children: (triggerProps) => /* @__PURE__ */ jsx(Fragment, { children: children(triggerProps) }) }),
        /* @__PURE__ */ jsx(
          Popover.Content,
          {
            ref: popoverContentRef,
            onFocus,
            onBlur,
            hideWhileClosed: true,
            children: /* @__PURE__ */ jsx(Flex, { gap: 2, style: { maxHeight: "240px" }, children: mode === "dd/mm" ? /* @__PURE__ */ jsxs(Fragment, { children: [
              dayPicker,
              monthPicker
            ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
              monthPicker,
              dayPicker
            ] }) })
          }
        )
      ]
    }
  );
}

const MIN_MONTH = 1;
const MAX_MONTH = 12;
const MIN_DAY = 1;
const MAX_DAY = 31;
const SEGMENT_LENGTH = 2;
function createYearlessDateSegmentsSteppingPlugin({
  mode
}) {
  const segmentsIndexes = createSegmentIndexes(mode);
  return (element) => {
    const listener = (event) => {
      if (event.key === "ArrowRight") {
        handleArrowRight(element, event);
        return;
      }
      if (event.key !== "ArrowUp" && event.key !== "ArrowDown") {
        return;
      }
      event.preventDefault();
      const selectionStart = element.selectionStart ?? 0;
      const activeSegment = getActiveSegment({
        segmentsIndexes,
        selectionStart
      });
      if (!activeSegment) {
        return;
      }
      const segmentSelection = segmentsIndexes.get(activeSegment);
      if (!segmentSelection) {
        return;
      }
      const maxValue = getMaxValueForSegment(
        activeSegment,
        element.value,
        segmentsIndexes
      );
      const updatedValue = updateSegmentValue({
        selection: segmentSelection,
        value: element.value,
        increment: event.key === "ArrowUp" ? -1 : 1,
        min: MIN_DAY,
        max: maxValue
      });
      const finalValue = activeSegment === "month" ? adjustDayForNewMonth(updatedValue, segmentsIndexes) : updatedValue;
      maskitoUpdateElement(element, {
        value: finalValue,
        selection: [selectionStart, selectionStart]
      });
    };
    element.addEventListener("keydown", listener);
    return () => element.removeEventListener("keydown", listener);
  };
}
function createSegmentIndexes(mode) {
  const map = /* @__PURE__ */ new Map();
  if (mode === "mm/dd") {
    map.set("month", [0, SEGMENT_LENGTH]);
    map.set("day", [SEGMENT_LENGTH + 1, SEGMENT_LENGTH * 2 + 1]);
  } else if (mode === "dd/mm") {
    map.set("day", [0, SEGMENT_LENGTH]);
    map.set("month", [SEGMENT_LENGTH + 1, SEGMENT_LENGTH * 2 + 1]);
  }
  return map;
}
function handleArrowRight(element, event) {
  const selectionStart = element.selectionStart ?? 0;
  const value = element.value;
  if (selectionStart === SEGMENT_LENGTH && value.includes("__")) {
    event.preventDefault();
    maskitoUpdateElement(element, {
      value: value + "/",
      selection: [selectionStart + 1, selectionStart + 1]
    });
  }
}
function adjustDayForNewMonth(value, segmentsIndexes) {
  const monthSelection = segmentsIndexes.get("month");
  const daySelection = segmentsIndexes.get("day");
  if (!monthSelection || !daySelection) {
    return value;
  }
  const monthValue = parseSegmentValue(value, monthSelection);
  const dayValue = parseSegmentValue(value, daySelection);
  if (monthValue < MIN_MONTH || monthValue > MAX_MONTH || dayValue < MIN_DAY) {
    return value;
  }
  const maxDaysInMonth = getDaysInMonth(monthValue);
  if (dayValue <= maxDaysInMonth) {
    return value;
  }
  const [dayFrom, dayTo] = daySelection;
  const adjustedDay = String(maxDaysInMonth).padStart(dayTo - dayFrom, "0");
  return value.slice(0, dayFrom) + adjustedDay + value.slice(dayTo, value.length);
}
function parseSegmentValue(value, selection) {
  const [from, to] = selection;
  const segmentText = value.slice(from, to);
  if (segmentText.includes("_")) return 0;
  return Number(segmentText.padEnd(to - from, "0"));
}
function getMaxValueForSegment(segment, value, segmentsIndexes) {
  if (segment === "month") {
    return MAX_MONTH;
  }
  const monthSelection = segmentsIndexes.get("month");
  if (!monthSelection) {
    return MAX_DAY;
  }
  const monthValue = parseSegmentValue(value, monthSelection);
  if (monthValue < MIN_MONTH || monthValue > MAX_MONTH) {
    return MAX_DAY;
  }
  return getDaysInMonth(monthValue);
}
function getActiveSegment({
  segmentsIndexes,
  selectionStart
}) {
  for (const [segmentName, segmentRange] of segmentsIndexes.entries()) {
    const [from, to] = segmentRange;
    if (from <= selectionStart && selectionStart <= to) {
      return segmentName;
    }
  }
  return null;
}
function updateSegmentValue({
  selection,
  value,
  increment,
  min,
  max
}) {
  const [from, to] = selection;
  const segmentValue = parseSegmentValue(value, selection);
  if (segmentValue === 0 && increment < 0) return value;
  const newSegmentValue = Math.max(
    min,
    Math.min(max, segmentValue + increment)
  );
  return value.slice(0, from) + String(newSegmentValue).padStart(to - from, "0") + value.slice(to, value.length);
}

const yearlessDatePlaceholderMask = ({
  mode,
  separator = "/",
  placeholder,
  enableStepping = false
}) => {
  const dateOptions = maskitoDateOptionsGenerator({
    mode,
    separator
  });
  const { plugins, removePlaceholder, ...placeholderOptions } = maskitoWithPlaceholder(placeholder);
  const datePlaceholderMask = {
    ...dateOptions,
    plugins: plugins.concat([
      ...dateOptions.plugins || [],
      ...enableStepping ? [createYearlessDateSegmentsSteppingPlugin({ mode })] : []
    ]),
    preprocessors: [
      ...placeholderOptions.preprocessors,
      ...dateOptions.preprocessors,
      makeZeroShortcutPreprocessor(mode, separator)
    ],
    postprocessors: [
      ...dateOptions.postprocessors,
      ...placeholderOptions.postprocessors
    ]
  };
  const transform = (value) => {
    return maskitoTransform(value, datePlaceholderMask);
  };
  return { options: datePlaceholderMask, removePlaceholder, transform };
};

const YearlessDateInput = forwardRef(
  ({
    onChange,
    mode = "mm/dd",
    value,
    error,
    size,
    wrapperProps,
    rootProps,
    loading = false,
    enableStepping = false,
    className: classNameProp,
    ...restProps
  }, ref) => {
    const placeholder = "__/__";
    const [inputValue, setInputValue] = useState(placeholder);
    const { options, removePlaceholder, transform } = yearlessDatePlaceholderMask({
      mode,
      placeholder,
      enableStepping
    });
    const maskedInputRef = useMaskito({ options });
    const inputRef = useRef(null);
    const combinedRef = useMergeRefs([maskedInputRef, inputRef, ref]);
    const previousValue = usePrevious(value);
    const previousMode = usePrevious(mode);
    useEffect(() => {
      if (mode !== previousMode) {
        setInputValue(
          (oldInputValue) => swapMode(oldInputValue, previousMode ?? mode, mode)
        );
      }
    }, [mode, previousMode]);
    const triggerAutoChange = useCallback(
      (stringValue) => {
        const {
          value: v,
          isInputValid,
          isInputEmpty
        } = parseInputValue(stringValue, mode, removePlaceholder);
        onChange?.({
          event: null,
          value: v,
          isInputValid,
          isInputEmpty
        });
      },
      [mode, removePlaceholder, onChange]
    );
    useEffect(() => {
      if (previousValue?.day !== value?.day || previousValue?.month !== value?.month) {
        if (value?.day && value?.month) {
          const stringValue = stringifyYearlessDate(
            value.day,
            value.month,
            mode
          );
          const transformedValue = transform(stringValue);
          setInputValue(transformedValue);
          if (transformedValue !== stringValue) {
            triggerAutoChange(transformedValue);
          }
        } else if (previousValue !== null && previousValue !== void 0 && (value === null || value?.day === null && value?.month === null)) {
          setInputValue(placeholder);
        } else {
          return;
        }
      }
    }, [value, mode, previousValue, transform, triggerAutoChange]);
    const currentParsedData = useMemo(() => {
      return parseInputValue(inputValue, mode, removePlaceholder);
    }, [inputValue, mode, removePlaceholder]);
    const handleChange = (event) => {
      setInputValue(event.target.value);
      const {
        value: v,
        isInputValid,
        isInputEmpty
      } = parseInputValue(event.target.value, mode, removePlaceholder);
      const isDateDifferent = v === null !== (currentParsedData.value === null) || v?.day !== currentParsedData.value?.day || v?.month !== currentParsedData.value?.month;
      if (!isDateDifferent) {
        return;
      }
      onChange?.({
        event,
        value: v ?? currentParsedData.value ?? null,
        isInputValid,
        isInputEmpty
      });
    };
    useImperativeHandle(ref, () => {
      const input = inputRef.current;
      if (!input) return null;
      return Object.assign(input, {
        setValue: (value2) => {
          if (!value2) {
            setInputValue(placeholder);
            return parseInputValue(placeholder, mode, removePlaceholder);
          }
          const valueAsString = stringifyYearlessDate(
            value2.day ?? null,
            value2.month ?? null,
            mode
          );
          const transformedValue = transform(valueAsString);
          setInputValue(transformedValue);
          return parseInputValue(transformedValue, mode, removePlaceholder);
        },
        removePlaceholder
      });
    }, [mode, placeholder, removePlaceholder, transform]);
    return /* @__PURE__ */ jsx(
      "div",
      {
        className: cx(textFieldStyles["textfield"]),
        "data-anv": "yearless-date-input",
        ...rootProps,
        children: /* @__PURE__ */ jsxs(
          "div",
          {
            ...wrapperProps,
            className: cx(
              textFieldStyles["input-wrapper"],
              wrapperProps?.className,
              {
                [textFieldStyles["small"]]: size === "small",
                [textFieldStyles["large"]]: size === "large",
                [dateFieldYearlessStyles["small"]]: size === "small",
                [dateFieldYearlessStyles["large"]]: size === "large"
              }
            ),
            children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  ...restProps,
                  ref: combinedRef,
                  "data-month-value": value?.month,
                  "data-day-value": value?.day,
                  "data-input-valid": currentParsedData.isInputValid,
                  "data-input-empty": currentParsedData.isInputEmpty,
                  value: inputValue,
                  onChange: handleChange,
                  type: "text",
                  className: cx(
                    textFieldStyles["input"],
                    dateFieldYearlessStyles["input"],
                    {
                      [textFieldStyles["error"]]: error ?? false
                    },
                    classNameProp
                  )
                }
              ),
              loading ? /* @__PURE__ */ jsx("div", { className: textFieldStyles["loading-spinner-wrapper"], children: /* @__PURE__ */ jsx(Spinner, {}) }) : null
            ]
          }
        )
      }
    );
  }
);
YearlessDateInput.displayName = "YearlessDateInput";

const YearlessDateInputWithPicker = forwardRef((props, ref) => {
  const {
    value: valueProp,
    defaultValue: defaultValueProp,
    onChange: onChangeProp,
    minDate,
    maxDate,
    unavailable,
    required,
    disablePicker = false,
    mode = "mm/dd",
    size = "medium",
    error = false,
    loading = false,
    onFocus: onFocusProp,
    onBlur: onBlurProp,
    ...restProps
  } = props;
  const inputRef = useRef(null);
  const popoverRef = useRef(null);
  const popoverContentRef = useRef(null);
  const [value, setValue] = useOptionallyControlledState({
    controlledValue: valueProp,
    defaultValue: defaultValueProp
  });
  const [tempPickerValue, setTempPickerValue] = useState(
    value
  );
  useImperativeHandle(
    ref,
    () => ({
      focus: () => {
        if (!inputRef.current) return;
        return inputRef.current.focus();
      },
      setValue: (value2) => {
        if (!inputRef.current) return;
        inputRef.current.setValue(value2);
      }
    }),
    [inputRef]
  );
  const currentValidity = useMemo(
    () => validateYearlessDate({
      value: value ?? null,
      constraints: {
        required,
        unavailable,
        minDate,
        maxDate
      }
    }),
    [value, required, unavailable, minDate, maxDate]
  );
  const handleInputChange = (change) => {
    const { event, value: value2, ...restChange } = change;
    setValue(value2);
    setTempPickerValue(value2);
    onChangeProp?.({
      ...restChange,
      value: value2,
      isValid: validateYearlessDate({
        value: value2,
        constraints: {
          required,
          unavailable,
          minDate,
          maxDate
        }
      })
    });
  };
  const inputProps = {
    required,
    mode,
    autoComplete: "off",
    ...restProps,
    value,
    onChange: handleInputChange,
    "data-valid": currentValidity,
    size,
    error,
    loading
  };
  const { props: focusWithinProps } = useFocusWithin({
    onFocus: (e) => {
      requestAnimationFrame(() => {
        onFocusProp?.(e);
      });
    },
    onBlur: (e) => {
      requestAnimationFrame(() => {
        onBlurProp?.(e);
      });
      popoverRef.current?.closePopover();
    },
    otherRelatedElements: popoverContentRef?.current ? [popoverContentRef.current] : []
  });
  if (disablePicker) {
    return /* @__PURE__ */ jsx(YearlessDateInput, { ref: inputRef, ...inputProps });
  }
  const handlePickerChange = (newValue) => {
    setTempPickerValue(newValue);
    if (!inputRef.current) return;
    if (mode === "mm/dd" && newValue.month || mode === "dd/mm" && newValue.day) {
      const valueSet = inputRef.current.setValue(newValue);
      setValue(valueSet.value);
      onChangeProp?.({
        ...valueSet,
        isValid: validateYearlessDate({
          value: valueSet.value,
          constraints: {
            required,
            unavailable,
            minDate,
            maxDate
          }
        })
      });
    }
  };
  const handlePickerMonthChange = (month) => {
    handlePickerChange({
      day: value?.day ?? tempPickerValue?.day ?? null,
      month
    });
  };
  const handlePickerDayChange = (day) => {
    handlePickerChange({
      day,
      month: value?.month ?? tempPickerValue?.month ?? null
    });
  };
  const handlePickerClose = () => {
    setTempPickerValue(null);
  };
  const handleInputFocus = (event) => {
    focusWithinProps.onFocus?.(event);
  };
  const handleInputBlur = (event) => {
    focusWithinProps.onBlur?.(event);
  };
  const handlePopoverBlur = (event) => {
    focusWithinProps.onBlur?.(event);
  };
  return /* @__PURE__ */ jsx(
    YearlessDateSelectionPopover,
    {
      popoverRef,
      popoverContentRef,
      month: value?.month ?? tempPickerValue?.month ?? null,
      day: value?.day ?? tempPickerValue?.day ?? null,
      onMonthChange: handlePickerMonthChange,
      onDayChange: handlePickerDayChange,
      onClose: handlePickerClose,
      mode,
      onBlur: handlePopoverBlur,
      children: ({ ref: ref2, onKeyDown }) => /* @__PURE__ */ jsx(
        YearlessDateInput,
        {
          ...inputProps,
          ref: mergeRefs([
            inputRef,
            ref2
          ]),
          onKeyDown: (ev) => {
            onKeyDown?.(ev);
            inputProps.onKeyDown?.(ev);
          },
          onClick: (ev) => {
            inputProps.onClick?.(ev);
            popoverRef.current?.openPopover();
          },
          onFocus: handleInputFocus,
          onBlur: handleInputBlur,
          enableStepping: true
        }
      )
    }
  );
});
YearlessDateInputWithPicker.displayName = "YearlessDateInputWithPicker";

export { YearlessDateInputWithPicker as Y };
//# sourceMappingURL=YearlessDateInputWithPicker-DyytWt0x.js.map
