class MPEventHandler{REMOVE_LOAD_SPINNER_DELAY=500;MAX_ORDER_PAY_RETRIES=5;constructor(e,r){this.cardForm=e,this.threeDSHandler=r,this.triggeredPaymentMethodSelectedEvent=!1,this.mercado_pago_submit=!1,this.hasToken=!1,this.mpFormId="checkout",this.mpSuperTokenTriggerHandler=null,this.mpSuperTokenAuthenticator=null,this.mpSuperTokenPaymentMethods=null,this.mpSuperTokenMetrics=null,this.mpSuperTokenErrorHandler=null,this.loadSpinnerTimeout=null}setSuperTokenDependencies({triggerHandler:e,authenticator:r,paymentMethods:o,metrics:t,errorHandler:n}){e&&r&&o&&t&&n?(this.mpSuperTokenTriggerHandler=e,this.mpSuperTokenAuthenticator=r,this.mpSuperTokenPaymentMethods=o,this.mpSuperTokenMetrics=t,this.mpSuperTokenErrorHandler=n):"function"==typeof sendMetric&&sendMetric("MP_SUPER_TOKEN_DEPENDENCIES_NOT_SET","setSuperTokenDependencies","mp_super_token_init_error")}getSuperTokenDeps(){return this.mpSuperTokenTriggerHandler&&this.mpSuperTokenAuthenticator||!window.mpSuperTokenTriggerHandler||this.setSuperTokenDependencies({triggerHandler:window.mpSuperTokenTriggerHandler,authenticator:window.mpSuperTokenAuthenticator,paymentMethods:window.mpSuperTokenPaymentMethods,metrics:window.mpSuperTokenMetrics,errorHandler:window.mpSuperTokenErrorHandler}),{superTokenTriggerHandler:this.mpSuperTokenTriggerHandler,superTokenAuthenticator:this.mpSuperTokenAuthenticator,superTokenPaymentMethods:this.mpSuperTokenPaymentMethods,superTokenMetrics:this.mpSuperTokenMetrics,superTokenErrorHandler:this.mpSuperTokenErrorHandler}}bindEvents(){jQuery("form.checkout").on("checkout_place_order_woo-mercado-pago-custom",((e,r)=>this.mercadoPagoFormHandler(e,r))),jQuery("body").on("payment_method_selected",this.handlePaymentMethodSelected.bind(this)),jQuery("form#order_review").submit(this.handleOrderReviewSubmit.bind(this)),jQuery(document.body).on("checkout_error",this.handleCheckoutError.bind(this)),jQuery(document).on("updated_checkout",this.handleUpdatedCheckout.bind(this)),jQuery(document).ready((()=>{this.threeDSHandler.set3dsStatusValidationListener(),wc_mercadopago_custom_event_handler_params.is_mobile||this.initCardFormWhenReady()}))}initCardFormWhenReady(){const e=document.querySelector(".mp-checkout-custom-container"),r=document.querySelector("#payment_method_woo-mercado-pago-custom"),o=this.isOrderPayPage();if(r?.checked)if(e){if(!this.cardForm.formMounted)return o?(this.cardForm.createLoadSpinner(),void Promise.resolve(this.cardForm.initCardForm()).finally((()=>this.cardForm.removeLoadSpinner()))):void(null!==e.offsetParent&&this.cardForm.initCardForm())}else o&&this.scheduleOrderPayInitRetry()}scheduleOrderPayInitRetry(){this.orderPayInitRetries=(this.orderPayInitRetries||0)+1,this.orderPayInitRetries>this.MAX_ORDER_PAY_RETRIES||setTimeout((()=>this.initCardFormWhenReady()),300)}isOrderPayPage(){const e=document.body?.classList?.contains("woocommerce-order-pay"),r=!!document.querySelector("form#order_review");return e||r}getCheckoutForm(){return this.isOrderPayPage()?jQuery("form#order_review"):jQuery("form.checkout")}showCheckoutClassicLoader(){this.getCheckoutForm()?.block({message:null,overlayCSS:{background:"#fff",opacity:.6}})}hideCheckoutClassicLoader(){this.getCheckoutForm()?.unblock()}mercadoPagoFormHandler(e,r){this.setMercadoPagoSessionId();const{superTokenPaymentMethods:o,superTokenMetrics:t}=this.getSuperTokenDeps();return o?.hideSuperTokenError(),!!this.mercado_pago_submit||("wallet_button"===jQuery("#mp_checkout_type").val()||("super_token"===jQuery("#mp_checkout_type").val()?(t?.registerClickOnPlaceOrderButton(),this.hasWooCommerceValidationErrors()?!this.isOrderPayPage()||(document.getElementById("order_review").submit(),!1):(this.handleWithSuperTokenSubmit(e,r),!1)):(jQuery("#mp_checkout_type").val("custom"),this.hasWooCommerceValidationErrors()&&this.isOrderPayPage()?(document.getElementById("order_review").submit(),!1):!this.hasToken&&(this.setPayerIdentificationInfo(),this.createToken()))))}async handleWithSuperTokenSubmit(e,r){const{superTokenTriggerHandler:o,superTokenAuthenticator:t,superTokenPaymentMethods:n,superTokenErrorHandler:i}=this.getSuperTokenDeps();try{if(e.preventDefault(),this.showCheckoutClassicLoader(),!n)throw new Error(MPSuperTokenErrorCodes.SUPER_TOKEN_PAYMENT_METHODS_NOT_FOUND);if(!t)throw new Error(MPSuperTokenErrorCodes.SUPER_TOKEN_AUTHENTICATOR_NOT_FOUND);const o=n.getActivePaymentMethod(),i=o&&n.isSelectedPaymentMethodValid();if(!o)throw new Error(MPSuperTokenErrorCodes.SELECT_PAYMENT_METHOD_ERROR);if(!i)throw new Error(MPSuperTokenErrorCodes.SELECT_PAYMENT_METHOD_NOT_VALID);if(!n.validateInstallmentSelection())return this.cardForm.removeLoadSpinner(),void this.hideCheckoutClassicLoader();this.isOrderPayPage()&&n.unmountCardForm(),await n.updateSecurityCode(),await t.authorizePayment(o.token),this.mercado_pago_submit=!0,t?.setSuperTokenValidation(!0),this.isOrderPayPage()?this.handle3dsPayOrderFormSubmission():r.$checkout_form.trigger("submit")}catch(e){if(e?.message===MPSuperTokenErrorCodes.SELECT_PAYMENT_METHOD_NOT_VALID)return i?.handleError(e),this.cardForm.removeLoadSpinner(),void this.hideCheckoutClassicLoader();const r=[MPSuperTokenErrorCodes.UPDATE_SECURITY_CODE_ERROR,MPSuperTokenErrorCodes.AUTHORIZE_PAYMENT_METHOD_ERROR,MPSuperTokenErrorCodes.AUTHORIZE_PAYMENT_METHOD_USER_CANCELLED];o?.resetSuperTokenOnError(r.includes(e?.message)),o?.setLastException(e),t?.setSuperTokenValidation(!1)}}hasWooCommerceValidationErrors(){if("function"==typeof window.hasWooCommerceValidationErrors)try{return window.hasWooCommerceValidationErrors()}catch(e){return"function"==typeof sendMetric&&sendMetric("MP_CUSTOM_CHECKOUT_VALIDATION_CDN_FALLBACK",e?.message||e?.name||"threw an error","mp_custom_checkout_validation_cdn_fallback"),!1}return"function"==typeof sendMetric&&sendMetric("MP_CUSTOM_CHECKOUT_VALIDATION_CDN_FALLBACK","hasWooCommerceValidationErrors not available","mp_custom_checkout_validation_cdn_fallback"),!1}createToken(){if("undefined"!=typeof CheckoutPage&&"function"==typeof CheckoutPage.installmentsWasSelected&&!CheckoutPage.installmentsWasSelected())return CheckoutPage.setInstallmentsErrorState(!0),CheckoutPage.scrollToCheckoutCustomContainer(),this.cardForm.removeLoadSpinner(),!1;return(window.callSdkWithMetrics||(e=>e()))((()=>this.cardForm.form.createCardToken()),"createCardToken").then((e=>{if(!e.token)throw new Error("cardToken is empty");if(!this.hasToken)return document.querySelector("#cardTokenId").value=e.token,this.mercado_pago_submit=!0,this.hasToken=!0,"order_review"===this.mpFormId?(this.handle3dsPayOrderFormSubmission(),!1):void jQuery("form.checkout").submit()})).catch((e=>{console.warn("Token creation error: ",e),this.cardForm.scrollToCardForm(),this.cardForm.removeLoadSpinner()})),!1}setMercadoPagoSessionId(){if("undefined"!=typeof MP_DEVICE_SESSION_ID&&MP_DEVICE_SESSION_ID)try{document.querySelector("#mpCardSessionId").value=MP_DEVICE_SESSION_ID}catch(e){console.warn(e)}}isCheckoutCustomPaymentMethodSelected(){const e=document.getElementById("payment_method_woo-mercado-pago-custom")||document.querySelector("input[value=woo-mercado-pago-custom]");return e&&e.checked}handlePaymentMethodSelected(){if(this.isCheckoutCustomPaymentMethodSelected()){if(this.isOrderPayPage())return this.onSelectCheckoutCustomInOrderPayPage()}else{this.cardForm.formMounted&&this.cardForm.form.unmount(),clearTimeout(this.loadSpinnerTimeout);const{superTokenTriggerHandler:e,superTokenPaymentMethods:r}=this.getSuperTokenDeps();e?.isSuperTokenPaymentMethodsLoaded()?r?.getPaymentMethodsListElement()?.style.setProperty("display","none","important"):e?.isFetchingPaymentMethods&&e.cancelLoad()}}handleOrderReviewSubmit(e){if(this.isCheckoutCustomPaymentMethodSelected())return this.mercadoPagoFormHandler(e);this.cardForm.formMounted&&this.cardForm.form.unmount()}handleCheckoutError(){this.hasToken=!1,this.mercado_pago_submit=!1,this.cardForm.removeLoadSpinner();const{superTokenTriggerHandler:e}=this.getSuperTokenDeps();e?.resetSuperTokenOnError(!0)}handleUpdatedCheckout(){if(this.isCheckoutCustomPaymentMethodSelected()){clearTimeout(this.loadSpinnerTimeout),this.cardForm.createLoadSpinner();const e=this.cardForm.getAmount(),r=this.cardForm.amount,o=[],{superTokenTriggerHandler:t}=this.getSuperTokenDeps();t&&o.push(t.loadSuperToken(e));this.cardForm.formMounted&&["form-checkout__cardNumber-container","form-checkout__expirationDate-container","form-checkout__securityCode-container"].every((e=>{const r=document.getElementById(e);return!!r&&!r.querySelector("iframe")}))?(this.cardForm.form.unmount(),this.cardForm.formMounted=!1):this.cardForm.formMounted&&e!==r&&this.cardForm.form.unmount(),this.cardForm.formMounted||o.push(this.cardForm.initCardForm()),Promise.all(o).finally((()=>{this.loadSpinnerTimeout=setTimeout((()=>this.cardForm.removeLoadSpinner()),this.REMOVE_LOAD_SPINNER_DELAY)}))}}handle3dsPayOrderFormSubmission(){var e=jQuery("#order_review").serialize();jQuery.post("#",e).done((e=>{if(e.three_ds_flow)this.threeDSHandler.load3DSFlow(e.last_four_digits);else if("success"===e.result&&e.redirect)window.location.href=e.redirect;else{if("fail"===e.result){jQuery("#order_review .woocommerce-error, #order_review .woocommerce-message").remove(),jQuery("#order_review").prepend('<div class="woocommerce-error">'+e.messages+"</div>");const r=document.querySelector("#order_review .woocommerce-error");return r&&r.scrollIntoView({behavior:"smooth"}),this.cardForm.removeBlockOverlay(),this.cardForm.removeLoadSpinner(),this.cardForm.form.unmount(),this.cardForm.initCardForm(),this.hasToken=!1,void(this.mercado_pago_submit=!1)}window.location.reload()}})).error((()=>{window.location.reload()}))}setPayerIdentificationInfo(){[{selector:"#form-checkout__identificationType",hiddenInputId:"#payerDocType"},{selector:"#form-checkout__identificationNumber",hiddenInputId:"#payerDocNumber"}].forEach((({selector:e,hiddenInputId:r})=>{const o=document.querySelector(e),t=document.querySelector(r);o&&t&&o.value&&(t.value=o.value)}))}onSelectCheckoutCustomInOrderPayPage(){let e=0;this.cardForm.createLoadSpinner();const r=setInterval((()=>{const{superTokenTriggerHandler:o}=this.getSuperTokenDeps();if(++e<100&&!o)return;clearInterval(r);const t=this.cardForm.getAmount(),n=[];return o&&n.push(o.loadSuperToken(t)),this.cardForm.formMounted||n.push(this.cardForm.initCardForm()),Promise.all(n).finally((()=>{setTimeout((()=>this.cardForm.removeLoadSpinner()),this.REMOVE_LOAD_SPINNER_DELAY)}))}),100)}};