import { useEffect, useRef } from "react";

/**
 * Scrolls the highlighted option into view.
 * Supports both regular DOM containers and react-window FixedSizeList refs.
 */
export function useScrollIntoView({ highlightedIndex, containerRef, listRef, isVirtualized = false }) {
  const prevIndex = useRef(highlightedIndex);

  useEffect(() => {
    if (highlightedIndex < 0) return;
    if (highlightedIndex === prevIndex.current) return;
    prevIndex.current = highlightedIndex;

    if (isVirtualized && listRef?.current) {
      listRef.current.scrollToItem(highlightedIndex, "smart");
      return;
    }

    if (containerRef?.current) {
      const items = containerRef.current.querySelectorAll('[role="option"]');
      const target = items?.[highlightedIndex];
      if (target) {
        target.scrollIntoView({ block: "nearest", behavior: "smooth" });
      }
    }
  }, [highlightedIndex, containerRef, listRef, isVirtualized]);
}
