(function($) {
  $.fn.carousel = function(options) {
    var settings = $.extend(
      {
        autoScroll: false,
        autoScrollTime: 6000,
        typeScroll: 'block', // single / block
        infinityScroll: false,
        hoverPause: false,
        itemsToShow: 'auto', // integer or "auto"
        sliderImage: false, // center / full / responsive / false
        resposive: false,
        ajaxLoading: false,
        full: false,
        minWidthItems: 150, //238 / 150
        indicators: true,
        columnLarge: false,
      },
      options
    );

    return this.each(function() {
      var $this = $(this),
        $wrapper = $('.carousel-wrapper', $this),
        $slider = $('.carousel-list', $wrapper),
        $items = $('.item-column', $slider),
        visible = jQuery.isNumeric(settings.itemsToShow)
          ? settings.itemsToShow
          : Math.floor($this.width() / settings.minWidthItems),
        currentPage = 1,
        pages,
        primeiroItemPage,
        visibleReal = visible,
        sliderWidth,
        itemsWidth,
        pageLimit,
        timer,
        varMouseOut = true,
        initialMinWidthItems;

      if (settings.ajaxLoading) {
        var totalQuantityAjax = Number($items.eq(0).data('quantity'));
        totalQuantityAjax = totalQuantityAjax < 24 ? totalQuantityAjax : 24;

        $_items = $items.filter(function (_,element){
          var resultado = $(element).find('.itembox:empty');
          return resultado.length > 0;
        });

        var fakeItemQuantity = totalQuantityAjax - $_items.length;
        //   $itemFake = $('<div>');
        // $itemFake.addClass('item-column');
        //
        // if (settings.columnLarge) {
        //   $itemFake.addClass('item-column--large');
        // }
        //
        // var $itemBox = $('<div>');
        // $itemBox.addClass('itembox rel paper');
        //
        // $itemFake.append($itemBox);
        //
        // for (var i = 0; i < fakeItemQuantity; i++) {
        //   $itemFake.clone().appendTo($slider);
        // }
      }

      if (settings.storeRating) {
        initialMinWidthItems = 540;
      } else {
        initialMinWidthItems = $items.hasClass('item-column--large') ? 238 : 150;
      }

      $this.off(); //remove todos os eventos ja atribuidos (reseta os eventos antes de atribuir novamente)

      if (settings.full == true && $(this).closest('.products_slider') != 'undefined') {
        $(this)
          .closest('.products_slider')
          .addClass('carousel-full');
      }
      //============================ INICIO - Responsivo FUTURA ============================//
      function responsivo() {
        if (initialMinWidthItems == 150) {
          // quando o valor não foi configurado e esta sendo utilizado o valor padrão
          if (window.innerWidth <= 360) {
            settings.minWidthItems = 144;
          } else if (window.innerWidth <= 480) {
            settings.minWidthItems = 160;
          } else if (window.innerWidth <= 1161) {
            settings.minWidthItems = 170;
          } else {
            settings.minWidthItems = 182;
          }
        } else if (initialMinWidthItems == 238) {
          // quando o valor não foi configurado e esta sendo utilizado o valor padrão
          if (window.innerWidth <= 360) {
            settings.minWidthItems = 144;
          } else if (window.innerWidth <= 480) {
            settings.minWidthItems = 170;
          } else if (window.innerWidth <= 540) {
            settings.minWidthItems = 200;
          } else if (window.innerWidth <= 768) {
            settings.minWidthItems = 238;
          } else if (window.innerWidth <= 940) {
            settings.minWidthItems = 238;
          } else if (window.innerWidth <= 1161) {
            settings.minWidthItems = 238;
          } else {
            settings.minWidthItems = 238;
          }
        }

        visible = jQuery.isNumeric(settings.itemsToShow)
          ? settings.itemsToShow
          : Math.floor($this.width() / settings.minWidthItems);
        visibleReal = visible > 0 ? visible : 1;

        if (settings.sliderImage == 'center') {
          if ($(window).width() < 1140) {
            $('.carousel-container.slide-home').css('margin-top', '-1rem');
          } else {
            $('.carousel-container.slide-home').css('margin-top', '0');
          }
        }

        // if (!settings.sliderImage && $('.item-column', $slider).length >= currentPage * visibleReal) {
        //   $('.item-column:nth-of-type(1n+0)', $slider).css('border-right', '1px solid #DDD');
        // }

        //identifica o primeiro item da pagina antes da quebra
        if (settings.typeScroll == 'block' && visibleReal) {
          primeiroItemPage = visibleReal * (currentPage - 1) + 1;
        }

        //muda a quantidade de itens visiveis de acordo com a tela
        if (settings.resposive) {
          visibleReal = Math.floor($this.width() / settings.minWidthItems);
          visibleReal = visibleReal > 0 ? visibleReal : 1;
        }

        //marca a currentPage como a página que contem o primeiro item em exibição antes da quebra
        if (settings.typeScroll == 'block' && visibleReal) {
          currentPage = Math.ceil(primeiroItemPage / visibleReal);
        }

        calcula_larguras();

        if ((!window.matchMedia('(pointer: coarse)').matches || !settings.sliderImage) && pages > 1) {
          addControlls();
        }

        goTo(1, false);
      }

      responsivo();

      if (!settings.sliderImage) {
        $(window).resize(function() {
          responsivo();
        });
        $this.on('refresh', function() {
          responsivo();
        });
      }
      //============================ FINAL - Responsivo FUTURA ============================//

      //Calcula as larguras do slider, dos items e define a página final
      function calcula_larguras() {
        //var discountWidth = window.matchMedia('(pointer: coarse)').matches ? 0.3 : 0;
        //itemsWidth = 100 / (visibleReal * pages) - discountWidth;
        // itemsWidth = 100 / pages - discountWidth;

        if (settings.typeScroll == 'block') {
          /* Transição de um grupo de itens por vez */
          $items = $('.item-column', $slider);
          pages = Math.ceil($items.length / visibleReal);
          sliderWidth = pages * 100;
          itemsWidth = 100 / (visibleReal * pages);
          pageLimit = pages; //Define a ultima pagina a ser rolada antes do reinicio
        } else {
          /* Transição de um item por vez */
          pages = $items.length;
          sliderWidth = (pages / visibleReal) * 100;
          itemsWidth = 100 / pages;
          pageLimit = pages - visibleReal + 1; //Define o último item a ser rolado antes do reinicio
        }
        seta_larguras();
      }

      function seta_larguras() {
        //seta as larguras calculadas acima nos elementos
        $slider.css({ width: sliderWidth + '%' });
        $items.css({ 'max-width': itemsWidth + '%', 'min-width': 'initial' });
      }

      //Reseta a altura dos itens antes de recalcular
      $items.css({ height: 'auto' });

      //Carrega a primeira imagem no banner principal
      if ($('.first-img', $items).length) {
        var firstImage = $('.first-img', $items),
          firstSource = firstImage.siblings('source');

        $.each(firstSource, function() {
          $(this).attr('srcset', $(this).attr('data-src'));
        });

        firstImage.attr('src', firstImage.attr('data-src'));

        firstImage.css({ display: 'block' });
        firstImage.on('load', function() {
          firstImage
            .parent()
            .next('.img-loading')
            .hide();
        });
      }
      if (settings.sliderImage && settings.indicators && pages > 1 && $(this).hasClass('slide-home')) {
        var $timeLine = $('<div>');
        $timeLine.addClass('time-line');
        $timeLine.append('<div class="time-line-current-time"></div>');
        $wrapper.append($timeLine);

        $('.time-line-current-time', $this)
          .stop(true, true)
          .css({ width: '0%' })
          .animate({ width: '100%' }, settings.autoScrollTime);

        var $indicators = $('<div>');
        $indicators.addClass('indicators-container');
        for (var i = 0; i < pageLimit; i++) {
          $indicators.append('<div class="indicators"><div class="indicators-content"></div></div>');
        }

        $this.append($indicators);

        $('.indicators', $this)
          .eq(0)
          .addClass('active');

        $('.indicators', $this).on('click', function() {
          goTo($('.indicators', $this).index($(this)) + 1);
        });
      }

      //No banner full a imagem tem position:absolute então a altura do banner e definida aqui
      if (settings.sliderImage == 'responsive') {
        $this.css({ 'margin-top': '-1rem' });
        if ($(' > img,  > picture', $items).length || $(' > a > img,  > a > picture', $items).length) {
          //se o banner tem imagens define a altura do banner no mesma altura da imagem
          $slider.addClass('img-full-responsive img');
          if ($(' > img,  > picture', $items).length) {
            if ($slider.data('banner-height')) {
              $items.height($slider.data('banner-height'));
            } else {
              $items.height($('> img, > picture', $items).height());
            }
          } else {
            if ($slider.data('banner-height')) {
              $items.height($slider.data('banner-height'));
            } else {
              $items.height($('> a > img, > a > picture', $items).height());
            }
          }
        } else {
          if ($slider.data('banner-height')) {
            $items.height($slider.data('banner-height'));
          } else {
            $items.height(400);
          }
        }
      } else if (settings.sliderImage == 'center') {
        $this.css({ 'max-width': '1140px', 'margin-top': '0' });
        if (!$(' > img,  > picture', $items).length && !$(' > a > img,  > a > picture', $items).length) {
          if ($slider.data('banner-height')) {
            $items.height($slider.data('banner-height'));
          } else {
            $items.height(400);
          }
        }
      } else if (settings.sliderImage == 'full') {
        $this.css({ 'margin-top': '-1rem' });
        if (!$(' > img,  > picture', $items).length && !$(' > a > img,  > a > picture', $items).length) {
          $items.height(400);
        }
      } else if (!settings.sliderImage) {
        if ($slider.data('aspect-ratio')) {
          $('.container-img', $items).css({
            height: 0,
            'padding-bottom': $slider.data('aspect-ratio'),
          });
        }
      }

      function carrega_imagem_banner_principal(page) {
        //INICIO - BANNER-PRINCIPAL-HOME Carregamento parcial das imagens
        var image = $('.slide-home .item-column:nth-child(' + page + ') .img-principal'),
          source = image.siblings('source');

        $.each(source, function() {
          $(this).attr('srcset', $(this).attr('data-src'));
        });

        image.attr('src', image.attr('data-src'));
        image.on('load', function() {
          $('.slide-home .item-column:nth-child(' + page + ') .img-loading').hide();
          $(this).css({ display: 'block' });
        });
        //FIM - BANNER-PRINCIPAL-HOME Carregamento parcial das imagens
      }

      $this.on('nextNewHtml', function(_, parameters) {
        //chamada ajax
        var $htmlNewItems = $(parameters.html);

        // carrega as imagens dos produtos
        window.initActionProductBox($htmlNewItems);
        window.initCountdown($htmlNewItems);

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

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

        //Só calcular as larguras se retornar algum produto via ajax
        // calcula_larguras();

        // if (typeof parameters.scroll != undefined && parameters.scroll == false) {
        //   $wrapper
        //     .filter(':not(:animated)')
        //     .animate({ scrollLeft: (currentPage - 1) * $wrapper.width() }, 600, function() {
        //       enableNext();
        //     });
        // }
      });

      $this.on('cheeeeeeega', function(_, parameters) {
        settings.ajaxLoading = false;
      });

      function goTo(page, get) {
        if (typeof get == 'undefined') {
          get = true;
        }

        if ($items.length >= visibleReal) {
          var dir = page < currentPage ? -1 : 1;

          if (settings.infinityScroll) {
            if (page > pageLimit && dir == 1) {
              page = 1;
            } else if (page == 0 && dir == -1) {
              page = pageLimit;
            }
          } else {
            if (page > pageLimit && dir == 1) {
              page = pageLimit;
            } else if (page == 0 && dir == -1) {
              page = 1;
            }
          }

          if (!settings.sliderImage) {
            $this.find('.next, .prev').removeAttr('style');

            if (page == pageLimit) {
              $this.find('.next').css({
                cursor: 'not-allowed',
                'background-color': '#DDD',
              });
            }
            if (page == 1) {
              $this.find('.prev').css({
                cursor: 'not-allowed',
                'background-color': '#DDD',
              });
            }
          }

          currentPage = page;

          if ($this.hasClass('slide-home')) {
            carrega_imagem_banner_principal(page);
          }

          // if (!settings.sliderImage && $('.item-column', $slider).length >= currentPage * visibleReal) {
          //   $('.item-column:nth-of-type(1n+0)', $slider).css('border-right', '1px solid #DDD');
          //   $('.item-column:nth-of-type(' + currentPage * visibleReal + ')', $slider).css('border-right', 'none');
          // }

          //Faz a transição entre os slides
          if (!settings.ajaxLoading) {
            if (window.matchMedia('(pointer: coarse)').matches) {
              $wrapper.filter(':not(:animated)').animate({ scrollLeft: (page - 1) * $wrapper.width() }, 600);
            } else {
              $slider.filter(':not(:animated)').animate({ left: (page - 1) * -(sliderWidth / pages) + '%' }, 600);
            }
          } else {
            if (window.matchMedia('(pointer: coarse)').matches) {
              enableNext();
            } else {
              $slider.filter(':not(:animated)').animate({ left: (page - 1) * -(sliderWidth / pages) + '%' }, 600);
              enableNext();
            }
          }

          $('.indicators', $this).removeClass('active');
          $('.indicators', $this)
            .eq(page - 1)
            .addClass('active');
          if (varMouseOut && pages > 1) {
            $('.time-line-current-time', $this)
              .stop(true, true)
              .css({ width: '0%' })
              .animate({ width: '100%' }, settings.autoScrollTime);
          }
        }
      }

      function getEventName() {
        var event;
        for (var i = 0; i < $this[0].classList.length; i++) {
          if ($this[0].classList[i].indexOf('slide-') >= 0) {
            event = $this[0].classList[i];
          }
        }
        return event;
      }

      function enableNext() {
        if (window.matchMedia('(pointer: coarse)').matches && settings.ajaxLoading) {
          var timerEndScroll = null;
          var initialScroll = $wrapper.scrollLeft();
          disableNext();
          $wrapper.on('scroll', function() {
            if (timerEndScroll) {
              clearTimeout(timerEndScroll);
            }
            timerEndScroll = setTimeout(function() {
              $('.indicators', $this)
                .removeClass('active')
                .eq(Math.floor($slider.scrollLeft() / $this.width()))
                .addClass('active');

              if (initialScroll < $wrapper[0].scrollLeft) {
                disableNext();
                $this.trigger(getEventName(), [
                  $this,
                  true,
                  { module: settings.module, pagination: fakeItemQuantity, limit: totalQuantityAjax },
                ]);
                initialScroll = $wrapper[0].scrollLeft;
              }
            }, 150);
          });
        }
      }

      function disableNext() {
        $wrapper.off('scroll');
      }

      function addContollsEvents() {
        $('a.prev', $this).click(function(e) {
          e.preventDefault();
          goTo(currentPage - 1);
        });

        $('a.next', $this).click(function(e) {
          e.preventDefault();
          goTo(currentPage + 1);
          if (settings.ajaxLoading) {
            $this.trigger(getEventName(), [
              $this,
              false,
              { module: settings.module, pagination: visibleReal, limit: totalQuantityAjax },
            ]);
            disableNext();
          }
        });

        enableNext();
        $this.bind('next', function() {
          goTo(currentPage + 1);
        });
      }

      //insere os controles
      function addControlls() {
        if ($('.control', $this).length > 0) {
          $('.control', $this).remove();
        }

        $wrapper.after(
          '<a href="#" class="control prev"><i class="fas fa-angle-left"></i></a><a href="#" class="control next"><i class="fas fa-angle-right"></i></a>'
        );

        addContollsEvents();
      }

      //================================= autoScroll e hoverPause - INICIO =================================//
      if (settings.autoScroll) {
        timer = setInterval(function() {
          $this.trigger('next');
        }, settings.autoScrollTime);

        if (settings.hoverPause == true && settings.autoScroll == true) {
          $this
            .mouseenter(function() {
              $('.indicators-content', $this).stop(true, true);
              $('.time-line-current-time')
                .stop(true, true)
                .css({ width: '0%' });
              varMouseOut = false;
            })
            .mouseleave(function() {
              varMouseOut = true;
              if (varMouseOut && pages > 1) {
                $('.time-line-current-time', $this)
                  .stop(true, true)
                  .css({ width: '0%' })
                  .animate({ width: '100%' }, settings.autoScrollTime);
              }
            });
          $this
            .mouseover(function() {
              clearInterval(timer);
            })
            .mouseout(function() {
              timer = setInterval(function() {
                $this.trigger('next');
              }, settings.autoScrollTime);
            });
        }
      }

      function autoScrollStop() {
        if (settings.autoScroll) {
          if (timer) {
            clearInterval(timer);
          }
          settings.autoScroll = false;
          var images = $this.find('.img-principal');
          images.each(function() {
            var image = $(this),
              source = image.siblings('source');

            $.each(source, function() {
              $(this).attr('srcset', $(this).attr('data-src'));
            });

            image.attr('src', image.attr('data-src'));
            image.on('load', function() {
              image.next('.img-loading').hide();
              image
                .parent()
                .next('.img-loading')
                .hide();

              image.css({ display: 'block' });
            });
          });
        }
      }

      if (window.matchMedia('(pointer: coarse)').matches) {
        $this.on('touchstart', function() {
          $wrapper.on('scroll', autoScrollStop);
        });
        $this.on('touchend', function() {
          $wrapper.off('scroll', autoScrollStop);
        });
      }

      if (window.matchMedia('(pointer: coarse)').matches && settings.indicators) {
        $wrapper.on('scroll', function() {
          $('.indicators', $this)
            .removeClass('active')
            .eq(Math.round($wrapper.scrollLeft() / $this.width()))
            .addClass('active');
        });
      }

      //================================= autoScroll e hoverPause - FINAL =================================//
    });
  };
})(jQuery);
