import { useCallback, useRef } from "react";

const TYPEAHEAD_TIMEOUT = 500;

/**
 * Typeahead: accumulates typed characters within a short window
 * and moves highlight to the first matching option.
 * Only for non-searchable dropdowns or when focus is on the listbox.
 */
export function useTypeahead({ options = [], setHighlightedIndex, isActive = true }) {
  const bufferRef = useRef("");
  const timerRef = useRef(null);

  const handleTypeahead = useCallback(
    (e) => {
      if (!isActive) return false;
      // Only handle single printable characters (not modifier combos)
      if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey) return false;

      e.preventDefault();

      bufferRef.current += e.key.toLowerCase();

      if (timerRef.current) clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => {
        bufferRef.current = "";
      }, TYPEAHEAD_TIMEOUT);

      const matchIndex = options.findIndex((opt) =>
        (opt.label || "").toLowerCase().startsWith(bufferRef.current)
      );

      if (matchIndex >= 0) {
        setHighlightedIndex(matchIndex);
      }

      return true; // signal that we consumed the event
    },
    [options, setHighlightedIndex, isActive]
  );

  const resetBuffer = useCallback(() => {
    bufferRef.current = "";
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  return { handleTypeahead, resetBuffer };
}
