// Menus
( function( window, document ) {
  const pr_agency_nav = document.getElementById( 'mySidenav' );
  const pr_agency_openBtn = document.querySelector( '.pr-agency-menu-toggle' );
  const pr_agency_closeBtn = document.querySelector( '.pr-agency-menu-close' );

  if ( ! pr_agency_nav ) {
    return;
  }

  function pr_agency_setExpanded( isExpanded ) {
    if ( pr_agency_openBtn ) {
      pr_agency_openBtn.setAttribute( 'aria-expanded', isExpanded ? 'true' : 'false' );
    }
  }

  function pr_agency_menu_open_nav() {
    pr_agency_nav.classList.add( 'show' );
    document.body.classList.add( 'mobilemenu-open' );
    pr_agency_setExpanded( true );
  }

  function pr_agency_menu_close_nav() {
    pr_agency_nav.classList.remove( 'show' );
    document.body.classList.remove( 'mobilemenu-open' );
    pr_agency_setExpanded( false );

    if ( pr_agency_openBtn ) {
      pr_agency_openBtn.focus();
    }
  }

  if ( pr_agency_openBtn ) {
    pr_agency_openBtn.addEventListener( 'click', pr_agency_menu_open_nav );
  }

  if ( pr_agency_closeBtn ) {
    pr_agency_closeBtn.addEventListener( 'click', pr_agency_menu_close_nav );
  }

  document.addEventListener( 'keydown', function( e ) {
    if ( e.key === 'Escape' && pr_agency_nav.classList.contains( 'show' ) ) {
      pr_agency_menu_close_nav();
    }
  } );

  function pr_agency_keepFocusInMenu() {
    document.addEventListener( 'keydown', function( e ) {
      if ( ! pr_agency_nav.classList.contains( 'show' ) ) {
        return;
      }

      const elements = [ ...pr_agency_nav.querySelectorAll( 'input, a, button' ) ].filter( function( element ) {
        return ! element.hasAttribute( 'disabled' );
      } );

      if ( ! elements.length ) {
        return;
      }

      const pr_agency_lastEl = elements[ elements.length - 1 ];
      const pr_agency_firstEl = elements[ 0 ];
      const pr_agency_activeEl = document.activeElement;
      const tabKey = e.key === 'Tab' || e.keyCode === 9;
      const shiftKey = e.shiftKey;

      if ( ! shiftKey && tabKey && pr_agency_lastEl === pr_agency_activeEl ) {
        e.preventDefault();
        pr_agency_firstEl.focus();
      }

      if ( shiftKey && tabKey && pr_agency_firstEl === pr_agency_activeEl ) {
        e.preventDefault();
        pr_agency_lastEl.focus();
      }
    } );
  }

  pr_agency_keepFocusInMenu();

  // Keep these names on window for backward compatibility with existing markup/plugins.
  window.pr_agency_menu_open_nav = pr_agency_menu_open_nav;
  window.pr_agency_menu_close_nav = pr_agency_menu_close_nav;
} )( window, document );