(function ($) {
  'use strict';

  $(function () {
    function syncMobileState() {
      $('body').toggleClass('sidebar-mobile-open', window.innerWidth <= 768 && $('#accordionSidebar').hasClass('toggled'));
    }
    $('#sidebarToggleTop').on('click', syncMobileState);
    $(window).on('resize', syncMobileState);
    syncMobileState();

    $(document).on('click', function (event) {
      if (window.innerWidth <= 768 && document.body.classList.contains('sidebar-mobile-open') &&
          !$(event.target).closest('#accordionSidebar, #sidebarToggleTop').length) {
        $('#sidebarToggleTop').trigger('click');
      }
    });

    $(document).on('keydown', function (event) {
      if (event.key === 'Escape') {
        if (window.innerWidth <= 768 && document.body.classList.contains('sidebar-mobile-open')) $('#sidebarToggleTop').trigger('click');
        if ($('#sidebar').hasClass('active')) $('#dismiss').trigger('click');
      }
    });
  });
})(jQuery);
