import { useCallback, useRef } from 'react';

export default function useFocusMemory(
  onFocus: () => void,
  onBlur: () => void
) {
  const windowMouseDownListenerRef = useRef<(() => void) | null>(null);

  const focus = useCallback(() => {
    onFocus();

    if (windowMouseDownListenerRef.current) {
      window.removeEventListener(
        'mousedown',
        windowMouseDownListenerRef.current
      );
      windowMouseDownListenerRef.current = null;
    }

    const handleWindowMouseDown = () => {
      onBlur();
      window.removeEventListener('mousedown', handleWindowMouseDown);
    };

    const handleWindowMouseUp = () => {
      windowMouseDownListenerRef.current = handleWindowMouseDown;
      window.addEventListener('mousedown', handleWindowMouseDown);
      window.removeEventListener('mouseup', handleWindowMouseUp);
    };

    window.addEventListener('mouseup', handleWindowMouseUp);
  }, []);

  return focus;
}
