/* eslint-disable prettier/prettier */
/*
Responsavel pelo carregamento dinamico dos módulos.
*/
window.waitEvent('scripts_window', () => {

  (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,
            acc,
            MODULE_NAME = module.name.replace('slide-', '');

          const moduleElement = $(module.element);

          function getAditionalParameters(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-brandproducts') {
              product_id = '&product_id=' + module.product_id;
            }

            if (module.name == 'slide-productwhosaw') {
              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;
          }

          $.ajax({
            type: 'get',
            url:
              'index.php?route=product/productList/module' +
              camelCase(MODULE_NAME.charAt(0).toUpperCase() + MODULE_NAME.slice(1)),
            data:
              'ajax=true&start=' +
              limitOffset +
              '&limit=' +
              6 +
              '&position=content_top' +
              getAditionalParameters(module),
          }).done(function (response) {
            var $htmlNewItems = $(response);

            window.initActionProductBox($htmlNewItems);
            window.initCountdown($htmlNewItems);

            $htmlNewItems = $htmlNewItems.filter('.item-column');
            var $newItems = moduleElement.find('.item-column .itembox:empty');

            limitOffset = $htmlNewItems.length;

            $htmlNewItems.each(function (index, element) {
              if ($newItems[index]) {
                $($newItems[index])
                  .parent()
                  .append($(element).find('.itembox')[0]);
                $($newItems[index]).remove();
              }
            });


            moduleElement.carousel({
              resposive: true,
              ajaxLoading: true,
              module: module,
              columnLarge: window.columnLarge == 4,
            });

            moduleElement.on(module.name, function (e, plugin, scroll, moduledata) {
              if (!window.matchMedia('(pointer: coarse)').matches) {
                acc = acc || moduledata.pagination;
                if (limitOffset % moduledata.pagination == 0 && limitOffset == 6 && limitOffset > moduledata.pagination) {
                  acc += moduledata.pagination;
                  if (acc <= limitOffset) {
                    return;
                  }
                } else if (limitOffset % moduledata.pagination != 0) {
                  moduledata.pagination = moduledata.pagination - (limitOffset % acc);
                }
              }

              var next = plugin.find('.next'),
                moduleName = e.type;

              if (limitOffset >= moduledata.limit) {
                plugin.trigger('cheeeeeeega', { scroll: scroll });
                $(window).off(moduleName);
                return;
              }

              $.ajax({
                type: 'get',
                url:
                  'index.php?route=product/productList/module' +
                  camelCase(MODULE_NAME.charAt(0).toUpperCase() + MODULE_NAME.slice(1)),
                data:
                  'ajax=true&start=' +
                  limitOffset +
                  '&limit=' +
                  moduledata.pagination +
                  '&position=content_top' +
                  getAditionalParameters(module),
                beforeSend: function () {
                  next.find('i').css({ display: 'none' });
                  if (!next.find('#temp-loading').length) {
                    next.append(
                      '<img id="temp-loading" src="assets/img/loading-black.svg" alt="loading" width="24" height="24">'
                    );
                  }
                },
              })
                .done(function (response) {
                  plugin.trigger('nextNewHtml', { html: response, scroll: scroll });
                })
                .fail(function (error) {
                  limitOffset = limitOffset - moduledata.pagination;
                  console.log('error');
                  console.log(error);
                })
                .always(function () {
                  next.find('i').css({ display: 'inline-block' });
                  next.find('#temp-loading').remove();
                });

              limitOffset = limitOffset + moduledata.pagination;
            });
          });

        }

        $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');
          }
        });
      });
    };
  })($);

  $('.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();
    });
  }
});
