export default (() => {
    const infiniteLoader = document.querySelector('[data-infinite-loader]')
    
    if(infiniteLoader) {
      const loadingIcon = infiniteLoader.querySelector('img')
      let page = infiniteLoader.dataset.page ? infiniteLoader.dataset.page : 1
      let pages = infiniteLoader.dataset.pages
      page++
      const currentUrl = new URL(window.location.href)

      currentUrl.searchParams.set('paged', page)

      infiniteLoader.addEventListener('click', function () {
        infiniteLoader.classList.add('loading');
        loadingIcon.classList.add('active')

        currentUrl.searchParams.set('paged', page)

          $.ajax({
            url: currentUrl.toString(),
            method: 'GET',

          }).done(function (response) {
            const wrapper = $(response).find('[data-load-more] > div')
            const container = $('[data-load-more]')
            page++
            if (page > pages) {
              infiniteLoader.classList.add('disabled')
            }
            container.append(wrapper)
          }).fail(function (response) {
            console.log(response)

          }).always(function () {
            loadingIcon.classList.remove('active')
            currentUrl.searchParams.set('paged', page)

            infiniteLoader.classList.remove('loading');

          });
      });
    }
  })()