import { jsx, jsxs } from 'react/jsx-runtime';
import * as React from 'react';
import { useState, useEffect, forwardRef, useRef, useMemo, useCallback, useImperativeHandle } from 'react';
import { i as maskitoTimeOptionsGenerator, a as maskitoWithPlaceholder, u as useMaskito } from './index.esm-C2ZhC_8d.js';
import { I as Icon } from './Icon-BMMbp40n.js';
import { T as TextField } from './TextField-CRDTnuUN.js';
import { c as cx } from './index-De1g9FRV.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { L as Listbox } from './Listbox-DDlxpVu9.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-CB_zHDbW.js';
import { u as useOptionallyControlledState } from './useOptionallyControlledState-DbDuos5L.js';
import { c as childrenToString } from './childrenToString-Bz9MqbHb.js';
import { useTrackingId } from './useTrackingId.js';
import { P as Popover } from './AiMark-B1-M3ZgP.js';

import './TimeField.css';const usePopoverCloseDelayWorkaround = (popoverOpen, delay = 300) => {
  const [shouldShowContent, setShouldShowContent] = useState(popoverOpen);
  useEffect(() => {
    if (!popoverOpen) {
      const timeout = setTimeout(() => {
        setShouldShowContent(false);
      }, delay);
      return () => clearTimeout(timeout);
    }
    setShouldShowContent(true);
  }, [popoverOpen, delay]);
  return shouldShowContent;
};

const SvgAccessTime = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "1em", height: "1em", viewBox: "0 0 24 24", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm-.22-13h-.06c-.4 0-.72.32-.72.72v4.72c0 .35.18.68.49.86l4.15 2.49c.34.2.78.1.98-.24a.71.71 0 0 0-.25-.99l-3.87-2.3V7.72c0-.4-.32-.72-.72-.72z" }));

const TIME_CONSTANTS = {
  /** Minutes in a full day (24 hours * 60 minutes) */
  MINUTES_IN_DAY: 1440,
  /** Maximum hour in 24-hour format */
  MAX_HOUR_24: 23,
  /** Maximum minute value */
  MAX_MINUTE: 59,
  /** Timeout in milliseconds for input debouncing */
  INPUT_DEBOUNCE_TIMEOUT: 100
};
const TIME_FORMAT_PLACEHOLDERS = {
  12: "––:–– ––",
  24: "––:––"
};
const CLOCK_ICON = SvgAccessTime;

function formatTimeString(hours, minutes, format) {
  if (hours === 24) {
    hours = 0;
  }
  if (format === 12) {
    let displayHours = hours;
    let period = "AM";
    if (hours === 0) {
      displayHours = 12;
    } else if (hours > 12) {
      displayHours = hours - 12;
      period = "PM";
    } else if (hours === 12) {
      period = "PM";
    }
    return `${displayHours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")} ${period}`;
  } else {
    return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}`;
  }
}

const MAX_HOUR = TIME_CONSTANTS.MAX_HOUR_24;
const MAX_MINUTE = TIME_CONSTANTS.MAX_MINUTE;
function getConstraintMinutes(min, max) {
  const minMinutes = min ? timeToMinutes(convertTimeFormat(min, 24)) : 0;
  const maxMinutes = max ? timeToMinutes(convertTimeFormat(max, 24)) : TIME_CONSTANTS.MINUTES_IN_DAY;
  return { minMinutes, maxMinutes };
}
function isWithinConstraints(timeMinutes, minMinutes, maxMinutes) {
  return timeMinutes >= minMinutes && timeMinutes <= maxMinutes;
}
const timeToMinutes = (timeStr) => {
  const match = timeStr.match(/^(\d{1,2}):(\d{2})(?:\s*(AM|PM))?$/i);
  if (!match) return 0;
  let hours = parseInt(match[1], 10);
  const minutes = parseInt(match[2], 10);
  const period = match[3]?.toUpperCase();
  if (minutes > MAX_MINUTE) return 0;
  if (period === "PM" && hours !== 12) {
    hours += 12;
  } else if (period === "AM" && hours === 12) {
    hours = 0;
  }
  if (hours > MAX_HOUR) return 0;
  return hours * 60 + minutes;
};
function convertTimeFormat(time, targetFormat) {
  if (!time) return time;
  const minutes = timeToMinutes(time);
  if (minutes === 0 && time !== "00:00" && time !== "12:00 AM") {
    return time;
  }
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  return formatTimeString(hours, mins, targetFormat);
}
function normalizePartialInput(value) {
  const cleanValue = value.replace(/[–_:]/g, "").replace(/\s+/g, "");
  if (/^\d{1,2}$/.test(cleanValue)) {
    const result = `${cleanValue}:00`;
    return result;
  } else if (/^\d{1,2}:\d{1}$/.test(cleanValue)) {
    const result = `${cleanValue}0`;
    return result;
  } else if (/^\d{4}$/.test(cleanValue)) {
    const result = `${cleanValue.slice(0, 2)}:${cleanValue.slice(2)}`;
    return result;
  } else if (/^\d{4}(AM|PM)$/i.test(cleanValue)) {
    const digits = cleanValue.slice(0, 4);
    const ampm = cleanValue.slice(4);
    const result = `${digits.slice(0, 2)}:${digits.slice(2)} ${ampm}`;
    return result;
  }
  return value;
}
function parse12HourFormat(normalizedValue, min, max) {
  const match = normalizedValue.match(/^(\d{1,2}):(\d{1,2})(?:\s*(AM|PM))?$/i);
  if (!match) return null;
  let hours = parseInt(match[1], 10);
  let minutes = parseInt(match[2], 10);
  const ampm = match[3]?.toUpperCase();
  if (minutes < 10 && normalizedValue.match(/^(\d{1,2}):(\d{1})$/)) {
    minutes *= 10;
  }
  if (ampm === "PM") {
    if (hours !== 12) {
      hours += 12;
    }
  } else if (ampm === "AM") {
    if (hours === 12) {
      hours = 0;
    }
  } else {
    if (hours === 12) {
      hours = 12;
    } else {
      if (min || max) {
        const amHours = hours;
        const pmHours = hours + 12;
        const { minMinutes, maxMinutes } = getConstraintMinutes(min, max);
        const amMinutes = amHours * 60 + minutes;
        const pmMinutes = pmHours * 60 + minutes;
        const amValid = isWithinConstraints(amMinutes, minMinutes, maxMinutes);
        const pmValid = isWithinConstraints(pmMinutes, minMinutes, maxMinutes);
        if (amValid && pmValid) ; else if (pmValid) {
          hours = pmHours;
        } else ;
      }
    }
  }
  return { hours, minutes };
}
function parse24HourFormat(normalizedValue) {
  const match = normalizedValue.match(/^(\d{1,2}):(\d{1,2})$/);
  if (!match) {
    return null;
  }
  const hours = parseInt(match[1], 10);
  let minutes = parseInt(match[2], 10);
  if (minutes < 10 && normalizedValue.match(/^(\d{1,2}):(\d{1})$/)) {
    minutes *= 10;
  }
  const result = { hours, minutes };
  return result;
}
function validate12HourConstraints(timeString, value, min, max) {
  if (!min && !max) return true;
  const originalHasAMPM = value.toUpperCase().includes("AM") || value.toUpperCase().includes("PM");
  if (!originalHasAMPM) {
    const timePart = timeString.replace(/\s*(AM|PM)$/i, "");
    const amTime = `${timePart} AM`;
    const pmTime = `${timePart} PM`;
    const amMinutes = timeToMinutes(convertTimeFormat(amTime, 24));
    const pmMinutes = timeToMinutes(convertTimeFormat(pmTime, 24));
    const { minMinutes, maxMinutes } = getConstraintMinutes(min, max);
    return isWithinConstraints(amMinutes, minMinutes, maxMinutes) || isWithinConstraints(pmMinutes, minMinutes, maxMinutes);
  } else {
    const timeMinutes = timeToMinutes(convertTimeFormat(timeString, 24));
    const { minMinutes, maxMinutes } = getConstraintMinutes(min, max);
    return isWithinConstraints(timeMinutes, minMinutes, maxMinutes);
  }
}
function validate24HourConstraints(timeString, min, max) {
  if (!min && !max) return true;
  const timeMinutes = timeToMinutes(timeString);
  const { minMinutes, maxMinutes } = getConstraintMinutes(min, max);
  if (isWithinConstraints(timeMinutes, minMinutes, maxMinutes)) {
    return true;
  }
  const hours = Math.floor(timeMinutes / 60);
  const minutes = timeMinutes % 60;
  if (minutes === 0) {
    for (let h = minMinutes; h <= maxMinutes; h += 60) {
      const potentialHour = Math.floor(h / 60);
      if (potentialHour.toString().startsWith(hours.toString())) {
        return true;
      }
    }
  }
  if (hours >= Math.floor(minMinutes / 60) && hours <= Math.floor(maxMinutes / 60)) {
    const hourMinutes = hours * 60;
    const hourMinMinutes = Math.max(minMinutes, hourMinutes);
    const hourMaxMinutes = Math.min(maxMinutes, hourMinutes + 59);
    for (let m = hourMinMinutes; m <= hourMaxMinutes; m++) {
      const potentialMinutes = m % 60;
      if (potentialMinutes.toString().startsWith(minutes.toString())) {
        return true;
      }
    }
  }
  return false;
}
function parseInputValue(value, format, removePlaceholder, min, max) {
  const valueMinusPlaceholder = removePlaceholder(value);
  if (valueMinusPlaceholder === "") {
    return {
      time: null,
      isInputValid: false,
      isInputEmpty: true
    };
  }
  const normalizedValue = normalizePartialInput(valueMinusPlaceholder);
  const parsed = format === 12 ? parse12HourFormat(normalizedValue, min, max) : parse24HourFormat(normalizedValue);
  if (!parsed) {
    return {
      time: null,
      isInputValid: false,
      isInputEmpty: false
    };
  }
  const { hours, minutes } = parsed;
  if (hours < 0 || hours > MAX_HOUR || minutes < 0 || minutes > MAX_MINUTE) {
    return {
      time: null,
      isInputValid: false,
      isInputEmpty: false
    };
  }
  const timeString = formatTimeString(hours, minutes, format);
  const isValid = format === 12 ? validate12HourConstraints(timeString, value, min, max) : validate24HourConstraints(timeString, min, max);
  if (!isValid) {
    return {
      time: null,
      isInputValid: false,
      isInputEmpty: false
    };
  }
  return {
    time: timeString,
    isInputValid: true,
    isInputEmpty: false
  };
}

function generateTimeOptions({
  step = 30,
  min,
  max,
  format
}) {
  const options = [];
  const minMinutes = min ? timeToMinutes(min) : 0;
  const maxMinutes = max ? timeToMinutes(max) : TIME_CONSTANTS.MINUTES_IN_DAY - 1;
  for (let minutes = 0; minutes < TIME_CONSTANTS.MINUTES_IN_DAY; minutes += step) {
    if (minutes < minMinutes || minutes > maxMinutes) {
      continue;
    }
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    options.push(formatTimeString(hours, mins, format));
  }
  return options;
}
function normalizeTimeString(str) {
  return str.replace(/[–_:]/g, "").replace(/\s+/g, "").toLowerCase();
}
function filterTimeOptions(options, userInput) {
  if (!userInput || userInput === TIME_FORMAT_PLACEHOLDERS[12] || userInput === TIME_FORMAT_PLACEHOLDERS[24]) {
    return options;
  }
  const normalizedInput = normalizeTimeString(userInput);
  const filtered = options.filter((option) => {
    const normalizedOption = normalizeTimeString(option);
    return normalizedOption.startsWith(normalizedInput);
  });
  return filtered;
}

function isTimeOnStep(time, step) {
  if (!step || step <= 0) return true;
  const totalMinutes = timeToMinutes(time);
  return totalMinutes % step === 0;
}
function isValidTime(time) {
  if (!time) return false;
  return timeToMinutes(time) > 0 || time === "00:00";
}
function isPartialInputPotentiallyValid(inputValue, format, min, max) {
  if (!min || !max) return false;
  const digits = inputValue.replace(/[^\d]/g, "");
  if (digits.length === 1) {
    const digit = parseInt(digits, 10);
    const minMinutes = timeToMinutes(min);
    const maxMinutes = timeToMinutes(max);
    for (let h = 0; h <= 23; h++) {
      const hourStr = h.toString().padStart(2, "0");
      const hourStrNoPad = h.toString();
      const startsWithDigit = hourStr.startsWith(digit.toString()) || hourStrNoPad.startsWith(digit.toString());
      if (!startsWithDigit) continue;
      if (format === 24) {
        const hourMinutes = h * 60;
        if (hourMinutes >= minMinutes && hourMinutes <= maxMinutes) {
          return true;
        }
      } else {
        if (h === 0) {
          if (digit === 1) {
            const midnightMinutes = 0;
            if (midnightMinutes >= minMinutes && midnightMinutes <= maxMinutes) {
              return true;
            }
          }
        } else if (h >= 1 && h <= 12) {
          const amHour24 = h === 12 ? 0 : h;
          const amMinutes = amHour24 * 60;
          if (amMinutes >= minMinutes && amMinutes <= maxMinutes) {
            return true;
          }
          const pmHour24 = h === 12 ? 12 : h + 12;
          const pmMinutes = pmHour24 * 60;
          if (pmMinutes >= minMinutes && pmMinutes <= maxMinutes) {
            return true;
          }
        }
      }
    }
  }
  return false;
}

function getNextFutureStep(time, step, format) {
  if (!step || step <= 0) return time;
  const totalMinutes = timeToMinutes(time);
  const nextStep = Math.ceil(totalMinutes / step) * step;
  const hours = Math.floor(nextStep / 60);
  const minutes = nextStep % 60;
  return formatTimeString(hours, minutes, format);
}
function handleAutoRounding(time, options) {
  const { autoround, step, format } = options;
  if (!autoround || !time) return time;
  const stepValue = step ?? 30;
  if (isTimeOnStep(time, stepValue)) {
    return time;
  }
  return getNextFutureStep(time, stepValue, format);
}
function generateAmPmVariants(currentTime, step, inputValue) {
  const hasAM = inputValue.toUpperCase().includes("AM");
  const hasPM = inputValue.toUpperCase().includes("PM");
  const getNextStepForTime = (time) => {
    const currentMinutes = timeToMinutes(time);
    const nextStepMinutes = Math.ceil(currentMinutes / step) * step;
    const finalMinutes = nextStepMinutes === currentMinutes ? nextStepMinutes + step : nextStepMinutes;
    const hours = Math.floor(finalMinutes / 60);
    const minutes = finalMinutes % 60;
    return formatTimeString(hours, minutes, 12);
  };
  const nextStep = getNextFutureStep(currentTime, step, 12);
  if (hasAM || hasPM) {
    return [nextStep];
  } else {
    const currentMinutes = timeToMinutes(currentTime);
    const pmMinutes = currentMinutes + 12 * 60;
    const pmHours = Math.floor(pmMinutes / 60);
    const pmMins = pmMinutes % 60;
    const pmVersion = getNextStepForTime(formatTimeString(pmHours, pmMins, 24));
    return [nextStep, pmVersion];
  }
}
function generatePmInterpretation(currentTime, step, inputValue) {
  if (inputValue.toUpperCase().includes("AM") || inputValue.toUpperCase().includes("PM")) {
    return [];
  }
  const currentMinutes = timeToMinutes(currentTime);
  const pmMinutes = currentMinutes + 12 * 60;
  const pmHours = Math.floor(pmMinutes / 60);
  const pmMins = pmMinutes % 60;
  const pmTime = formatTimeString(pmHours, pmMins, 12);
  if (isValidTime(pmTime)) {
    const pmNextStep = getNextFutureStep(pmTime, step, 12);
    return [pmNextStep];
  }
  return [];
}
function getAutoRoundingOptions(currentTime, step, format, inputValue, min) {
  if (!currentTime) {
    return [];
  }
  if (!isValidTime(currentTime)) {
    if (format === 12) {
      return generatePmInterpretation(currentTime, step, inputValue);
    }
    return [];
  }
  const nextStep = getNextFutureStep(currentTime, step, format);
  if (format === 12 && !min) {
    return generateAmPmVariants(currentTime, step, inputValue);
  }
  return [nextStep];
}

const timePlaceholderMask = ({
  format,
  placeholder
}) => {
  const timeOptions = maskitoTimeOptionsGenerator({
    mode: format === 12 ? "HH:MM AA" : "HH:MM",
    step: 0
    // We handle step logic in your business layer
  });
  const { plugins, removePlaceholder, ...placeholderOptions } = maskitoWithPlaceholder(placeholder);
  const timePlaceholderMask2 = {
    ...timeOptions,
    plugins: plugins.concat(timeOptions.plugins || []),
    preprocessors: [
      ...placeholderOptions.preprocessors,
      ...timeOptions.preprocessors
    ],
    postprocessors: [
      ...timeOptions.postprocessors,
      ...placeholderOptions.postprocessors
    ]
  };
  return { options: timePlaceholderMask2, removePlaceholder };
};

const styles = {
	"time-field": "_time-field_1el61_1"
};

const MaskedTimeInput = forwardRef(
  ({
    selectedTime,
    format,
    placeholder,
    min,
    max,
    onInputChange,
    onKeyDown,
    onFocus,
    onBlur,
    className,
    ...props
  }, ref) => {
    const [inputValue, setInputValue] = useState(placeholder);
    const { options, removePlaceholder } = timePlaceholderMask({
      format,
      placeholder
    });
    const maskedInputRef = useMaskito({ options });
    const inputRef = useRef(null);
    const combinedRef = useMergeRefs([maskedInputRef, inputRef, ref]);
    const isUserTypingRef = useRef(false);
    const inputValueRef = useRef(placeholder);
    const previousPlaceholderRef = useRef(placeholder);
    const currentParsedData = useMemo(() => {
      return parseInputValue(inputValue, format, removePlaceholder, min, max);
    }, [inputValue, format, removePlaceholder, min, max]);
    useEffect(() => {
      inputValueRef.current = inputValue;
    }, [inputValue]);
    useEffect(() => {
      previousPlaceholderRef.current = placeholder;
    }, [placeholder]);
    useEffect(() => {
      if (selectedTime !== void 0 && !isUserTypingRef.current) {
        const newInputValue = selectedTime ? convertTimeFormat(selectedTime, format) : placeholder;
        setInputValue(newInputValue);
        inputValueRef.current = newInputValue;
      }
    }, [selectedTime, format, placeholder]);
    useEffect(() => {
      if (placeholder === previousPlaceholderRef.current) return;
      const isOldPlaceholder = inputValue === TIME_FORMAT_PLACEHOLDERS[12] || inputValue === TIME_FORMAT_PLACEHOLDERS[24];
      if (isOldPlaceholder) {
        setInputValue(placeholder);
      }
      previousPlaceholderRef.current = placeholder;
    }, [placeholder, inputValue]);
    const handleChange = useCallback(
      (event) => {
        isUserTypingRef.current = true;
        const { time, isInputValid, isInputEmpty } = parseInputValue(
          event.target.value,
          format,
          removePlaceholder,
          min,
          max
        );
        const isPotentiallyValidPartial = !isInputValid && !isInputEmpty && event.target.value.length >= placeholder.length && // User is typing, not deleting
        isPartialInputPotentiallyValid(event.target.value, format, min, max);
        if (isInputValid || isInputEmpty || isPotentiallyValidPartial) {
          setInputValue(event.target.value);
        } else {
          setInputValue(placeholder);
        }
        onInputChange?.({
          event,
          time,
          isInputValid,
          isInputEmpty
        });
        setTimeout(() => {
          isUserTypingRef.current = false;
        }, TIME_CONSTANTS.INPUT_DEBOUNCE_TIMEOUT);
      },
      [format, removePlaceholder, onInputChange, min, max, placeholder]
    );
    const resetTypingFlag = useCallback(() => {
      isUserTypingRef.current = false;
    }, []);
    const handleBlur = useCallback(
      (event) => {
        if (currentParsedData.time && currentParsedData.isInputValid) {
          const completedValue = convertTimeFormat(
            currentParsedData.time,
            format
          );
          setInputValue(completedValue);
        }
        onBlur?.(event);
      },
      [currentParsedData, format, onBlur]
    );
    useImperativeHandle(ref, () => {
      const input = inputRef.current;
      if (!input)
        return null;
      return Object.assign(input, {
        resetTypingFlag
      });
    });
    const classNames = useMemo(() => {
      return cx(styles["time-field"], className);
    }, [className]);
    return /* @__PURE__ */ jsx(
      TextField,
      {
        ref: combinedRef,
        "data-input-valid": currentParsedData.isInputValid,
        "data-input-empty": currentParsedData.isInputEmpty,
        "data-time": currentParsedData.time ?? "",
        value: inputValue,
        onChange: handleChange,
        prefix: /* @__PURE__ */ jsx(Icon, { svg: CLOCK_ICON }),
        autoComplete: "off",
        onKeyDown,
        onFocus,
        onBlur: handleBlur,
        className: classNames,
        ...props
      }
    );
  }
);
MaskedTimeInput.displayName = "MaskedTimeInput";

const TimeField = (props) => {
  const { componentProps } = useLayoutPropsUtil(props);
  const {
    label,
    labelProps,
    size,
    value: valueProp,
    defaultValue,
    min,
    max,
    onChange,
    format = 12,
    step = 30,
    required,
    description,
    error: errorProp,
    disableSuggestions = false,
    autoround = false,
    className,
    ...rest
  } = componentProps;
  const [isDropdownOpen, setIsDropdownOpenRaw] = useState(false);
  const setIsDropdownOpen = (open) => {
    setIsDropdownOpenRaw(open);
  };
  const [selectedOptionIndex, setSelectedOptionIndex] = useState(0);
  const [inputValueForFiltering, setInputValueForFiltering] = useState("");
  const [currentParsedTime, setCurrentParsedTime] = useState(
    null
  );
  const [selectedTime, setSelectedTime] = useOptionallyControlledState({
    controlledValue: valueProp,
    defaultValue: defaultValue ?? null
  });
  const [inputParsedData, setInputParsedData] = useState({ time: null, isInputValid: false, isInputEmpty: true });
  const lastOnChangeCallRef = useRef(null);
  const isDropdownClickingRef = useRef(false);
  const [justSelected, setJustSelected] = useState(false);
  const tabJustPressedRef = useRef(false);
  const closeJustTriggeredRef = useRef(false);
  const inputRef = useRef(null);
  const popoverContentRef = useRef(null);
  const popoverRefSetter = useRef(
    null
  );
  const popoverCallbackRef = useCallback((node) => {
    popoverRefSetter.current?.(node);
  }, []);
  const combinedRef = useMergeRefs([popoverCallbackRef, inputRef]);
  const placeholder = TIME_FORMAT_PLACEHOLDERS[format];
  const shouldShowOptionsFromHook = usePopoverCloseDelayWorkaround(isDropdownOpen);
  const shouldShowOptions = tabJustPressedRef.current ? false : shouldShowOptionsFromHook;
  const dropdownTimeoutRef = useRef(null);
  useEffect(() => {
    const dropdownRef = dropdownTimeoutRef.current;
    return () => {
      if (dropdownRef) {
        clearTimeout(dropdownRef);
      }
    };
  }, []);
  const allTimeOptions = useMemo(
    () => generateTimeOptions({ step, min, max, format }),
    [step, min, max, format]
  );
  const baseFilteredOptions = useMemo(() => {
    if (!inputValueForFiltering || inputValueForFiltering.match(/^[–_:]+$/)) {
      return allTimeOptions;
    }
    return filterTimeOptions(allTimeOptions, inputValueForFiltering);
  }, [allTimeOptions, inputValueForFiltering]);
  const autoRoundingOptions = useMemo(() => {
    if (!autoround || baseFilteredOptions.length > 0 || !inputValueForFiltering || inputValueForFiltering.match(/^[–_:]+$/)) {
      return [];
    }
    const currentTime = currentParsedTime || inputParsedData.time;
    const autoRoundedOptions = getAutoRoundingOptions(
      currentTime,
      step ?? 30,
      format,
      inputValueForFiltering,
      min
    );
    return autoRoundedOptions.filter(
      (option) => !baseFilteredOptions.includes(option)
    );
  }, [
    autoround,
    baseFilteredOptions,
    inputValueForFiltering,
    currentParsedTime,
    inputParsedData.time,
    format,
    min,
    step
  ]);
  const filteredOptions = useMemo(() => {
    if (baseFilteredOptions.length === 0 && autoRoundingOptions.length === 0) {
      if (!inputParsedData.isInputValid && inputValueForFiltering && !inputValueForFiltering.match(/^[–_:]+$/)) {
        return allTimeOptions;
      }
    }
    return [...baseFilteredOptions, ...autoRoundingOptions];
  }, [
    baseFilteredOptions,
    autoRoundingOptions,
    allTimeOptions,
    inputValueForFiltering,
    inputParsedData.isInputValid
  ]);
  const handleBlur = useCallback(
    (event) => {
      if (event.relatedTarget && popoverContentRef.current?.contains(event.relatedTarget) && isDropdownClickingRef.current) {
        isDropdownClickingRef.current = false;
        return;
      }
      setIsDropdownOpen(false);
      setSelectedOptionIndex(0);
      const input = event.target;
      const parsedInputTime = input.dataset.time || null;
      const isInputValid = input.dataset.inputValid === "true";
      const isInputEmpty = input.dataset.inputEmpty === "true";
      let finalTime = parsedInputTime;
      if (autoround && finalTime && isInputValid) {
        const beforeRounding = finalTime;
        finalTime = handleAutoRounding(finalTime, {
          autoround,
          step,
          format
        });
        if (finalTime !== beforeRounding) {
          inputRef.current?.resetTypingFlag?.();
          setSelectedTime(finalTime);
        }
      }
      const currentChange = {
        time: finalTime,
        isInputValid,
        isInputEmpty
      };
      const lastChange = lastOnChangeCallRef.current;
      const isDuplicate = lastChange && lastChange.time === currentChange.time && lastChange.isInputValid === currentChange.isInputValid && lastChange.isInputEmpty === currentChange.isInputEmpty;
      if (!isDuplicate) {
        onChange?.(currentChange);
        lastOnChangeCallRef.current = currentChange;
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [format, step, autoround, onChange]
  );
  const handleFocus = useCallback(() => {
    if (!disableSuggestions && !justSelected) {
      setIsDropdownOpen(true);
      setSelectedOptionIndex(0);
    }
  }, [disableSuggestions, justSelected]);
  useEffect(() => {
    if (filteredOptions.length <= 1 && isDropdownOpen) {
      setIsDropdownOpen(false);
    }
    if (!disableSuggestions && filteredOptions.length > 1 && document.activeElement && document.activeElement.tagName === "INPUT" && !isDropdownOpen && !justSelected && !tabJustPressedRef.current && !closeJustTriggeredRef.current) {
      setIsDropdownOpen(true);
      setSelectedOptionIndex(0);
    }
  }, [filteredOptions, disableSuggestions, isDropdownOpen, justSelected]);
  const handleInputChange = (change) => {
    setInputValueForFiltering(change.event.target.value);
    setCurrentParsedTime(change.time);
    setInputParsedData({
      time: change.time,
      isInputValid: change.isInputValid,
      isInputEmpty: change.isInputEmpty
    });
    setSelectedOptionIndex(0);
    setJustSelected(false);
    setSelectedTime(null);
  };
  const scrollToSelectedOption = useCallback(() => {
    if (!popoverContentRef.current || selectedOptionIndex < 0) return;
    const optionElements = popoverContentRef.current.querySelectorAll('[role="option"]');
    const targetElement = optionElements[selectedOptionIndex];
    if (targetElement) {
      targetElement.scrollIntoView({
        block: "nearest",
        behavior: "auto"
      });
    }
  }, [selectedOptionIndex]);
  useEffect(() => {
    if (isDropdownOpen && selectedOptionIndex >= 0) {
      scrollToSelectedOption();
    }
  }, [selectedOptionIndex, isDropdownOpen, scrollToSelectedOption]);
  const handleOptionSelect = useCallback(
    (selectedTime2) => {
      if (inputRef.current?.resetTypingFlag) {
        inputRef.current.resetTypingFlag();
      }
      setIsDropdownOpen(false);
      setSelectedOptionIndex(0);
      setJustSelected(true);
      setCurrentParsedTime(selectedTime2);
      setSelectedTime(selectedTime2);
      const changeData = {
        time: selectedTime2,
        isInputValid: true,
        isInputEmpty: false
      };
      onChange?.(changeData);
      lastOnChangeCallRef.current = changeData;
      requestAnimationFrame(() => {
        inputRef.current?.focus();
      });
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [onChange]
  );
  const handleKeyDown = useCallback(
    (event) => {
      if (!isDropdownOpen) {
        return;
      }
      switch (event.key) {
        case "ArrowDown":
          event.preventDefault();
          setSelectedOptionIndex(
            (prev) => prev < filteredOptions.length - 1 ? prev + 1 : 0
          );
          break;
        case "ArrowUp":
          event.preventDefault();
          setSelectedOptionIndex(
            (prev) => prev > 0 ? prev - 1 : filteredOptions.length - 1
          );
          break;
        case "Enter":
          event.preventDefault();
          if (filteredOptions[selectedOptionIndex]) {
            handleOptionSelect(filteredOptions[selectedOptionIndex]);
          }
          break;
        case "Tab":
          tabJustPressedRef.current = true;
          setIsDropdownOpen(false);
          setSelectedOptionIndex(0);
          setTimeout(() => {
            tabJustPressedRef.current = false;
          }, 50);
          break;
      }
    },
    [isDropdownOpen, selectedOptionIndex, filteredOptions, handleOptionSelect]
  );
  const popoverDisabled = disableSuggestions;
  const { aiMark, ...labelPropsWithoutAiMark } = labelProps || {};
  const data = {
    label: childrenToString(label),
    labelProps: labelPropsWithoutAiMark,
    description: childrenToString(description),
    size,
    format,
    step,
    min,
    max,
    autoround,
    disableSuggestions
  };
  const trackingId = useTrackingId({
    name: "TimeField",
    data,
    hasOverride: !!rest["data-tracking-id"]
  });
  const justTheInput = /* @__PURE__ */ jsx(
    MaskedTimeInput,
    {
      "data-tracking-id": trackingId,
      ref: combinedRef,
      selectedTime,
      format,
      placeholder,
      min,
      max,
      onInputChange: handleInputChange,
      onKeyDown: handleKeyDown,
      onBlur: handleBlur,
      onFocus: handleFocus,
      label,
      labelProps,
      size,
      description,
      error: errorProp,
      className: popoverDisabled ? className : void 0,
      ...rest,
      "aria-label": label ? void 0 : "Select a time",
      "data-anv": "time-field"
    }
  );
  if (popoverDisabled) {
    return justTheInput;
  }
  return /* @__PURE__ */ jsxs(
    Popover,
    {
      open: isDropdownOpen,
      role: "listbox",
      noPadding: true,
      placement: "bottom-start",
      matchReferenceWidth: true,
      onClickOutside: () => {
        setIsDropdownOpen(false);
      },
      onClose: () => {
        closeJustTriggeredRef.current = true;
        setIsDropdownOpen(false);
        setTimeout(() => {
          closeJustTriggeredRef.current = false;
        }, 50);
      },
      fitScreen: true,
      maxHeight: 205,
      children: [
        /* @__PURE__ */ jsx(Popover.Trigger, { children: ({ ref: setReference }) => {
          popoverRefSetter.current = setReference;
          return justTheInput;
        } }),
        /* @__PURE__ */ jsx(
          Popover.Content,
          {
            ref: popoverContentRef,
            "data-open": isDropdownOpen,
            "data-disabled": disableSuggestions,
            onMouseDown: () => {
              isDropdownClickingRef.current = true;
            },
            onTouchStart: () => {
              isDropdownClickingRef.current = true;
            },
            children: shouldShowOptions && /* @__PURE__ */ jsx(
              Listbox,
              {
                selected: filteredOptions[selectedOptionIndex],
                onSelectionChange: (selected) => {
                  if (selected) {
                    handleOptionSelect(selected);
                  } else {
                    const currentOption = filteredOptions[selectedOptionIndex];
                    if (currentOption) {
                      handleOptionSelect(currentOption);
                    }
                  }
                },
                "aria-label": "Time suggestions",
                children: filteredOptions.map((option) => /* @__PURE__ */ jsx(Listbox.Option, { value: option, label: option, children: option }, option))
              }
            )
          }
        )
      ]
    }
  );
};
TimeField.displayName = "TimeField";

export { TimeField as T };
//# sourceMappingURL=TimeField-DTg0CE5L.js.map
