import { useState, useCallback, useRef } from "react";

const useSafeFocusState = () => {
  const [focusedItem, setFocusedItem] = useState(null);
  const blurTimeoutRef = useRef(null);

  const setFocusAsync = useCallback((item) => {
    return new Promise((resolve) => {
      if (blurTimeoutRef.current) {
        clearTimeout(blurTimeoutRef.current);
        blurTimeoutRef.current = null;
      }
      if (process.env.NODE_ENV === "development") {
        console.log("[useSafeFocusState] Focus Set:", item);
      }
      setFocusedItem(item);
      resolve(item);
    });
  }, []);

  const clearFocusAsync = useCallback((delay = 0) => {
    return new Promise((resolve) => {
      if (blurTimeoutRef.current) {
        clearTimeout(blurTimeoutRef.current);
      }
      blurTimeoutRef.current = setTimeout(() => {
        if (process.env.NODE_ENV === "development") {
          console.log("[useSafeFocusState] Focus Cleared");
        }
        setFocusedItem(null);
        blurTimeoutRef.current = null;
        resolve();
      }, delay);
    });
  }, []);

  return { focusedItem, setFocusAsync, clearFocusAsync };
};

export default useSafeFocusState; 