/**
 * @file
 * Javascript functionality for component life cycle.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentLifeCycle = Drupal.componentLifeCycle || {};
  Drupal.behaviors.componentLifeCycle = {
    attach: function (context) {
      Drupal.componentLifeCycle.addClassForCountItem();
      Drupal.componentLifeCycle.circleItem(context);
      Drupal.componentLifeCycle.addMatchHeight();
    }
  }
  Drupal.componentLifeCycle.addClassForCountItem = function () {
    const $component_wrapper = $(once('componentWrapper', '.component-builder.component-wrapper.component-wrapper--type-life_cycle'));
    var count = $(once('countItem', ".field--name-field-life-cycle")).children().length;
    $component_wrapper.addClass('item-count-display--life-cycle-'+ count);
  };
  Drupal.componentLifeCycle.addMatchHeight = function () {
    const $component_wrapper_selector = $('.component-builder.component-wrapper.component-wrapper--type-life_cycle.component-wrapper--content.field--name-field-life-cycle');
    const $title_group = ".field__item";
    // $.addMatchHeight($component_wrapper_selector, $title_group);

  };
  Drupal.componentLifeCycle.circleItem = function (context) {
    const $life_cycle = $(once('bubbleMap', '.component-builder.component-wrapper.component-wrapper--type-life_cycle', context));
    if($life_cycle.length > 0) {
      $life_cycle.each(function() {
        const $this = $(this);
        const $component_wrapper_content = $this.find('.component-wrapper--content');
        let width = 0;
        let height = 0;
        if ($component_wrapper_content.length > 0) {
          width = $this.width();
          height = $this.height();
        }
        let $main_content_wrapper = $(once('getElement', '.main-content-life-cycle', this));
        $main_content_wrapper.addClass('field__item');
        var x = $main_content_wrapper.wrap('<p/>').parent().html();
        $main_content_wrapper.unwrap();
        $main_content_wrapper.css('display', 'none');
        let $field_life_cycle = $this.find('.field--name-field-life-cycle');
        if ($field_life_cycle.length > 0) {
          $field_life_cycle.each(function () {
            $(once('addElementMarkup', this)).prepend(x);
          });
        }
        $field_life_cycle = $this.find('.field--name-field-life-cycle');
        if ($field_life_cycle.length > 0) {
          $field_life_cycle.each(function () {
            $(this).incircle({
              'left': width / 4  + "px",
              'top': height / 4  + "px",
            });
          });
        }
      })
    }
  }


})(jQuery, Drupal, once);
