/* eslint-disable prettier/prettier */
/*
Responsavel pelo carregamento dinamico dos módulos.
*/
$(document).ready(function() {
  (function($) {
    $.fn.moduleLoad = function(options) {
      var settings = $.extend(
        {
          desconto: 0,
        },
        options
      );

      return this.each(function() {
        var $this = $(this);
        const { module } = settings;

        function moduleLoad() {
          var limitOffset = 0,
            MODULE_NAME = module.name.replace('slide-', '');

          function getAdditionalParameters(module) {
            var category = '',
              datarelacionados = '',
              product_id = '',
              orderpromotionid = '',
              featured_products = '';

            if (module.name == 'slide-lpbc' && typeof module.category_id != 'undefined') {
              category = '&category_id=' + module.category_id;
            }

            if (module.name == 'slide-produtosrelacionados') {
              category = '&category_id=' + module.category_id;
              datarelacionados = '&product_name=' + atob(module.product_name);
              datarelacionados = datarelacionados + '&product_id=' + module.product_id;
              datarelacionados = datarelacionados + '&product_grid_id=' + module.product_grid_id;
            }

            if (module.name == 'slide-special') {
              orderpromotionid = '&order_promotion_id=' + module.order_promotion_id;
            }

            if (module.name == 'slide-boughtalso') {
              product_id = '&product_id=' + module.product_id;
            }

            if (module.name == 'slide-featured') {
              featured_products = '&featured_product=' + module.productsIds;
            }

            return category + orderpromotionid + datarelacionados + product_id + featured_products;
          }

          var url =
            'index.php?route=product/productList/module' +
            camelCase(MODULE_NAME.charAt(0).toUpperCase() + MODULE_NAME.slice(1)) +
            '&ajax=true&start=' +
            limitOffset +
            '&limit=6&position=content_top' +
            getAdditionalParameters(module);

          var waitingForAjax = true;
          var initial = 0;

          $.ajax({
            url: url,
            type: 'get',
            dataType: 'html',
          })
            .done(function(products) {
              products = $(products);
              window.initProductBoxAction(products);

              products = products.filter('.ftr-product-card');
              var $newItems = $this.find('.ftr-product-card:empty');

              products.each(function(index) {
                if ($newItems[index]) {
                  $($newItems[index]).html(products[index].children);
                }
              });

              $('.ftr-js-scroller').on('scrollstart', { latency: 100 }, function() {
                initial = $(this).scrollLeft();
              });

              $this.find('.ftr-js-scroller').on('scrollstop', { latency: 100 }, function() {
                var $this = $(this);

                var moduleName = $this.data('module-name');
                if (!moduleName) return;

                if ($this.scrollLeft() <= initial || waitingForAjax) {
                  return;
                }

                limitOffset = $this.find('.ftr-product-card:not(:empty)').length;
                if (limitOffset >= 24) return;

                var url =
                  'index.php?route=product/productList/module' +
                  camelCase(MODULE_NAME.charAt(0).toUpperCase() + MODULE_NAME.slice(1)) +
                  '&ajax=true&start=' +
                  limitOffset +
                  '&limit=6&position=content_top' +
                  getAdditionalParameters(module);

                waitingForAjax = true;
                $.ajax({
                  url: url,
                  type: 'get',
                  dataType: 'html',
                })
                  .done(function(moreProducts) {
                    moreProducts = $(moreProducts);
                    window.initProductBoxAction(moreProducts);
                    moreProducts = moreProducts.filter('.ftr-product-card');
                    var $newItems = $this.find('.ftr-product-card:empty');
                    moreProducts.each(function(index) {
                      if ($newItems[index]) {
                        $($newItems[index]).html(moreProducts[index].children);
                      }
                    });
                  })
                  .fail(function(error) {
                    console.log(error);
                    console.log('error');
                  })
                  .always(function() {
                    waitingForAjax = false;
                  });
              });
            })
            .fail(function(error) {
              console.log(error);
              console.log('error');
            })
            .always(function() {
              waitingForAjax = false;
            });
        }

        $this.one('moduleLoad', function() {
          moduleLoad();
        });

        if ($this.parent().offset().top < $(window).scrollTop() + $(window).height() + settings.desconto) {
          $this.trigger('moduleLoad');
        }

        $(window).on('scroll', function() {
          if ($this.parent().offset().top < $(window).scrollTop() + $(window).height() + settings.desconto) {
            $this.trigger('moduleLoad');
          }
        });
      });
    };
  })($);

  $('.ftr-js-load-slide').trigger('load');

  for (var i = 0; i < window.productModules.length; i++) {
    const module = window.productModules[i];
    $(module.element).moduleLoad({ module });
  }

  function camelCase(string) {
    return string.replace(/[_-]([a-z])/g, function($1) {
      return $1.replace(/[_-]/g, '').toUpperCase();
    });
  }
});
