import { useEffect, useState, RefObject } from 'react';

/**
 * useCarouselMinHeight
 *
 * Locks a carousel container's minimum height to the tallest observed value while
 * `enabled` is true. Useful when a carousel temporarily shrinks (small-carousel mode)
 * and slide content wraps, causing per-slide height changes. When disabled, the
 * tracker resets so the layout returns to its natural size.
 */
export const useCarouselMinHeight = (
  ref: RefObject<HTMLElement>,
  baseMinHeight: number,
  enabled: boolean,
  observeKey: unknown,
): number => {
  const [maxObservedHeight, setMaxObservedHeight] = useState(0);

  useEffect(() => {
    if (!enabled) {
      setMaxObservedHeight(0);
      return;
    }

    setMaxObservedHeight(0);

    const node = ref.current;
    if (!node || typeof ResizeObserver === 'undefined') {
      return;
    }

    const observer = new ResizeObserver((entries) => {
      const entry = entries[0];
      if (!entry) {
        return;
      }

      const nextHeight = entry.contentRect.height;
      setMaxObservedHeight((prev) => (nextHeight > prev ? nextHeight : prev));
    });

    observer.observe(node);

    return () => observer.disconnect();
  }, [ref, enabled, observeKey]);

  return enabled ? Math.max(baseMinHeight, maxObservedHeight) : baseMinHeight;
};

export default useCarouselMinHeight;
