class MPCardForm{TIMEOUT_TO_WAIT_INIT_CARD_FORM=1e4;constructor(){this.form=null,this.formMounted=!1,this.mpFormId="checkout",this.amount=null,this.onReadyDebounce=null,this.fields=null,this.initCardFormTimeoutReference=null,this.isLoading=!1,this.dispatcherMissingReported=!1,this.sendMelidataTimeToLoadMetric()}async initCardForm(e=this.getAmount()){if(this.amount=e,this.cardNumberFilledValidator=!1,!window.mpSdkInstance){const e=new MercadoPago(wc_mercadopago_custom_checkout_params.public_key,{locale:wc_mercadopago_custom_checkout_params.locale});window.mpSdkInstance=e}return new Promise(((t,o)=>{this.createTimeoutToWaitInitCardForm(o),this.form=window.mpSdkInstance.cardForm({amount:e,iframe:!0,form:this.getCardFormConfig(),callbacks:this.getCardFormCallbacks(t,o)})})).then((()=>{this.clearTimeoutToWaitInitCardForm(),this.sendMetric("MP_CARDFORM_SUCCESS","Security fields loaded","mp_custom_checkout_security_fields_client"),CheckoutPage.verifyCardholderNameOnFocus()})).catch((e=>{this.clearTimeoutToWaitInitCardForm();const t=this.handleCardFormErrors(e);this.sendMetric("MP_CARDFORM_ERROR",t,"mp_custom_checkout_security_fields_client"),console.error("Mercado Pago cardForm error: ",t)}))}createTimeoutToWaitInitCardForm(e=()=>{}){this.initCardFormTimeoutReference=setTimeout((()=>{this.removeLoadSpinner(),e(new Error("INIT_CARD_FORM_TIMEOUT"))}),this.TIMEOUT_TO_WAIT_INIT_CARD_FORM)}clearTimeoutToWaitInitCardForm(){clearTimeout(this.initCardFormTimeoutReference)}getCardFormConfig(){const e={fontSize:"16px",height:"48px",padding:"14px",textAlign:"left",fontFamily:"Inter ",fontWeight:"400",placeholderColor:" #0000008C"},t={src:"https://fonts.googleapis.com/css2?family=Inter"};return{id:this.mpFormId,cardNumber:{id:"form-checkout__cardNumber-container",placeholder:"1234 1234 1234 1234",style:e,customFonts:[t]},cardholderName:{id:"form-checkout__cardholderName",placeholder:wc_mercadopago_custom_checkout_params.placeholders.cardholderName},cardExpirationDate:{id:"form-checkout__expirationDate-container",placeholder:wc_mercadopago_custom_checkout_params.placeholders.cardExpirationDate,mode:"short",style:e,customFonts:[t]},securityCode:{id:"form-checkout__securityCode-container",placeholder:wc_mercadopago_custom_card_form_params.security_code_placeholder_text_3_digits,style:e,customFonts:[t]},identificationType:{id:"form-checkout__identificationType"},identificationNumber:{id:"form-checkout__identificationNumber"},issuer:{id:"form-checkout__issuer",placeholder:wc_mercadopago_custom_checkout_params.placeholders.issuer},installments:{id:"form-checkout__installments",placeholder:wc_mercadopago_custom_checkout_params.placeholders.installments}}}getCardFormCallbacks(e,t){return{onReady:t=>{this.fields=t,this.setupSecureFieldsStylesAndAddListeners(),e()},onFormMounted:t=>{this.formMounted=!0,document.dispatchEvent(new CustomEvent("mp_card_form_mounted")),e(),t&&console.log("Callback to handle the error: creating the CardForm",t)},onFormUnmounted:t=>{this.formMounted=!1,CheckoutPage.clearInputs(),e(),t&&console.log("Callback to handle the error: unmounting the CardForm",t)},onInstallmentsReceived:(e,t)=>{if(e){const t=wc_mercadopago_custom_checkout_params.error_messages;return this.addErrorAlert(t.installments[e.message]??t.default),void console.warn("Installments handling error: ",e)}CheckoutPage.setChangeEventOnInstallments(t)},onCardTokenReceived:e=>{e&&console.error("Token handling error: ",e)},onPaymentMethodsReceived:(e,t)=>{if(e)console.error("Payment methods handling error: ",e);else try{if(t){CheckoutPage.clearInputs();const e=t[0];CheckoutPage.setValueOn("paymentMethodId",e.id),CheckoutPage.setCvvConfig(e.settings[0].security_code),CheckoutPage.setImageCard(e.secure_thumbnail||e.thumbnail);const o=CheckoutPage.loadAdditionalInfo(e.additional_info_needed);CheckoutPage.additionalInfoHandler(o),CheckoutPage.setDisplayOfError("fcCardNumberContainer","remove","mp-error"),CheckoutPage.setDisplayOfInputHelper("mp-card-number","none"),CheckoutPage.setDisplayOfError("mpCardholderNameInputLabel","remove","mp-label-error"),CheckoutPage.setDisplayOfError("mpDocumentInputLabel","remove","mp-label-error"),CheckoutPage.setDisplayOfInputHelper("mp-card-holder-name","none"),CheckoutPage.setDisplayOfInputHelperInfo("mp-card-holder-name","flex"),CheckoutPage.shouldEnableInstallmentsComponent(e.payment_type_id)}else CheckoutPage.setDisplayOfError("fcCardNumberContainer","add","mp-error"),CheckoutPage.setDisplayOfInputHelper("mp-card-number","flex")}catch(e){if(e)return void console.error("Payment methods handling error: ",e);CheckoutPage.setDisplayOfError("fcCardNumberContainer","add","mp-error"),CheckoutPage.setDisplayOfInputHelper("mp-card-number","flex")}},onSubmit:e=>{e.preventDefault()},onValidityChange:(e,t)=>{if("cardNumber"===t&&(this.cardNumberFilledValidator=!0),e){let o=CheckoutPage.getHelperMessage(t),r=wc_mercadopago_custom_checkout_params.input_helper_message[t][e[0].code];o.innerHTML=r||wc_mercadopago_custom_checkout_params.input_helper_message[t].invalid_length,"cardNumber"===t&&("invalid_length"!==e[0].code&&(CheckoutPage.setBackground("fcCardNumberContainer","no-repeat #fff"),CheckoutPage.removeAdditionFields(),CheckoutPage.clearInputs()),CheckoutPage.setDisplayOfInputHelperInfo("mp-card-holder-name","flex"));let a=CheckoutPage.findContainerField(t);return CheckoutPage.setDisplayOfError(a,"add","mp-error"),"cardholderName"===t&&CheckoutPage.verifyCardholderName(),CheckoutPage.setDisplayOfInputHelper(CheckoutPage.inputHelperName(t),"flex")}if("cardholderName"===t&&!CheckoutPage.verifyCardholderName())return;let o=CheckoutPage.findContainerField(t);return CheckoutPage.setDisplayOfError(o,"removed","mp-error"),CheckoutPage.setDisplayOfInputHelper(CheckoutPage.inputHelperName(t),"none")},onError:e=>{CheckoutPage.verifyCardholderName(),e.forEach((e=>(this.removeBlockOverlay(),e.message.includes("timed out")?t(e):e.message.includes("cardNumber")?(CheckoutPage.setDisplayOfError("fcCardNumberContainer","add","mp-error"),CheckoutPage.setDisplayOfInputHelper("mp-card-number","flex")):e.message.includes("cardholderName")?(CheckoutPage.setDisplayOfError("fcCardholderName","add","mp-error"),CheckoutPage.setDisplayOfInputHelperInfo("mp-card-holder-name","none"),CheckoutPage.setDisplayOfError("mpCardholderNameInputLabel","add","mp-label-error"),CheckoutPage.setDisplayOfInputHelper("mp-card-holder-name","flex")):e.message.includes("expirationMonth")||e.message.includes("expirationYear")?(CheckoutPage.setDisplayOfError("fcCardExpirationDateContainer","add","mp-error"),CheckoutPage.setDisplayOfInputHelper("mp-expiration-date","flex")):e.message.includes("securityCode")?(e.message.includes("should be a number")||e.message.includes("should be of length")?CheckoutPage.setDisplayOfInputHelperMessage("mp-security-code",wc_mercadopago_custom_checkout_params.input_helper_message.securityCode.invalid_length):CheckoutPage.setDisplayOfInputHelperMessage("mp-security-code",wc_mercadopago_custom_checkout_params.input_helper_message.securityCode.invalid_type),CheckoutPage.setDisplayOfError("fcSecurityNumberContainer","add","mp-error"),CheckoutPage.setDisplayOfInputHelper("mp-security-code","flex")):e.message.includes("identificationNumber")?(CheckoutPage.setDisplayOfError("fcIdentificationNumberContainer","add","mp-error"),CheckoutPage.setDisplayOfInputHelper("mp-doc-number","flex")):t(e))))}}}scrollToCardForm(){const e=document.querySelector("#mp-checkout-custom-root.mp-checkout-container");e&&e.scrollIntoView({behavior:"smooth"})}getAmount(){const e=document.getElementById("mp-amount");if(!e)return this.amount;const t=parseFloat(e.value.replace(",","."));return String(t)}handleCardFormErrors(e){if(e.length){const t=[];return e.forEach((e=>{t.push(e.description||e.message)})),t.join(",")}return e.description||e.message}sendMetric(e,t,o){void 0!==window.mPmetrics&&window.mPmetrics.push({action:e,label:t,target:o})}isClassicCheckout(){return!!document.querySelector(".payment_method_woo-mercado-pago-custom")}startLoadingOnClassicCheckout(){jQuery("form.checkout")?.block({message:null,overlayCSS:{background:"#fff",opacity:.6}})}stopLoadingOnClassicCheckout(){jQuery("form.checkout")?.unblock()}getMelidataReadyPromise(){return window.melidataReady?window.melidataReady:Promise.reject(new Error("melidataReady is undefined"))}createLoadSpinner(){if(this.isLoading)return;const e=document.querySelector("#mp-checkout-custom-root.mp-checkout-container"),t=document.querySelector(".mp-checkout-custom-load");this.isLoading=!0,e?.classList.add("mp-hidden"),e?.classList.add("mp-display-none"),t?.classList.remove("mp-hidden"),t?.classList.remove("mp-display-none");const o=Date.now(),r=!!window.melidata;this.getMelidataReadyPromise().then((()=>{if(!r){const e=Math.round((Date.now()-o)/10)/100;sendMetric(e,"time in seconds waiting for melidata client at loading start","mp_custom_checkout_melidata_load_start_delay")}document.dispatchEvent(new CustomEvent("mp_super_token_loading_start",{detail:{dateNowInMilliseconds:o}}))})).catch((e=>{sendMetric("MP_MELIDATA_CLIENT_UNDEFINED",`Loading started but melidata client failed to load: ${e?.message||"unknown error"}`,"mp_custom_checkout_melidata_client_undefined")}))}removeLoadSpinner(){const e=document.querySelector(".mp-checkout-custom-load"),t=e&&"none"!==window.getComputedStyle(e).display;if(!this.isLoading&&!t)return;const o=document.querySelector("#mp-checkout-custom-root.mp-checkout-container"),r=document.querySelector(".mp-checkout-custom-load");this.isLoading=!1;window.mpSuperTokenTriggerHandler?window.mpSuperTokenTriggerHandler.isSuperTokenPaymentMethodsLoaded()&&r?.classList.add("mp-hidden"):"function"==typeof sendMetric&&sendMetric("MP_SUPER_TOKEN_TRIGGER_HANDLER_MISSING","removeLoadSpinner","mp_cardform_trigger_handler_missing"),setTimeout((()=>{r?.classList.add("mp-hidden"),r?.classList.add("mp-display-none"),o?.classList.remove("mp-hidden"),o?.classList.remove("mp-display-none")}),800);const a=Date.now(),i=!!window.melidata;this.getMelidataReadyPromise().then((()=>{if(!i){const e=Math.round((Date.now()-a)/10)/100;sendMetric(e,"time in seconds waiting for melidata client at loading end","mp_custom_checkout_melidata_load_end_delay")}document.dispatchEvent(new CustomEvent("mp_super_token_loading_end",{detail:{dateNowInMilliseconds:a}}))})).catch((e=>{sendMetric("MP_MELIDATA_CLIENT_UNDEFINED",`Loading ended but melidata client failed to load: ${e?.message||"unknown error"}`,"mp_custom_checkout_melidata_client_undefined")}))}removeBlockOverlay(){jQuery("form#order_review").length>0&&jQuery(".blockOverlay").css("display","none")}addErrorAlert(e){this.removeElementsByClass("woocommerce-NoticeGroup-checkout"),jQuery(window.mpCheckoutForm).prepend(`\n            <div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">\n                <ul class="woocommerce-error" role="alert">\n                    <li>${e}<li>\n                </ul>\n            </div>\n        `),window.scrollTo(0,0)}removeElementsByClass(e){const t=document.getElementsByClassName(e);for(;t.length>0;)t[0].parentNode.removeChild(t[0])}setupSecureFieldsStylesAndAddListeners(){if(!this.fields)return;"undefined"!=typeof MPCheckoutFieldsDispatcher||"function"!=typeof sendMetric||this.dispatcherMissingReported||(sendMetric("MP_CHECKOUT_FIELDS_DISPATCHER_MISSING","setupSecureFieldsStylesAndAddListeners","mp_checkout_init_error"),this.dispatcherMissingReported=!0);const e=[{field:this.fields.cardNumber,fieldName:"cardNumber",containerId:"form-checkout__cardNumber-container",focusEventName:"card_number_focused",blurEventName:"card_number_filled",validator:()=>this.cardNumberFilledValidator},{field:this.fields.expirationDate,containerId:"form-checkout__expirationDate-container"},{field:this.fields.securityCode,containerId:"form-checkout__securityCode-container"}];for(const t of e)t.field&&"function"==typeof t.field.on&&(t.field.on("focus",(()=>{this.addOrRemoveCssClass(t.containerId,"mp-checkout-custom-card-form-focus","add"),t.focusEventName&&"undefined"!=typeof MPCheckoutFieldsDispatcher&&MPCheckoutFieldsDispatcher.addEventListenerDispatcher(null,"focus",t.focusEventName,{onlyDispatch:!0})})),t.field.on("blur",(()=>{let e=!1;this.addOrRemoveCssClass(t.containerId,"mp-checkout-custom-card-form-focus"),t.validator&&(e="function"==typeof t.validator?t.validator():t.validator),t.blurEventName&&e&&"undefined"!=typeof MPCheckoutFieldsDispatcher&&(MPCheckoutFieldsDispatcher.addEventListenerDispatcher(null,"blur",t.blurEventName,{onlyDispatch:!0}),t.fieldName&&this.updateFieldValidator(t.fieldName))})))}addOrRemoveCssClass(e,t,o="remove"){const r=document.getElementById(e);r?.classList["add"===o?"add":"remove"](t)}updateFieldValidator(e){"cardNumber"===e&&(this.cardNumberFilledValidator=!1)}sendMelidataTimeToLoadMetric(){const e=Date.now(),t=setInterval((()=>{if(window.melidata){clearInterval(t);const o=Date.now();sendMetric((o-e)/1e3,"time in seconds to load melidata client","mp_custom_checkout_melidata_time_to_load")}}),100);setTimeout((()=>{clearInterval(t)}),2e4)}};