import { flip, size, useFloating, autoUpdate } from '@floating-ui/react';
import { useRef, useState, useEffect } from 'react';

const INDEX_WIDTH_CALCULATION = 100;
const WIDTH_MULTIPLIER = 7.3;
function estimateSize() {
  return 45;
}
const useComboboxFloat = (items, range, isOpen) => {
  var _a;
  const inputRef = useRef(null);
  const floatingRef = useRef(null);
  const [popoverWidth, setPopoverWidth] = useState(void 0);
  const [popoverMaxWidth, setPopoverMaxWidth] = useState(void 0);
  const middleware = [
    flip({
      // see https://floating-ui.com/docs/flip#combining-with-shift
      crossAxis: true,
      boundary: document.body
    }),
    size({
      apply({ availableWidth }) {
        setPopoverMaxWidth(availableWidth);
      }
    })
  ];
  const elements = { reference: inputRef.current, floating: floatingRef.current };
  const { floatingStyles } = useFloating({
    strategy: "fixed",
    open: isOpen,
    placement: "bottom-start",
    middleware,
    elements,
    whileElementsMounted: autoUpdate
  });
  useEffect(() => {
    if (range === null) {
      return;
    }
    const startVisibleIndex = range == null ? void 0 : range.startIndex;
    const endVisibleIndex = range == null ? void 0 : range.endIndex;
    if (typeof startVisibleIndex === "undefined" || typeof endVisibleIndex === "undefined") {
      return;
    }
    if (startVisibleIndex === 0 || startVisibleIndex % INDEX_WIDTH_CALCULATION === 0 && startVisibleIndex >= INDEX_WIDTH_CALCULATION) {
      let maxLength = 0;
      const calculationEnd = Math.min(items.length, endVisibleIndex + INDEX_WIDTH_CALCULATION);
      for (let i = startVisibleIndex; i < calculationEnd; i++) {
        maxLength = Math.max(maxLength, items[i].label.length);
      }
      setPopoverWidth(maxLength * WIDTH_MULTIPLIER);
    } else if (endVisibleIndex % INDEX_WIDTH_CALCULATION === 0 && endVisibleIndex >= INDEX_WIDTH_CALCULATION) {
      let maxLength = 0;
      const calculationStart = Math.max(0, startVisibleIndex - INDEX_WIDTH_CALCULATION);
      for (let i = calculationStart; i < endVisibleIndex; i++) {
        maxLength = Math.max(maxLength, items[i].label.length);
      }
      setPopoverWidth(maxLength * WIDTH_MULTIPLIER);
    }
  }, [items, range, setPopoverWidth]);
  const floatStyles = {
    ...floatingStyles,
    width: popoverWidth,
    maxWidth: popoverMaxWidth,
    minWidth: (_a = inputRef.current) == null ? void 0 : _a.offsetWidth
  };
  return { inputRef, floatingRef, floatStyles };
};

export { estimateSize, useComboboxFloat };
//# sourceMappingURL=useComboboxFloat.js.map
