import { useEffect, useCallback, useRef } from 'react';
import useDrawerClickAway from './useDrawerClickAway';
const animationsFinished = drawerRef => {
  if (!drawerRef.current) {
    return [];
  }
  return drawerRef.current.getAnimations({
    subtree: true
  }).map(animation => animation.finished);
};
const useFocusDrawer = drawer => {
  const drawerRef = useDrawerClickAway(drawer);
  const closeButtonRef = useRef();
  const closeOnEscape = useCallback(event => {
    const key = event.which || event.keyCode;
    if (key === 27) {
      event.stopPropagation();
      drawer.toggle();
    }
  }, [drawer]);
  useEffect(() => {
    if (drawer.state === 'closed') return undefined;

    // Stop scrolling in background
    const {
      overflow
    } = window.document.body.style;
    window.document.body.style.overflow = 'hidden';

    // Add event listener so the modal closes on esc
    window.document.addEventListener('keyup', closeOnEscape);

    // Wait for animations to finish and then handle focus
    const previouslyActive = window.document.activeElement;
    Promise.all(animationsFinished(drawerRef)).then(() => {
      // Focus first focusable element
      closeButtonRef.current.focus();
    });
    return () => {
      window.document.body.style.overflow = overflow;
      window.document.removeEventListener('keyup', closeOnEscape);
      Promise.all(animationsFinished(drawerRef)).then(() => {
        // Focus back on the open button
        previouslyActive.focus();
      });
    };
  }, [drawer.state]);
  return [drawerRef, closeButtonRef];
};
export default useFocusDrawer;