$(document).ready(function() {
  var token = document.querySelector('body').getAttribute('data-token'),
    productGrid = document.querySelectorAll('.js-product-grid');

  for (let i = 0; i < productGrid.length; i++) {
    productGrid[i].onclick = productGridList.bind(productGrid[i]);
  }

  function productGridList(event) {
    event.preventDefault();
    var pageProductForm = document.getElementById('page-product-form'),
      productKeyId = this.getAttribute('data-product-key-id'),
      productName =
        pageProductForm != null
          ? document.querySelector('.js-product-name').textContent
          : this.querySelector('.js-product-name').textContent,
      modalProductGridList = document.getElementById('modal-product-grid-list'),
      typeMarketplace = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info')).type_marketplace,
      urlFilter = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info')).urlFilter,
      parent = document.createElement('div');

    if (modalProductGridList != null) modalProductGridList.remove();

    parent.id = 'modal-product-grid-list';
    parent.classList.add('adm-modal-overlay', 'overlay', 'overlay-black-3');

    parent.innerHTML =
      '<div class="adm-modal-container center-middle-fixed background-white"><img src="../assets/img/loading-black.svg" width="64" height="64" alt="" /></div>';
    document.querySelector('body').append(parent);

    const mktplaceFilter = (typeMarketplace != "" ? '&type_marketplace='+typeMarketplace : '');
    $.ajax({
      url:
        'index.php?route=catalog/product/retornoProductsGrid&token=' +
        token +
        '&product_grid_id=' +
        productKeyId +
        mktplaceFilter +
        (urlFilter || ''),
      type: 'get',
      dataType: 'html',
      beforeSend: function() {},
      complete: function() {},
      success: function(html) {
        parent.innerHTML = html;
        document.getElementById('modal-product-grid-list').querySelector('.js-product-name').textContent = productName;
        var productGridClose = document.querySelectorAll('.js-product-grid-close');

        if (pageProductForm != null) {
          var productId = document.querySelector('.js-product-id').textContent,
            openElement = document.getElementById(productId);

          openElement.classList.remove('background-white', 'shadow-small', 'hover:shadow-large');
          openElement.querySelector('.fas').classList.remove('fa-angle-right');
          openElement.querySelector('.fas').classList.add('fa-check');
        }

        for (let i = 0; i < productGridClose.length; i++) {
          productGridClose[i].onclick = function() {
            document.getElementById('modal-product-grid-list').remove();
          };
        }
      },
    });
  }
});
