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

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

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

  document.querySelector('#continue_buying').addEventListener('click', () => {
    const prevHostname = document.referrer ? new URL(document.referrer) : "";
    const currentHostname = new URL(window.location.href);

    if(prevHostname.hostname != currentHostname.hostname){
      return window.location.href = BASE_URL;
    } 

    window.location.href = document.referrer;
  })

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