const paypalEl = {
  canDisplayPayPal: '#canDisplayPayPalOnBasketPage',
  checkoutAction: '.checkout-action',
  checkoutPayPalWrapper: '.checkout-widget__basket-block',
  checkoutActionWrapper: '.checkout-action__wrapper',
}

export function checkPayPalAvailability(data) {
  const payPalEnabled = data?.paymentInfos?.payPalEnabled;
  const clickAndCollectOnly = data.clickAndCollectOnly;
  const canDisplayPayPal = $(paypalEl.canDisplayPayPal).val() === 'true';
  const payPalInfo = data?.paymentInfos?.payPalPaymentInfo;
  const isPayPalAllowed = payPalEnabled && clickAndCollectOnly && canDisplayPayPal;

  $(paypalEl.checkoutAction).find(paypalEl.checkoutPayPalWrapper).remove();

  if (isPayPalAllowed) {
    $(paypalEl.checkoutAction).each(function () {
      const actionWrapper = $(this).parent(paypalEl.checkoutActionWrapper);
      let buttonId = 'paypal-button-container-content-small';

      if (actionWrapper.hasClass('large')) {
        buttonId = 'paypal-button-container-content'
      }

      if (actionWrapper.hasClass('mounted')) {
        buttonId = 'paypal-button-container-content-mounted'
      }

      $(this).append(paintPayPal(buttonId, payPalInfo));
      if (!Wick.checkLocalEnv) {
        prepareButtons('#' + buttonId);
      }
    })
  }
}

function paintPayPal(idForBtn, info) {
  const isPayPalCustomerAvailable = info.payer && info.id;
  return `
    <div class="checkout-action__section checkout-widget__basket-block">
      <div class="form-row__col-btn pay-pal_container" data-paypal>
        <a class="pay-pal_wrap">
          <div class="buttons-container">
            <div class="paypal-button-container">
              <div class="paypal-button" id=${idForBtn}></div>
            </div>
          </div>
        </a>
        ${isPayPalCustomerAvailable ? paintPayPalCustomerInfo(info) : ''}
      </div>
    </div>
  `
}

function paintPayPalCustomerInfo(info) {
  const removePaymentMethodLink = `checkout/hybrid/remove-payment-method?paymentInfoId=${info.id}&amp;isCartPage=true`

  return `
    <div class="pay-pal_container-email">
      <div class="pay-pal_email-heading">Your PayPal email:</div>
      <div class="pay-pal_email-value">${info.payer}</div>
      <div class="pay-pal_email-link">
          <a href="${removePaymentMethodLink}">Don't use this email</a>
      </div>
    </div>
  `
}
