/**
 * @file
 * Javascript functionality for component flexslider.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentFlexslider = Drupal.componentFlexslider || {};
  Drupal.behaviors.componentFlexslider = {
    attach: function (context) {
      Drupal.componentFlexslider.flexslider(context);
    }
  }

  Drupal.componentFlexslider.flexslider = function (context) {
    const $component_wrapper = $(once('wrapperFlexslider', '.preview .component-builder.component-wrapper--type-flexslider, .component-builder.component-wrapper--type-flexslider:not(.component-builder-preview)', context));
    if ($component_wrapper.length > 0) {
      $component_wrapper.each(function () {

        let flexslider_type = $(this).attr('flexslider-type');
        let width = $(this).width();
        if (flexslider_type === 'basic') {
          $(this).flexslider({
            selector: '.component-wrapper--content .field--name-field-flexslider > .field__item',
            animation: "slide",
            itemWidth: width,
          });
        }
        else if (flexslider_type === 'thumbnail-image') {
          let $field_flexslider_items = $(this).find(".field--name-field-flexslider .field--name-field-fs-image");
          if ($field_flexslider_items.length > 0) {
            $field_flexslider_items.each(function () {
              let $field_item = $(this);
              let $images = $field_item.find('img');
              if ($images.length > 0) {
                $images.each(function () {
                  let srcImage = $(this).attr('src');
                  $field_item.attr('data-thumb', srcImage);
                });
              }
            });
          }
          $(this).flexslider({
            selector: '.field--name-field-flexslider div.field--name-field-fs-image',
            animation: "slide",
            controlNav: "thumbnails",
          });

        }
      });
    }
  };

  Drupal.componentFlexslider.groupTagsForFlex = function () {
    const $component_wrapper = $('.component-builder.component-wrapper.component-wrapper--type-flexslider');
    if ($component_wrapper.length > 0) {
      $component_wrapper.each(function () {
        let $fields_to_group = $component_wrapper.find('div.flex-viewport , ol.flex-control-nav , ul.flex-direction-nav');
        if ($fields_to_group.length > 0) {
          $(once('groupField', $fields_to_group)).wrapAll('<div class="group-flexslider"></div>');
        }
      });
    }
  }

})(jQuery, Drupal, once);
