// Copyright 1999-2025. WebPros International GmbH. All rights reserved.

import { useRef, useLayoutEffect, useState } from 'react';
import { useResizeObserver } from './useResizeObserver';
import { useMutationObserver } from './useMutationObserver';
const MUTATION_OBSERVER_OPTIONS = {
  subtree: true,
  childList: true,
  characterData: true
};
export const useSqueeze = _ref => {
  let {
    ref,
    compact,
    expand
  } = _ref;
  const minWidth = useRef(0);
  const lastAction = useRef(null);
  const [recheck, setRecheck] = useState(false);
  const checkRef = useRef();
  const check = () => {
    if (!ref.current) return;
    const root = ref.current;
    const width = Math.ceil(root.getBoundingClientRect().width);
    const {
      scrollWidth
    } = root;
    let isCompactChanged = false;
    if (scrollWidth > width) {
      isCompactChanged = compact();
      minWidth.current = scrollWidth;
      lastAction.current = 'compact';
    } else if (minWidth.current && width > minWidth.current || lastAction.current === 'expand') {
      isCompactChanged = expand();
      lastAction.current = 'expand';
    }
    if (isCompactChanged) {
      setRecheck(c => !c);
    }
  };
  checkRef.current = check;
  useLayoutEffect(() => {
    checkRef.current?.();
  }, [recheck]);
  useResizeObserver({
    ref,
    onResize: check
  });
  useMutationObserver({
    ref,
    onMutate: check,
    options: MUTATION_OBSERVER_OPTIONS
  });
};