/**
 * @file
 * Defines Javascript behaviors for the component builder toolbar menu.
 */

(function ($, Drupal, drupalSettings, once) {
  'use strict';

  Drupal.componentToolbarMenu = Drupal.componentToolbarMenu || {};

  Drupal.behaviors.componentWrapperToolbarMenu = {
    attach: function (context, settings) {
      Drupal.componentToolbarMenu.alterBlock(context, settings);
      Drupal.componentToolbarMenu.setMenuEvent(context, settings);
    }
  };

  Drupal.componentToolbarMenu.alterBlock = function (context) {
    const $blocks = $('.component-builder-toolbar__block');
    if ($blocks.length > 0) {
      $.each($blocks, function (index, item) {
        const $block = $(item);
        const title = $block.data('title') || "";
        if (title.length > 0) {
          const $markup = $("<div class='component-builder-toolbar__block__title'>Block: " + title + "</div>");
          if ($block.find('.component-builder-toolbar__block__title').length == 0) {

            $(once('appendBlock', $block)).append($markup);
            Drupal.componentToolbarMenu.updateBlockTitle();
          }
        }
      })
    }
  };

  Drupal.componentToolbarMenu.updateBlockTitle = function (show = true) {
    if (show) {
      const $blockSiblings = $('.component-builder-toolbar__block__title').siblings();
      if ($blockSiblings) {
        $blockSiblings.addClass('component-builder-toolbar__hidden-sibling-block');
      }
    }
    else {
      const $blockSiblings = $('.component-builder-toolbar__block__title').siblings();
      if ($blockSiblings) {
        $blockSiblings.removeClass('component-builder-toolbar__hidden-sibling-block');
      }
    }
    $('.contextual').removeClass('component-builder-toolbar__hidden-sibling-block');
  };

  Drupal.componentToolbarMenu.setMenuEvent = function (context, settings) {
    const $menu = $(once('toolbarMenu', '#component-builder-toolbar-menu', context));
    if ($menu.length > 0) {
      $('.icon-toolbar-menu').click(function () {
        $(this).toggleClass('active');
      })
      $('.btn-mode').click(function () {
        if ($(this).hasClass('btn-mode-review')) {
          $('body').addClass('preview');
          Drupal.componentToolbarMenu.updateBlockTitle(false);
          Drupal.attachBehaviors(context, settings);
        }
        else {
          $('body').removeClass('preview');
          Drupal.componentToolbarMenu.updateBlockTitle();
        }
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
      })
    }
  };

})(jQuery, Drupal, drupalSettings, once);
