import { useMemo, useState } from 'react';

/**
 * Handles focus and blur events with React hooks to help make elements
 * accessible by programmatically managing focus. This ensures that all
 * functionality exposed through a mouse or pointer event can also be
 * accessed using the keyboard alone.
 *
 * @link https://reactjs.org/docs/accessibility.html#mouse-and-pointer-events
 * @param initialState
 * @returns
 */
const useToggleOnFocus = (initialState = false) => {
  const [currentState, toggleState] = useState(initialState);

  const eventHandlers = useMemo(() => {
    let timeoutId: ReturnType<typeof setTimeout>;
    return {
      onFocus: (event?: Event) => {
        clearTimeout(timeoutId);
        toggleState(true);
      },
      onBlur: (event?: Event) => {
        timeoutId = setTimeout(() => toggleState(false));
      }
    };
  }, []);

  return { currentState, eventHandlers, toggleState };
};

export default useToggleOnFocus;
