(function ($, Drupal) {

  Drupal.behaviors.pagedesigner_layouts_init_components = {
    attach: function (context, settings) {
      once('pagedesigner_layouts_init_components', 'body', context).forEach(() => {
        $(document).on('pagedesigner-init-components', function (e, editor) {
          init(editor);
        });
      });
    }
  };

  function init(editor) {

    // add layout button to toolbar
    editor.DomComponents.getTypes().forEach(function (componentType) {
      if (componentType.id == 'row' || componentType.id == 'component') {
        const originalInitToolbar = componentType.model.prototype.initToolbar;
        if (!originalInitToolbar._overridden) {
          componentType.model.prototype.initToolbar = function (...args) {
            // Correctly call the parent method
            originalInitToolbar.apply(this, args);
            var tb = this.get('toolbar');
            if (tb) {
              tb.push({
                attributes: {
                  class: `fas fa-cube`,
                  title: Drupal.t('Store as layout component'),
                  weight: 4
                },
                command: 'open-modal-create-layout'
              });
              tb.sort(function (a, b) {
                return a.attributes.weight - b.attributes.weight;
              });
              this.set('toolbar', tb);
            }
          };
          componentType.model.prototype.initToolbar._overridden = true;
        }
      }
    });
  }

})(jQuery, Drupal);
