import documentReady from "@assets/js/documentReady";
import axiosApi from '@assets/js/axios-api';

const BASE_URL = document.getElementById('base-urls').dataset.baseUrlLoja;

documentReady(init);

function init() {
  let dataInfo = JSON.parse(document.querySelector('[data-info]').dataset.info);
  const carousel = document.getElementById('reviews-carousel'),
    btnMoreReviews = document.querySelector('.btn-more-reviews'),
    btnTogglePagination = document.querySelector('.js-toggle'),
    comments = document.querySelectorAll('.review-comment'),
    modalContent = document.getElementById('reviews-modal-content'),
    overlay = document.getElementById('reviews-modal-overlay'),
    pages = document.getElementById('reviews-pages'),
    reviewsPerPage = pages.dataset.reviewsPerPage,
    limit_reviews = Math.ceil(pages.dataset.totalReviews / reviewsPerPage);

  let nextPage = 2;
  
  overlay.onmousedown = (e) => {
    modalContent.innerHTML = '';
    overlay.classList.add('hidden');
  };

  document.querySelectorAll('#reviews-modal-overlay, .js-close-modal').forEach((item) => {
    item.onmousedown = (e) => {
      modalContent.innerHTML = '';
      overlay.classList.add('hidden');
    };
  });

  document.getElementById('reviews-modal').onmousedown = (e) => e.stopPropagation();

  initCarouselControls(carousel);

  carousel.querySelectorAll('.review-box').forEach((box) => {
    box.onclick = showReview.bind({box, modalContent, overlay});
  });

  if (btnMoreReviews) {
    btnMoreReviews.onclick = (e) => {
      e.preventDefault();
      if (nextPage <= limit_reviews) {
        btnMoreReviews.classList.add('hidden');
        document.querySelector('.js-loading-reviews').classList.remove('hidden');
        axiosApi({
          method: 'GET',
          url: BASE_URL + 'index.php?route=product/product_reviews/getReviews&limit='+ reviewsPerPage,
          type: 'json',
          params: {
            product_id: dataInfo.productId,
            page: nextPage,
          }
        })
          .then(({data}) => {
            if (data) {
              document.querySelector('.js-loading-reviews').classList.add('hidden');
              document.getElementById('reviews-content').innerHTML += data.html;
              nextPage++;
              if (nextPage <= limit_reviews) {
                btnMoreReviews.classList.remove('hidden');
              }
            }
          })
          .catch((err) => console.log(err));
      }
    }
  }

  btnTogglePagination.onclick = (e) => {
    e.preventDefault();
    togglePagination();
    if (carousel.classList.contains('hidden')) {
      btnTogglePagination.innerHTML = 'Ver Todos';
    } else {
      btnTogglePagination.innerHTML = 'Ver Menos';
    }
  };
}

function initCarouselControls(container) {
  const prevControl = container.querySelector('.control.prev'),
    nextControl = container.querySelector('.control.next'),
    cols = container.querySelectorAll('.review-column'),
    list = container.querySelector('.carousel-wrapper');

  if (cols.length > 3){
    const dist = Math.ceil(cols[1].getBoundingClientRect().left - cols[0].getBoundingClientRect().left);
    window.addEventListener('resize', () => {
      Math.ceil(cols[1].getBoundingClientRect().left - cols[0].getBoundingClientRect().left);
    });
    prevControl.onclick = () => {
      if (cols[0].getBoundingClientRect().left < list.getBoundingClientRect().left) {
        list.scrollBy({
          top: 0,
          left: -dist,
          behavior: 'smooth'
        });
      } else {
        list.scroll({
          top: 0,
          left: cols[cols.length - 1].getBoundingClientRect().left,
          behavior: 'smooth'
        });
      }
    };
    nextControl.onclick = () => {
      const lastCol = cols[cols.length - 1];
      if ((lastCol.getBoundingClientRect().left + lastCol.offsetWidth) > list.getBoundingClientRect().right) {
        list.scrollBy({
          top: 0,
          left: dist,
          behavior: 'smooth'
        });
      } else {
        list.scroll({
          top: 0,
          left: 0,
          behavior: 'smooth'
        });
      }
    };
  }
}

function showReview() {
  let {box, modalContent, overlay} = (this);

  modalContent.innerHTML = box.innerHTML;
  modalContent.querySelector('.review-comment').innerHTML =  '<span class="text-medium text-dark">' +
    modalContent.querySelector('.review-comment').dataset.text +
    '</span>';
  modalContent.querySelector('.review-comment').classList.remove('review-comment');
  overlay.classList.remove('hidden');
}

function togglePagination() {
  document.querySelectorAll('.reviews-container').forEach((container) => {
    container.style.opacity = '0';
    setTimeout(() => {
      container.classList.toggle('hidden');
      setTimeout(() => {
        container.style.opacity = '1';
      }, 300)
    }, 300);
  });
}