import documentReady from '@assets/js/documentReady';
import { handlerNotification, sendAjaxFromForm, removeProductAjax, init, refreshST, updateCartList } from '../base/cart';
import googleAnalytics from '@assets/js/googleAnalytics';
import seeKitProducts from '../../see-kit-products';

init();
let checkCartList = $('.js-header__cart-total').text();

documentReady(() => {
  seeKitProducts();



  const removeProductAll = document.querySelectorAll('.js-remove-product');
  if (removeProductAll) {
    for (const removeProduct of removeProductAll) {
      removeProduct.addEventListener('click', event => {
        event.preventDefault();
        event.stopPropagation();
        const item = removeProduct.closest('.js-order-by-item');
        googleAnalytics('remove_from_cart', {
          currency: 'BRL',
          items: [
            {
              item_id: item.dataset.code,
              item_name: item.dataset.name,
              price: item.dataset.unitPrice,
              currency: 'BRL',
              quantity: item.dataset.quantity,
            },
          ],
        });

        removeProductAjax(removeProduct.href, removeProduct);
      });
    }
  }

  window.addEventListener('quote-shipping', () => {
    const applyShippingForm = document.querySelector('#postcode-result form');
    if (applyShippingForm) {
      applyShippingForm.onsubmit = function(e) {
        e.preventDefault();
        sendAjaxFromForm(applyShippingForm)
          .then(({ cartlist: cartList }) => {
            refreshST(cartList);

            const resultContainer = document.querySelector('#postcode-result');
            if (resultContainer) {
              resultContainer.classList.add('hidden');
              resultContainer.innerHTML = '';
            }
          })
          .catch(err => console.log(err, err.response));
      };
    }
  });

  const couponForm = document.querySelector('#discount-coupon-form');
  if (couponForm) {
    couponForm.onsubmit = function(e) {
      e.preventDefault();
      sendAjaxFromForm(couponForm).catch(err => console.log(err, err.response));
    };
  }

});

var target = document.querySelector( '.js-header__cart-total' );
var observer = new MutationObserver( handleMutationObserver  );
var config = { childList: true, attributes: true };

function handleMutationObserver( mutations ) {
  mutations.forEach(function(mutation) {
    if (checkCartList !== $('.js-header__cart-total').text()){
      checkCartList == 0 ? location.reload(): updateCartList();
      checkCartList = $('.js-header__cart-total').text();
    }
  });
}
observer.observe( target, config );