import {createEvent} from "./utils/create-event";
import {appendLoader, showLoader, hideLoader} from "./utils/loader";

var Wick = window.Wick || {};

Wick.PLPLoadMore = {
  PLP_LOAD_MORE_EVENT: 'loadMore',
  HIDDEN_CLASS_NAME: 'd-none',
  initialPageNumber: 0,
  el: {
    $loadMoreBtn: $('.btn-load-more'),
    loader: '.loader-wrapper',
    $sortOptions: $('#sort_form1'),
    productsList: '.products-list'
  },
  numberOfPagesPLP: $('#numberOfPagesPLP').val(),
  loaderPayload: {
    wrapper: 'body',
    hidden: true,
    modifier: 'basket-loader',
  },
  loadMore () {
    showLoader(Wick.PLPLoadMore.el.loader);

    return new Promise((resolve, reject) => {
      const eventDetail = {resolve, reject};
      const payload = {
        currentPage: ++Wick.PLPLoadMore.initialPageNumber,
        sort: Wick.PLPLoadMore.el.$sortOptions.val() || '',
      };
      const event = createEvent(Wick.PLPLoadMore.PLP_LOAD_MORE_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then((response) => {
        if (!response.length) {
          return;
        }

        Wick.PLPLoadMore.showNewCards(response);
        Wick.PLPLoadMore.toggleLoadMoreBtn();
        Wick.VatToggle.reapplyDisplayClass();
      })
      .finally(() => {
        hideLoader(Wick.PLPLoadMore.el.loader);
        Wick.PLPLoadMore.el.$loadMoreBtn.blur();
        Wick.BannerPlacementManager.checkProductsInColumn();
        $(window).trigger('productBannerPositionChanged');
        Wick.EnergyEfficiency.drawEnergyLabels();
        Wick.PLP?.bindEvents();
      })
  },
  showNewCards (newProductsHtml) {
    const $newProductsHtml = $(newProductsHtml);
    $(Wick.PLPLoadMore.el.productsList).append($newProductsHtml);
  },
  toggleLoadMoreBtn() {
    if (Wick.PLPLoadMore.initialPageNumber + 1 >= +Wick.PLPLoadMore.numberOfPagesPLP) {
      Wick.PLPLoadMore.el.$loadMoreBtn.addClass(Wick.PLPLoadMore.HIDDEN_CLASS_NAME);
    }
  },
  init () {
    if (!Wick.PLPLoadMore.el.$loadMoreBtn.length) {
      return;
    }
    appendLoader(Wick.PLPLoadMore.loaderPayload);

    Wick.PLPLoadMore.el.$loadMoreBtn.on('click', Wick.PLPLoadMore.loadMore);
  }
}

$(document).ready(function () {
  if (!Wick.PLPLoadMore.el.$loadMoreBtn.length) {
    return;
  }

  Wick.PLPLoadMore.init();
});
