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

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

  // Handle HTML before sortable init.
  $(document).ready(function() {
    var $region_wrappers = $('.component-builder-toolbar-region-wrapper');
    $region_wrappers.each(function() {
      var $this = $(this);
      var $region = $this.find('> .component-builder-toolbar__region');
      var $region_name = $this.find('.component-builder-toolbar__region-name');
      var region = $region_name.data('region');
      if (!$region.length) {
        $this.addClass('component-builder-toolbar__region component-builder-toolbar__sortable region region--' + region);
        $this.attr('data-region', region);
      }
      else {
        $region.unwrap($this);
      }

      // exception case sortable for olivero theme
      if (region == 'footer_top') {
        const $clone = $region_name.parent().children().clone();
        $region.empty();
        $region.html($clone);
      }
    });
  });

  var sortableClass = 'component-builder-toolbar__sortable';

  var ajax = Drupal.ajax;

  Drupal.componentToolbar = Drupal.componentToolbar || {};
  Drupal.componentToolbar.componentSortable = [];

  Drupal.componentToolbar.initSortable = function() {
    $('.' + sortableClass).each(function(index, sortable) {
      var $sortable = $(sortable);
      if (!$sortable.hasClass('js-sortable-processed')) {
        var sortableObj = new Sortable(sortable, {
          group: 'componentToolbar',
          handle: '.sortable-handle',
          animation: 150,
          dragClass: 'sortable-drag',
          ghostClass: 'sortable-drag-host',
          sort: true,
          onEnd: function(event) {
            Drupal.componentToolbar.moveWrapper(event);
          },
        });
        const region = $(this).data('region');
        Drupal.componentToolbar.componentSortable[region] = sortableObj;
        $sortable.addClass('js-sortable-processed');
        $(once('hover', '.component-builder-toolbar--component-block', sortable)).hover(
          function () {
            $(this).addClass("highlight");
          },
          function () {
            $(this).removeClass("highlight");
          });
      }
    });
  };

  Drupal.componentToolbar.getWeight = function (region) {
    var obj_update = {
      'block': {},
      'component': {}
    };
    const $region = $(`[data-region="${region}"]`);
    const $children = $region.find('.component-builder-toolbar__block,.component-builder-toolbar--component-block');
    $children.each(function (index, item) {
      const $item = $(item);
      if ($item.hasClass('component-builder-toolbar__block')) {
        let item_id = $item.data('id');
        obj_update['block'][item_id] = index;
      }
      else {
        let item_id = $item.data('wrapper-id');
        obj_update['component'][item_id] = index;
      }
    })
    return obj_update;
  }

  Drupal.componentToolbar.moveWrapper = function(event) {
    var from_region = $(event.from).closest('.component-builder-toolbar__region').data('region');
    var to_region = $(event.to).closest('.component-builder-toolbar__region').data('region');
    if ((from_region !== to_region) || (event.oldIndex !== event.newIndex && from_region === to_region)) {
      var $item = $(event.item);
      var oldIndex = to_region === 'content' ? $item.data('field-delta') : $item.data('region-weight');
      oldIndex = oldIndex || 0;
      var $before = $item.prev();
      var $after = $item.next();

      var newIndex = event.newIndex;
      if (newIndex === 0 && to_region !== 'content') {
        newIndex = (typeof $after.data('region-weight') == 'number') ? $after.data('region-weight') - 1 : 0;
      }
      else if (newIndex !== 0 && to_region !== 'content') {
        newIndex = (typeof $before.data('region-weight') == 'number') ? $before.data('region-weight') + 1 : 0;
      }
      else if (newIndex !== 0) {
        newIndex = (typeof $before.data('field-delta') == 'number') ? $before.data('field-delta') + 1 : 0;
      }

      const $content = Drupal.componentToolbar.loading();
      $content.appendTo($('body'));

      let weight_region = '';
      if (to_region !== 'content') {
        weight_region = Drupal.componentToolbar.getWeight(to_region);
      }
      ajax({
        url: [$item.data('move-wrapper-url'), from_region, oldIndex, to_region, newIndex].filter(function (element) {
          return element !== undefined;
        }).join('/'),
        method: 'POST',
        submit: {
          items: weight_region,
        },
        error: function() {
          console.log('Error');
        },
        timeout: 1000,
      })
        .execute()
        .done(function () {
          $content.remove();
        });

      window.setTimeout(() => {
        $content.remove();
      }, 15000);
    }
  };

  Drupal.componentToolbar.loading = function (ready = '') {
    const $content = $('<div class="component-toolbar-move-loading"><span class="component-toolbar-move-loading-icon"></span></div>');
    if (ready) {
      $content.addClass('ready');
    }
    return $content;
  }

  Drupal.componentToolbar.initEvents = function (context) {
    // Add class default for olivero theme.
    $(once('sidebarGird', '.sidebar-grid.grid-full', context)).addClass('component-wrapper-sidebar-grid');

    $(once('reviewComponent', '.component-builder-toolbar__wrapper-preview-link')).click(function () {
      const $parent = $(this).closest('.component-builder-toolbar--component-block');
      if ($parent) {
        $parent.toggleClass('preview');
        Drupal.attachBehaviors();
      }
    })

    $(once('propertiesLink', '.component-builder-toolbar__wrapper-properties-link')).click(function () {
      const $preview = $(this).siblings('.component-builder-toolbar__wrapper-preview-link');
      const $parent = $(this).closest('.component-builder-toolbar--component-block');
      if ($preview && !$parent.hasClass('.preview')) {
        $parent.addClass('preview');
      }
    })
    $(once('useAjax', '.use-ajax', context)).click(function () {
      const $content = Drupal.componentToolbar.loading();
      $content.appendTo($('body'));
      setTimeout(function () {
        $content.remove();
      }, 10000);
    });

    $(once('dialog-behavior', window))
      .on('dialog:beforecreate', function () {
        $('.component-toolbar-move-loading').remove();
      })
  }

  $.fn.componentToolbarScrollTo = function (data) {
    $('html, body').animate({
      scrollTop: $(this).offset().top - 200
    }, 500);
  }

  Drupal.behaviors.componentToolbarWrapperDrag = {
    attach: function (context) {
      Drupal.componentToolbar.initSortable();
      Drupal.componentToolbar.initEvents(context);
    }
  };

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