(function ($, Drupal) {

  Drupal.behaviors.pagedesigner_layouts_render_block_element = {
    attach: function (context, settings) {
      once('pagedesigner_layouts_render_block_element', 'body', context).forEach(() => {
        $(document).on('pagedesigner-render-block-element', function (e, block, element) {
          addDeleteButtonToBlockElement(block, element);
        });
      });
    }
  };

  function addDeleteButtonToBlockElement(block, element) {
    $blockElement = $(element);
    if (block.get('category').id == 'Layouts') {
      var $btn = $('<div class="gjs-am-close">⨯</div>');
      var layoutId = block.get('id').replace('layout', '');
      $btn.click(function () {
        if (confirm(Drupal.t("Do you really want to delete this layout?"))) {
          editor.BlockManager.remove('layout' + layoutId)
          Drupal.restconsumer.delete('/pagedesigner/layout/' + layoutId);
        }
      });
      $blockElement.append($btn);
    }
  }

})(jQuery, Drupal);
