/**
 *
 * to check if current browser support ApplePay
 * @param {boolean}
 * if @returns {false} attach error message Your Device Dose Not Support ApplePay
 */
if (!window.ApplePaySession && dataObj.payment_brands.includes('APPLEPAY')) {
    jQuery('.woocommerce-notices-wrapper')
        .append(`<ul class="woocommerce-error" role="alert"><li> ${dataObj.is_arabic ? 'جهازك او متصفحك لا يدعم الدفع عن طريق ابل' : 'Your Device Or Browser Dose Not Support ApplePay'} </li></ul>`)
}

/**
 * initiate wpwlOptions
 */


function updateHyperpayCheckout(extraData) {
    shouldProceed = false;
    jQuery.ajax({
        url: '/?wc-ajax=recurring_update_checkout',
        type: "POST",
        dataType: "json",
        async: false,
        data: {
            selectedCard: jQuery('input[name="registrationId"]:checked').val(),
            checkoutId: dataObj.checkoutId,
            orderId: dataObj.orderId,
            ...extraData,
            _wpnonce: dataObj.hyperpay_update_nonce,

        },
        success: function (response) {
            if (response && response.success) {
                shouldProceed = true;
            } else {
                alert("Something went wrong, please try again.");
                shouldProceed = false;
            }
        },
        error: function (xhr, status, error) {
            alert("Server error. Please try again later.");
            shouldProceed = false;
        }
    });
    return shouldProceed;
}

var wpwlOptions = {

    registrations: {requireCvv: true},
    onReady: function () {


        jQuery('.wpwl-form-virtualAccount-STC_PAY .wpwl-wrapper-radio-qrcode').hide();
        jQuery('.wpwl-form-virtualAccount-STC_PAY .wpwl-wrapper-radio-mobile').hide();
        jQuery('.wpwl-form-virtualAccount-STC_PAY .wpwl-group-paymentMode').hide();
        jQuery('.wpwl-form-virtualAccount-STC_PAY .wpwl-group-mobilePhone').show();
        jQuery('.wpwl-form-virtualAccount-STC_PAY .wpwl-wrapper-radio-mobile .wpwl-control-radio-mobile').attr('checked', true);
        jQuery('.wpwl-form-virtualAccount-STC_PAY .wpwl-wrapper-radio-mobile .wpwl-control-radio-mobile').trigger('click');
        jQuery(".wpwl-form.wpwl-form-registrations.wpwl-clearfix").last().find(".wpwl-button.wpwl-button-pay").remove();
        jQuery(".wpwl-form.wpwl-form-registrations.wpwl-clearfix").last().remove();
        jQuery('.wpwl-group.wpwl-group-brand').hide() ;

        let element = jQuery("" +
            "<div class=\"wpwl-group wpwl-group-registration show_new_card_form_div wpwl-clearfix \">        " +
            "<label class=\"wpwl-registration\">            " +
            "<div class=\"\">                " +
            "<input value='' type=\"radio\" name=\"registrationId\" id='show_new_card_form' >  <div class='add_new_card_brand'>+ Add New Card            </div></div>" +
            "            </div> </div>        </label>    </div>");

        // Find the last element of the target group
        let target = jQuery(".wpwl-group.wpwl-group-registration.wpwl-has-cvv.wpwl-clearfix").last();


        // Move the element after the target

        if (element.length && target.length) {
            element.insertAfter(target);
        }

        var createRegistrationHtml = `
  <div class="customLabel">
    <input 
      type="checkbox" 
      aria-required="true" 
      id="hyperpay_save_card" 
      value="true"
      ${dataObj.is_subscription == 'yes' ? 'checked disabled' : ''}
    />
    <label for="hyperpay_save_card">
        ${dataObj.is_subscription == 'yes' ?
            dataObj.is_arabic ? 'حفظ بيانات بطاقتي للدفع في المستقبل (مطلوب للاشتراكات)' : 'Save my card details for future payments (required for subscriptions)'
            :
            dataObj.is_arabic ? 'حفظ بيانات بطاقتي للدفع في المستقبل ' : 'Save my card details for future payments'
        }
    </label>
  </div>
  <div class="customInput"></div>`;
        jQuery('input[name="registrationId"]').on("change", function () {
            if (jQuery("#show_new_card_form").is(':checked')) {
                jQuery(".wpwl-wrapper-registration-cvv iframe").css("visibility", "hidden").css("height", "0");
                jQuery(".wpwl-group-registration").removeClass("wpwl-selected");
                jQuery(this).closest(".wpwl-group-registration").addClass("wpwl-selected");
                jQuery(".wpwl-container.wpwl-container-card.wpwl-clearfix").show();
                jQuery(".wpwl-form.wpwl-form-registrations.wpwl-clearfix").find(".wpwl-button.wpwl-button-pay").last().hide();
            } else {
                jQuery(".wpwl-container.wpwl-container-card.wpwl-clearfix").hide();
                jQuery(this).closest(".wpwl-group-registration").removeClass("wpwl-selected");
                jQuery(".wpwl-form.wpwl-form-registrations.wpwl-clearfix").find(".wpwl-button.wpwl-button-pay").last().show();
            }
        })
        jQuery('form.wpwl-form-card').find('.wpwl-button').before(createRegistrationHtml);

    },
    onBeforeSubmitOneClickCard: function (e) {
        return updateHyperpayCheckout({createRegistration: "false"});
    },
      onBlurCardNumber: function (isValid) {
        let paymentBrand = this.$form.find('.wpwl-control-brand').val();
        if (dataObj.id != 'hyperpay_mada' && paymentBrand == "MADA") {
            setTimeout(function () {
                jQuery('.wpwl-hint-cardNumberError').remove();
                jQuery('.wpwl-control-cardNumber').removeClass('wpwl-has-error');
                jQuery('.wpwl-control-cardNumber').addClass('wpwl-has-error').after('<div class="wpwl-hint wpwl-hint-cardNumberError">mada card is not allowed, please choose mada debit card from the payment options</div>');
                jQuery('.wpwl-button-pay').prop('disabled', true);
            }, 5);
        }
    },

    onBeforeSubmitCard: function (e) {
        let createRegistration = jQuery("#hyperpay_save_card").is(":checked")
        return updateHyperpayCheckout({createRegistration})
    },
    style: dataObj.style, // <== this style comes from settings page of gateways
    paymentTarget: "_top",
    locale: dataObj.is_arabic ? 'ar' : 'en',
    registrations: {
        hideInitialPaymentForms: true,
        requireCvv: "true"
    },
    browser: {
        threeDChallengeWindow: 5
    }


}

if (dataObj.supported_network) {
    wpwlOptions.applePay = {
        supportedNetworks: dataObj.supported_network
    }
}

