(function ($) {

  'use strict';

  Drupal.behaviors.responsive_menu = {
    attach: function (context, settings) {

      $('body', context).once('responsive-menu', function() {

        const mmenuId = '#off-canvas';

        if (typeof(Mmenu) !== "undefined") {

          // Get variables from Drupal settings to be used in configuring the menu.
          var position = Drupal.settings.responsive_menu.position;
          var theme = Drupal.settings.responsive_menu.theme;
          var drag = Drupal.settings.responsive_menu.drag;

          // Set up the off canvas menu.
          var options = {
            extensions: [
              theme,
              'fx-menu-slide',
              'pagedim-black',
              position === 'left' ? 'position-left' : 'position-right'
            ],
            drag: drag,
            keyboardNavigation: {
              enable: true,
              enhance: true,
            },
          }

          var config = {
            clone: false,
            classNames: {
              selected: 'active'
            }
          }

          // Allow the settings and options to be extended or overridden.
          if (typeof Drupal.settings.responsive_menu.custom !== 'undefined') {
            if (typeof Drupal.settings.responsive_menu.custom.options !== 'undefined') {
              $.extend(options, Drupal.settings.responsive_menu.custom.options);
            }
            if (typeof Drupal.settings.responsive_menu.custom.config !== 'undefined') {
              $.extend(config, Drupal.settings.responsive_menu.custom.config);
            }
          }

          // Set up the off canvas menu.
          var mmenu = new Mmenu(mmenuId, options, config);
        }


        // Apply the superfish library to the menu.
        if ($.fn.superfish) {
          // Get the superfish settings.
          var superfishDelay = Drupal.settings.responsive_menu.superfish.delay,
            superfishSpeed = Drupal.settings.responsive_menu.superfish.speed,
            superfishSpeedOut = Drupal.settings.responsive_menu.superfish.speedOut;
          // Attach superfish to the responsive menu.
          $('#horizontal-menu').superfish({
            delay: parseInt(superfishDelay, 10),
            speed: parseInt(superfishSpeed, 10),
            speedOut: parseInt(superfishSpeedOut, 10)
          }).addClass('sf-menu');
        }

      });
    }
  };

})(jQuery);
