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();

  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 );