/**
 * @file
 * Behaviors for the component_wrapper widget in node add form.
 */

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

  Drupal.componentWrapper = Drupal.componentWrapper || {};
  Drupal.behaviors.componentWrapper = {
    attach: function (context) {
      Drupal.componentWrapper.changeTypeSelectComponentType(context);
      Drupal.componentWrapper.setEvent(context);
    }
  }

  Drupal.componentWrapper.setEvent = function (context) {
    $(once('name-component-type', '.field--type-entity-reference.field--name-component-type', context)).each(function () {
      var $select = $(this).find('select');
      if ($select.length > 0) {
        Drupal.componentWrapper.showFieldReferenceWithComponentType($select);

        $select.change(function () {
          // temporary disable all submit buttons
          $select.closest('fieldset.component-complexity-complex').find('input[type="submit"]').prop('disabled', 'disabled');
          Drupal.componentWrapper.showFieldReferenceWithComponentType($(this))
        })
      }

      let $selectProperties = $('#component-attributes-wrapper--composite [class*=component-attributes-composite-properties-options-column] select');
      Drupal.componentWrapper.showFieldReferenceWithColumn($selectProperties);
      $(once('change-properties-component', '#component-attributes-wrapper--composite [class*=component-attributes-composite-properties-options-column] select', context)).each(function () {
        $(this).change(function () {
          Drupal.componentWrapper.showFieldReferenceWithColumn($(this));
        })
      })

      var $select = $(this).find('select');
      if ($select.length > 0) {
        Drupal.componentWrapper.showFieldReferenceWithComponentType($select);
        $select.change(function () {
          Drupal.componentWrapper.showFieldReferenceWithComponentType($(this))
        })
      }
    })
  }

  Drupal.componentWrapper.changeTypeSelectComponentType = function (context) {
    const $component_type = $(once('selectComponentType', '.component-builder--component-typem, select[name$="[component_type]"]', context));

    if ($component_type.length > 0) {
      var $select_ele = '';

      if ($component_type.closest('#drupal-modal').length > 0) {
        $component_type.select2({
          placeholder: Drupal.t('Select Component'),
          templateResult: Drupal.componentWrapper.templateSelectComponentType,
          dropdownParent: $('#drupal-modal'),
        });
      } else {
        $component_type.select2({
          placeholder: Drupal.t('Select Component'),
          templateResult: Drupal.componentWrapper.templateSelectComponentType,
        });
      }

      let optgroupState = {};

      $(once('selectResultsGroup', 'body')).on('click', '.select2-container--open .select2-results__group', function () {
        $(this).siblings().toggle();
        $(this).closest('li.select2-results__option--group').toggleClass('hide-component-group');
        let id = $(this).closest('.select2-results__options').attr('id');
        let index = $('.select2-results__group').index(this);
        if (optgroupState[id] && optgroupState[id][index]) {
          optgroupState[id][index] = !optgroupState[id][index];
        }
      });

      $component_type.on('select2:open', function () {
      //   $('.select2-dropdown--below,.select2-dropdown--above').css('opacity', 0);
      //   setTimeout(() => {
      //     let groups = $('.select2-container--open .select2-results__group');
      //     let id = $('.select2-results__options').attr('id');
      //     if (!optgroupState[id]) {
      //       optgroupState[id] = {};
      //     }
      //     $.each(groups, (index, v) => {
      //       if (index === 0) {
      //         optgroupState[id][index] = true;
      //       } else {
      //         optgroupState[id][index] = optgroupState[id][index] || false;
      //       }
      //       if (optgroupState[id][index]) {
      //         $(v).parent().removeClass('hide-component-group');
      //       } else {
      //         $(v).parent().addClass('hide-component-group');
      //       }
      //       optgroupState[id][index] ? $(v).siblings().show() : $(v).siblings().hide();
      //     });
      //     $('.select2-dropdown--below,.select2-dropdown--above').css('opacity', 1);
      //   }, 0);

        setTimeout(() => {
          $('input.select2-search__field').trigger('focus');
        }, 0);
      });
    }
  }

  Drupal.componentWrapper.templateSelectComponentType = function (state) {
    let html = [];
    if (!state.id) {
      return state.text;
    } else {
      const images = JSON.parse(drupalSettings.component_type_images);
      const $element = $(state.element);
      const value = $element.val();
      html.push('<div class="group-inner">');
      html.push('<div class="group-field">');
      let src = "";
      if (images[value] && images[value].length > 0) {
        src = window.location.origin + '/' + images[value];
      }
      html.push('<div class="field-img"><img src="' + src + '" class="img-flag" /></div>');
      if (state.text !== undefined) {
        html.push('<h4>' + state.text + '</h4>');
      }
      html.push('</div>');
      return $(html.join("\n"));
    }
  };

  Drupal.componentWrapper.showFieldReferenceWithComponentType = function ($selector, allowedFields = []) {
    var $parentSelect = $selector.closest('.field--type-entity-reference.field--name-component-type');
    var $parentIEF = $parentSelect.parent();
    var $complexField = $parentIEF.children('.field--type-entity-reference.field--widget-inline-entity-form-complex, .field--type-entity-reference.field--widget-inline-entity-form-simple');
    Drupal.componentWrapper.displayElement($complexField, 'none');
    const selectValue = $selector.val();
    var isSelect = false;
    if (parseInt(selectValue) == selectValue) {
      isSelect = true;
    }

    var textSelect = $selector.find('option:selected').text();
    if (textSelect.length > 0) {
      textSelect = textSelect.toLowerCase().replaceAll(' ', '-');
      const machineComponent = textSelect.replaceAll('-', '_');

      if (allowedFields.length === 0) {
        if (machineComponent === 'composite') {
          const $select = $parentIEF.find('#component-attributes-wrapper--composite [class*=component-attributes-composite-properties-options-column] select');
          if ($select.length > 0) {
            const selectValue = $select.val();
            if (isSelect) {
              allowedFields = Drupal.componentWrapper.getCompositeAllowed(selectValue, false);
            }
          }
        } else if (isSelect) {
          allowedFields = [textSelect];
        }
        if (machineComponent === 'timeline') {
          Drupal.componentWrapper.showFieldForComponentWithSubWrapper($('.field--name-field-timelines-wrapper'), 'Timeline', "field-timelines-wrapper-wrapper", "field--name-field-timeline");
        }
        if (machineComponent === 'tabs') {
          Drupal.componentWrapper.showFieldForComponentWithSubWrapper($('.field--name-field-tabs-column'), 'Tabs', "field-tabs-column-wrapper", "field--name-field-tabs");
        }
        if (machineComponent === 'tabs_simple') {
          Drupal.componentWrapper.showFieldForComponentWithSubWrapper($('.field--name-field-tabs-column'), 'Tabs Simple', "field-tabs-column-wrapper", "field--name-field-tabs-simple");
        }
      }

      var allowItemClass = [];
      for (let key in allowedFields) {
        // Test hide field.
        let fieldClass = 'field--name-field-' + allowedFields[key];
        let itemClass = '.field--type-entity-reference.field--widget-inline-entity-form-complex.' + fieldClass + ', .field--type-entity-reference.field--widget-inline-entity-form-simple.' + fieldClass;
        allowItemClass.push(itemClass);
      }

      if (allowItemClass.length > 0) {
        allowItemClass = allowItemClass.join(',');
        var $allowItem = $parentIEF.children(allowItemClass);
        if ($allowItem.length > 0) {
          if (!$parentIEF.children(allowItemClass).hasClass('field--name-field-timeline')
            && !$parentIEF.children(allowItemClass).hasClass('field--name-field-tabs')
            && !$parentIEF.children(allowItemClass).hasClass('field--name-field-tabs-simple')
          ) {
            Drupal.componentWrapper.displayElement($parentIEF.children(allowItemClass));
          }
        }
      }

      Drupal.componentWrapper.displayElement($parentIEF.find('.component-attributes-wrapper--item'), 'none');
      Drupal.componentWrapper.displayElement($parentIEF.find('.component-attributes-wrapper--tabs.component-attributes-wrapper--item'), 'none');

      const $display_properties = $('.edit-component-type--properties');
      $display_properties.unbind('click').click(function () {
        const $parent = $(this).closest('.field--name-component-type').parent();
        if ($parent) {
          const $properties = $parentIEF.find('#component-attributes-wrapper--' + machineComponent);
          if ($properties.length) {
            $parent.find('> .component-attributes-wrapper').toggleClass('component-attributes-wrapper__style--none-border');
          }
          $parent.find('> .wrapper-display--custom').toggleClass('component-attributes-wrapper__style--none-border');
        }
        let display = 'block';
        if ($display_properties.hasClass('active')) {
          display = 'none';
        }
        $display_properties.toggleClass('active');
      })
      Drupal.componentWrapper.showCustomStyle($parentIEF, machineComponent);
    }
  }

  Drupal.componentWrapper.showCustomStyle = function ($parentIEF, machineComponent) {
    var $properties = $parentIEF.find('#component-attributes-wrapper--' + machineComponent, '.component-attributes-wrapper--item');
    let $select = $('[name="custom_style"], .component-builder--custom-style');
    if ($properties.length > 0) {
      $select.parent().css('display', 'block');
    } else {
      $select.parent().css('display', 'none');
    }
    $select.unbind('click').click(function () {
      const display_style = $(this).is(':checked') ? 'block' : 'none';
      Drupal.componentWrapper.displayElement($properties, display_style);
    })
  }

  Drupal.componentWrapper.showFieldForComponentWithSubWrapper = function ($field_selected, $allowedOptionSubWrapper, $field_wrapper, $field_item) {
    if ($field_selected.length > 0) {
      $field_selected.css('display', 'block');
      $(document).ajaxStop(function () {
        let $wrapper_custom = $field_selected.find('.wrapper-display--custom.js-form-wrapper.form-wrapper');
        if ($wrapper_custom.length > 0) {
          $wrapper_custom.css('display', 'none');
        }

        let $form_select = $field_selected.find('select.form-select.form-element.form-element--type-select[id*="component-type"]');
        if ($form_select.length > 0) {
          let $selectOptions = $form_select.find("option");
          if ($selectOptions.length > 0) {
            $selectOptions.each(function () {
              if ($(this).text() === $allowedOptionSubWrapper) {
                let idTabContent = $(this).attr('value');
                $form_select.val(idTabContent).change();
                $form_select.css({'display': 'none'});

                let $label = $form_select.siblings('.form-item__label');
                $label.css({'display': 'none'});
              }
            });
          }
        }

        let $inner_wrapper = $field_selected.find("[id*='" + $field_wrapper + "']");
        if ($inner_wrapper.length > 0) {
          $inner_wrapper.css('display', 'none');
        }

        let $field_item_select = $field_selected.find('.field--type-entity-reference.' + $field_item + '.js-form-wrapper.form-wrapper');
        if ($field_item_select.length > 0) {
          $field_item_select.css('display', 'block');
        }

        const parent_field_hidden = '.field--name-field-timelines-wrapper, .field--name-field-tabs-column';
        Drupal.componentWrapper.hiddenChildFields(parent_field_hidden);
      });
    }
  }

  Drupal.componentWrapper.showFieldReferenceWithColumn = function ($selector) {
    $selector = $($selector);
    if ($selector.length != 1) {
      return;
    }
    var numberColumn = $selector.val();
    var $parentWrapperProperties = $selector.closest('#component-attributes-wrapper');
    var $parentIEF = $parentWrapperProperties.parent();

    let allowedColumnClass = [];
    let allColumnClass = [
      '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-left-column',
      '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-middle-column',
      '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-right-column',
      '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-left-column',
      '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-middle-column',
      '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-right-column'
    ];
    if (numberColumn == 1) {
      allowedColumnClass = [
        '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-left-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-left-column'
      ];
    } else if (numberColumn == 2) {
      allowedColumnClass = [
        '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-left-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-left-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-right-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-right-column'
      ];
    } else if (numberColumn == 3) {
      allowedColumnClass = allColumnClass;
    }
    let allowedColumnClassString = allowedColumnClass.join(',')
    let allColumnClassString = allColumnClass.join(',')
    Drupal.componentWrapper.displayElement($parentIEF.find(allColumnClassString), 'none');
    Drupal.componentWrapper.displayElement($parentIEF.find(allowedColumnClassString));
  }

  Drupal.componentWrapper.displayElement = function (element, display = 'block') {
    $(element).css({'display': display});
  }

  Drupal.componentWrapper.getCompositeAllowed = function (numberColumn, full_class = true) {
    var allowedColumnClass = [];
    if (full_class) {
      var allColumnClass = [
        '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-left-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-middle-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-right-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-left-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-middle-column',
        '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-right-column'
      ];
      if (numberColumn == 1) {
        allowedColumnClass = [
          '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-left-column',
          '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-left-column'
        ];
      } else if (numberColumn == 2) {
        allowedColumnClass = [
          '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-left-column',
          '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-left-column',
          '.field--type-entity-reference.field--widget-inline-entity-form-complex.field--name-field-right-column',
          '.field--type-entity-reference.field--widget-inline-entity-form-simple.field--name-field-right-column'
        ];
      } else if (numberColumn == 3) {
        allowedColumnClass = allColumnClass;
      }
    } else {
      var allColumnClass = [
        'left-column',
        'middle-column',
        'right-column',
      ];
      if (numberColumn == 1) {
        allowedColumnClass = [
          'left-column',
        ];
      } else if (numberColumn == 2) {
        allowedColumnClass = [
          'left-column',
          'right-column',
        ];
      } else if (numberColumn == 3) {
        allowedColumnClass = allColumnClass;
      }
    }
    return allowedColumnClass
  }

  Drupal.componentWrapper.hiddenChildFields = function (selector, fields_hidden = '', level = 1) {
    const $selector = $(selector);
    fields_hidden = '.component-attributes-wrapper--item';
    if ($selector.length > 0) {
      const $fields = $selector.find(fields_hidden);
      if ($fields.length > 0) {
        $fields.hide();
      }
    }
  }

})(jQuery, Drupal, once);
