if(!customElements.get("shopping-assistance")){class e extends HTMLElement{constructor(){super(),this.uniqueSuffix="shopping-assistance"+Math.random().toString(36).substr(2,9),this.classList.add(this.uniqueSuffix),this.marketplaces=[],this.contanerClass="", this.defaultStyles=`\n .${this.uniqueSuffix} .spa-tab {\n display: flex;\n flex-direction: column;\n align-items: start;\n display:none;\n }\n .${this.uniqueSuffix} .no-select {\n user-select: none;\n }\n .${this.uniqueSuffix} .shpa-item-container{\n display: flex;\n margin-bottom: 10px;\n flex-direction: column;\n flex: 100% 0 0;\n width: 100%;\n margin-bottom: 10px; \n background-color: #ffffff0d;\n }\n .${this.uniqueSuffix} .shpa-item-label{\n padding-bottom: 3px;\n line-height: 36px;\n color: #333; \n display: flex;\n justify-content: flex-start;\n }\n .${this.uniqueSuffix} .spa-tab .focused label {\n color: #00afd6;\n }\n .${this.uniqueSuffix} .spa-tab .shap-item-input {\n display: flex;\n justify-content: space-between;\n padding: 6px;\n font-size: 1.2rem;\n border: 1px solid #ccc;\n border-radius: 5px;\n box-shadow: none;\n background-color: transparent;\n }\n .${this.uniqueSuffix} .spa-tab input {\n width: 100%;\n flex: 100% 0 1;\n font-size: 1.2rem;\n background: transparent !important;\n border: none !important;\n box-shadow: none !important;\n display: flex;\n outline: none;\n }\n .${this.uniqueSuffix} .comerce-btn,\n .${this.uniqueSuffix} .comerce-list-btn,\n .${this.uniqueSuffix} .qrstart-btn {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 10px;\n font-size: 1.2rem;\n border: 1px solid #ccc;\n border-radius: 5px;\n box-shadow: none;\n background-color: transparent;\n }\n .${this.uniqueSuffix} .comerce-btn .mkbeta{\n padding: 2px 8px;\n font-size: 10px;\n float: right;\n position: absolute;\n right: -5px;\n margin-top: -3px;\n border: #034c5d 2px solid;\n }\n .${this.uniqueSuffix} .recipient-btn {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 10px;\n font-size: 1.2rem;\n border: 1px solid #ccc;\n border-radius: 5px;\n box-shadow: none;\n background-color: transparent;\n }\n .${this.uniqueSuffix} .comerce-logo {\n background-size: contain;\n background-repeat: no-repeat;\n background-position: center;\n min-width: 60px;\n width: 60px;\n height: 60px;\n border-radius: 50%;\n background-color: #034c5d;\n }\n .${this.uniqueSuffix} .marketplace-fees{ margin-left: -6px;font-size: 0.8rem;}\n .${this.uniqueSuffix} .comerce-logo-small {\n background-size: contain;\n background-repeat: no-repeat;\n background-position: center;\n width: 20px;\n height: 20px;\n border-radius: 50%;\n background-color: #fff;\n display:inline-block;\n }\n .${this.uniqueSuffix} .item-list-container {\n display: flex;\n margin-bottom: 10px;\n flex-direction: column;\n flex: 100% 0 0;\n width: 100%;\n }\n .${this.uniqueSuffix} .btn-tab {\n color:white;\n text-transform: uppercase;\n }\n .${this.uniqueSuffix} .btn-tab.selected {\n color:#80e3ff;\n font-weight: bold;\n background: #005f75;\n }\n .${this.uniqueSuffix} .btn-tab.selected:after {\n content: " ";\n display: block;\n background: #005f75;\n width: 10px;\n height: 10px;\n transform: rotate(45deg);\n z-index: 0;\n position: absolute;\n left: 0;\n right: 0;\n margin: auto;\n top: 30px;\n }\n .${this.uniqueSuffix} .market-quotation{\n border-color: #43b6d7 !important;\n background: #125a6d !important;\n }\n .${this.uniqueSuffix} .witing-price{\n display: none;\n }\n .${this.uniqueSuffix} .spa-tab.selected {\n display:flex;\n } \n .${this.uniqueSuffix} .shpa-item-url-help {\n color: #f00;\n font-size: 0.8rem;\n }\n .${this.uniqueSuffix} .shpa-item-instructions {\n background: #0000000d;\n }\n #${this.uniqueSuffix}recipient-state,\n #${this.uniqueSuffix}recipient-country\n {\n width: 100%;\n background: transparent;\n border: none; \n outline: none;\n }\n \n #${this.uniqueSuffix} btn-assistance-tab {\n background: #fff;\n color: #333;\n }\n #${this.uniqueSuffix}-container .progress-risk{\n position: absolute;\n background: #0c586a;\n height: 18px;\n width: 18px;\n top: 0;\n bottom: 0;\n margin-top: 24px;\n border: 2px solid #0e6e84;\n border-radius: 50%;\n }\n #${this.uniqueSuffix}-container .prod-thumbnail{\n display: inline-block;\n width: 40px;\n height: 40px;\n background-size: cover;\n background-repeat: no-repeat;\n background-position: center;\n border-radius: 5px;\n margin-right: 5px;\n }\n #${this.uniqueSuffix}-container .swipe-container {\n position: relative;\n overflow: hidden;\n width: 100%;\n height: 150px;\n border-radius: 5px; \n margin-bottom: 4px;\n border: 1px solid #56c6e6;\n }\n #${this.uniqueSuffix}-container .swipeable-button {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n color: white;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: transform 0.3s ease; \n z-index: 1;\n border:none !important;\n }\n #${this.uniqueSuffix}-container .url-cleaner button { padding-top: 4px !important;padding-bottom: 4px !important;background: transparent !important;box-shadow: none !important;border: none !important;padding-left: 10px !important;padding-right: 10px !important;}\n #${this.uniqueSuffix}-container .url-cleaner button i{ font-size: 20px;color: #56c6e6;}\n #${this.uniqueSuffix}-container .swipeable-menu {\n position: absolute;\n right: -100%; \n top: 0;\n width: 100%;\n height: 100%;\n background-color: #024c5d ;\n border: 1px solid #56c6e6 !important;\n display: flex;\n border-radius: 5px;\n transition: right 0.3s ease;\n z-index: 0;\n flex-wrap: wrap;\n align-content: center;\n justify-content: center;\n align-items: center;\n }\n .bg-dark .btn.btn-outline-danger{\n border: 1px solid #ff9faf !important;\n color: #ff91a3 !important;\n }\n .bg-danger-light{\n background-color: #db717180 !important;\n }\n .quotation-note { \n color: white;\n font-size: 1rem;\n background: #0a7088;\n }\n .shpa-check-points-item h5{\n cursor: pointer;\n } \n .shpa-check-points-item.collapsed .shpa-check-points-item-content{\n display:none;\n } \n .shpa-check-points-item .mdi-chevron-right{\n display:none;\n } \n .shpa-check-points-item.collapsed .mdi-chevron-right{\n display:inline;\n }\n .shpa-check-points-item.collapsed .mdi-chevron-down{\n display:none;\n }\n #${this.uniqueSuffix}-overlay {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: rgb(0 0 0 / 52%); \n pointer-events: none; \n } \n #${this.uniqueSuffix}-overlay::before {\n content: '';\n position: absolute;\n top: 50%;\n left: 50%;\n width: 200px; \n height: 200px;\n transform: translate(-50%, -50%);\n background-color: #e1d4d433;\n border: 2px solid #56c6e6;\n box-sizing: border-box;\n border-radius: 8px;\n }\n #${this.uniqueSuffix}-videoContainer {\n position: relative;\n overflow: hidden;\n display: inline-block;\n border-radius: 4px;\n border: 1px solid #56c6e6;\n width: 100%; \n } \n #${this.uniqueSuffix}-recipient-container,\n #${this.uniqueSuffix}-discliamer-container{\n flex-direction: column;\n }\n #${this.uniqueSuffix}-pickup-containe .pickup-item{\n background: #02637a !important;\n }\n #${this.uniqueSuffix}-pickup-container .pickup-item.selected{\n border-left: 10px solid #56c6e6 !important;\n background: #043b48 !important;\n }\n .generalinstructions::placeholder{color:#70cae5;opacity:.8;}\n .shpa-step1,\n .shpa-step2,\n .shpa-step3,\n .shpa-step4{display:none !important; }\n .shpa-current-step-1 .shpa-step1,\n .shpa-current-step-2 .shpa-step2,\n .shpa-current-step-3 .shpa-step3,\n .shpa-current-step-4 .shpa-step4{display:flex !important; flex-direction: column; }\n .shpa-current-step-1 .shpa-step1.row,\n .shpa-current-step-2 .shpa-step2.row,\n .shpa-current-step-3 .shpa-step3.row,\n .shpa-current-step-4 .shpa-step4.row\n {\n flex-direction: row;\n }\n @media (max-width: 420px){\n .shpa-checkpoint-step{\n max-width:54px;\n font-size:10px;\n }\n }\n #${this.uniqueSuffix}-orders .toggle-show.custom-switch {\n padding-left: 2.25rem\n }\n\n #${this.uniqueSuffix}-orders .toggle-show.custom-switch .custom-control-label::before {\n left: -2.25rem;\n top: 0;\n pointer-events: all;\n width: 50px;\n height: 30px;\n border-radius: 30px;\n } \n #${this.uniqueSuffix}-orders .toggle-show.custom-switch .custom-control-label::after {\n position: absolute;\n top: 2px;\n left: -34px;\n display: block;\n width: 26px !important;\n height: 26px !important;\n border-radius: 50% !important;\n content: "\\F209";\n text-align: center;\n background: no-repeat 50%/50% 50%;\n font-family: "Material Design Icons";\n font-size: 18px;\n color: #fff;\n background: #425e76;\n }\n\n #${this.uniqueSuffix}-orders .toggle-show.custom-switch .custom-control-input:checked ~ .custom-control-label::after {\n left: -26px;\n content: "\\F208";\n color: #56c6e6;\n text-align: center;\n } \n #${this.uniqueSuffix}-orders .toggle-show .custom-control-input:checked ~ .custom-control-label::before {\n border-color: #43b6d7;\n background-color: #56c6e6;\n } \n #${this.uniqueSuffix}-orders .toggle-show .custom-control-input:focus:not(:checked) ~ .custom-control-label::before {\n border-color: #56c6e6;\n }\n #${this.uniqueSuffix}-details-container fieldset .header-accordion .mdi-chevron-right{\n display:none;\n }\n #${this.uniqueSuffix}-details-container fieldset.collapsed {\n border: 0 none !important;\n padding-top: 0 !important;\n padding-bottom: 0 !important;\n margin-bottom: 0 !important;\n }\n #${this.uniqueSuffix}-details-container fieldset.collapsed .header-accordion .mdi-chevron-right{\n display:inline;\n }\n #${this.uniqueSuffix}-details-container fieldset.collapsed .header-accordion .mdi-chevron-down{\n display:none; \n }\n #${this.uniqueSuffix}-details-container fieldset.collapsed .header-accordion{\n border-color:#017996 !important;\n }\n #${this.uniqueSuffix}-details-container fieldset.collapsed div.content-accordion{\n display:none !important;\n } \n #${this.uniqueSuffix}-orders .toggle-show.custom-switch .custom-control-input:disabled:checked ~ .custom-control-label::before {\n background-color: rgb(63 89 114);\n } \n #${this.uniqueSuffix}-orders .toggle-show.custom-switch .custom-control-input:disabled ~ .custom-control-label::after {\n content: "\\F4E6";\n text-align: center;\n color: #9a9a9a;\n background: transparent;\n -webkit-animation: rotating 2s linear infinite;\n -moz-animation: rotating 2s linear infinite;\n -ms-animation: rotating 2s linear infinite;\n -o-animation: rotating 2s linear infinite;\n animation: rotating 2s linear infinite;\n }\n #${this.uniqueSuffix}-orders .pg-btn{\n transform: translateY(0px) !important;\n }\n `, this.overrideStyles=null,this.importFromBrowserExtension=!1,this.i18n={},this.onStep=e=>{},this.onRefreshStart=()=>{},this.onRefreshEnd=()=>{},this.onUnderMaintenace=()=>{},this.onCalculate=()=>{},this.onValidation=()=>{},this.data={},this._step=1,this.stepCache={}}prev(){this._step>1&&(this._step--,this.innerHTML=this.stepCache[`s${this._step}`].html,this.step(this._step,this.stepCache[`s${this._step}`].data))}next(){this._step \n
\n ${this.trans("Espere mientras cargamos los comercios disponibles")}....\n `,"function"==typeof this.onRefreshStart&&this.onRefreshStart(),this.fetchMarketpplaces().then((t=>{this.marketplaces=t,this.render(),e&&e.products&&(this.startData=e,this.startData.importFromBrowserExtension&&(this.importFromBrowserExtension=this.startData.importFromBrowserExtension),this.choiceComerce=this.marketplaces.find((t=>t.slug==e.marketplace)),this.step(2,this.choiceComerce),this.data={},e.products.forEach((e=>{this.addItemUI(e)}))),"function"==typeof this.onRefreshEnd&&this.onRefreshEnd() })).catch((e=>{this.innerHTML=`
\n \n
\n \n
\n
`,this.querySelector(".refresh-btn").addEventListener("click",(()=>{ this.startData=null,this.refresh()})),"function"==typeof this.onRefreshEnd&&this.onRefreshEnd()})),this.step(1,this.marketplaces)}render(e){let t="";if(this.overrideStyles)for(let e in this.overrideStyles){let i=[];for(let t in this.overrideStyles[e])i.push(`${t}:${this.overrideStyles[e][t]};`);t+=`.${this.uniqueSuffix} ${e} {${i.join("")}}`}const i=[];this.marketplaces.forEach((e=>{const t=0==e.percentFee+e.fixFee+e.fixMinimum ;i.push(`\n `) })), this.innerHTML=`\n \n \n
\n
\n \n \n
\n
\n
\n
${this.trans("¿Cómo te gustaría iniciar tu compra?")}
\n \n \n
\n \n \n\n
\n
\n
\n \n

${this.trans("No tienes pedidos todavía.")}

\n
\n
\n
\n
\n
\n `, this.tabContainer=this.querySelector(`#${this.uniqueSuffix}-tab-container`),this.detailContainer=this.querySelector(`#${this.uniqueSuffix}-details-container`),this.assistanceContainer=this.querySelector(`#${this.uniqueSuffix}-container`),this.ordersContainer=this.querySelector(`#${this.uniqueSuffix}-orders`),this.assistanceTabBtn=this.querySelector(".btn-assistance-tab"),this.ordersTabBtn=this.querySelector(".btn-order-tab"),this.assistanceTabBtn.addEventListener("click",(()=>{this.assistanceTabBtn.classList.add("selected"),this.ordersTabBtn.classList.remove("selected"),this.assistanceContainer.classList.add("selected"),this.ordersContainer.classList.remove("selected")})),this.ordersTabBtn.addEventListener("click",(()=>{this.assistanceTabBtn.classList.remove("selected"),this.ordersTabBtn.classList.add("selected"),this.assistanceContainer.classList.remove("selected"),this.ordersContainer.classList.add("selected"),this.orderHistoryUI()})), this.assistanceContainer.querySelector(".comerce-list-btn").addEventListener("click",(()=>{this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-qr`).style.display="none",this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-mode`).style.display="none",this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-marketplaces`).style.display="block"})),this.assistanceContainer.querySelectorAll(".qrstart-btn").forEach((e=>e.addEventListener("click",(()=>{this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-qr-message`).innerHTML="",this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-qr`).style.display="block",this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-mode`).style.display="none",this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-marketplaces`).style.display="none" ;const e=this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-video`),t=this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-canvas`),i=t.getContext("2d");navigator.mediaDevices.getUserMedia({video:{facingMode:"environment"}}).then((n=>{this.stream=n,e.srcObject=n,e.addEventListener("loadedmetadata",(()=>{e.play(),t.width=e.videoWidth,t.height=e.videoHeight,this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-videoContainer`).style.height=e.videoHeight,e.play(),this.stopCamera=()=>{this.stream&&(this.stream.getTracks().forEach((e=>e.stop())),e.srcObject=null,this.stream=!1)}})),e.addEventListener("play",(()=>{const n=()=>{if(e.paused||e.ended)return;t.width=e.videoWidth,t.height=e.videoHeight,i.drawImage(e,0,0,t.width,t.height);const s=i.getImageData(0,0,t.width,t.height),a=jsQR(s.data,t.width,t.height);if(a&&(a.data??"").trim().length>1){ if(/shpa:\w+/.test(a.data))return this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-qr-message`).innerHTML='',fetch("/rest/v1/shpa/seed/"+a.data.split("shpa:").pop()).then((e=>e.json())).then((e=>{this.stopCamera&&this.stopCamera(),this.importFromBrowserExtension=!0,this.refresh(e),setTimeout((()=>this.validateForm()),100)})).catch((e=>{this.stopCamera&&this.stopCamera(),this.assistanceContainer.querySelector(".comerce-list-btn").click(),window.alertModal(this.trans("Ups!"),`${this.trans("El código QR escaneado no es válido.")}`)}));this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-qr-message`).innerHTML=``}requestAnimationFrame(n)};requestAnimationFrame(n)}))})).catch((e=>{this.stopCamera&&this.stopCamera(),this.assistanceContainer.querySelector(".comerce-list-btn").click()}))})))), this.assistanceContainer.querySelector(".cancel-qr-btn").addEventListener("click",(()=>{this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-qr`).style.display="none",this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-mode`).style.display="block",this.assistanceContainer.querySelector(`#${this.uniqueSuffix}-choice-marketplaces`).style.display="none",this.stopCamera&&this.stopCamera()})),this.assistanceContainer.querySelectorAll("button.comerce-btn").forEach((e=>e.addEventListener("click",(e=>{let t=e.target;if("BUTTON"!=t.tagName.toUpperCase()&&(t=t.parentElement),"BUTTON"!=t.tagName.toUpperCase()&&(t=t.parentElement),this.choiceComerce=this.marketplaces.find((e=>e.slug==t.getAttribute("slug"))),"y"==t.getAttribute("urlscrapp"))this.addItemUI(),this.step(2,this.choiceComerce);else{ const e=this.isMobile()?this.isAndroid()?"https://remesita.com/ayuda/compra-asistida-en-remesita-18/como-instalar-la-extension-compra-asistida-con-srm-para-android-163.html":"https://remesita.com/ayuda/compra-asistida-en-remesita-18/como-instalar-la-extension-compra-asistida-con-srm-para-iphone-166.html":"https://remesita.com/ayuda/compra-asistida-en-remesita-18/como-instalar-la-extension-compra-asistida-con-srm-para-pc-168.html";window.alertModal(this.trans("Atención"),`${this.trans("Para importar tus productos, utiliza la extensión del navegador y transfiere los datos directamente desde la página oficial de _MARKETPLACE_.",{_MARKETPLACE_:t.getAttribute("mkname")})} \n ${this.trans("Descubre cómo se hace dando click aquí!")}`)}})))),this.checkForExtensionAndSuggestInstall(),"function"==typeof e&&e(),document.dispatchEvent(new CustomEvent("shpaReady"))}createApiUrl(e){ return`https://${"dev"==($('meta[name="app-env"]')?.attr("content")??"")?"dev-api":"api"}.remesita.com/rest/v1/${e}`}isChromeExtensionInstalled(){const e=document.querySelector('meta[name="shpa-extension-installed"]');return e&&"true"===e.content}isMobile(){return/Mobile|Android|iP(ad|od|hone)/.test(window.navigator.userAgent)}isAndroid(){return/Android/i.test(navigator.userAgent)}isiOS(){return/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream}isChromiumBased(){const e=window.navigator.userAgent;return e.includes("Chrome")||e.includes("Chromium")}getExtenstionLink(){return"https://chromewebstore.google.com/detail/compra-asistida-con-srm/acopglmpkeanapgdhhbnbhggbjagnhem?authuser=0&hl=es"}checkForExtensionAndSuggestInstall(){let e=null ;if(!document.querySelector('meta[name="shpa-extension-installed"]')&&!this.querySelector(`#${this.uniqueSuffix}-suggestion`)&&(e=this.isChromiumBased()?this.isMobile()?this.trans('Para mejorar tu experiencia usa el navegador _BROW_ con Nuestra extensión.',{_EXTENSIONLINK_:this.getExtenstionLink(),_BROWSER_LINK_:this.isiOS()?"https://apps.apple.com/app/id1484498200":"https://play.google.com/store/apps/details?id=com.kiwibrowser.browser",_BROW_:this.isiOS()?"Orion Browser":"Kiwi Browser"})+" "+this.trans("Así podrás importar tus carritos de compra automáticamente."):this.trans('Para mejorar tu experiencia instala Nuestra extensión de Chrome.',{_EXTENSIONLINK_:this.getExtenstionLink() })+" "+this.trans("Así podrás importar tus carritos de compra automáticamente."):this.isMobile()?this.trans('Para mejorar tu experiencia lo recomendable es que instales el navegador _BROW_ y Nuestra extensión.',{_EXTENSIONLINK_:this.getExtenstionLink(),_BROWSER_LINK_:this.isiOS()?"https://apps.apple.com/app/id1484498200":"https://play.google.com/store/apps/details?id=com.kiwibrowser.browser",_BROW_:this.isiOS()?"Orion Browser":"Kiwi Browser"})+" "+this.trans("Así podrás importar tus carritos de compra automáticamente."):this.trans('Para mejorar tu experiencia lo recomendable es uses navegador _BROW_ y le instales Nuestra extensión de Chrome',{_EXTENSIONLINK_:this.getExtenstionLink(),_BROWSER_LINK_:"https://www.google.com/intl/es/chrome/dr/download/",_BROW_:"CHROME" })+" "+this.trans("Así podrás importar tus carritos de compra automáticamente."),null!=e)){const t=document.createElement("div");t.id=this.uniqueSuffix+"-suggestion",t.innerHTML=`\n
\n \n ${e}\n \n \n
`,this.prepend(t)}}discoverProductLink(e){return new Promise(((t,i)=>{$.ajax({type:"POST",url:this.createApiUrl(`shpa/discovery/${this.choiceComerce.slug}`),dataType:"json",data:{url:e}, success:e=>(e.error??"").length?i([e.error]):(e.errors??[]).length?i(e.errors):void 0===Object.keys(this.data).find((t=>this.data[t].link==e.link))?t(e):i(this.trans("Este producto ya ha sido agregado")),error:e=>i(e)})}))}fetchMarketpplaces(){return new Promise(((e,t)=>{$.ajax({type:"GET",url:this.createApiUrl("shpa/marketplaces"),dataType:"json",success:i=>(i.error??"").length?t(i.error):e(i),error:e=>t(e)})}))}calcTotal(){const e=Object.keys(this.data).reduce(((e,t)=>e+parseFloat(this.data[t].price)*this.data[t].qty),0),t=Object.keys(this.data).reduce(((e,t)=>e+this.data[t].qty),0);return void 0!==this.assistanceContainer&&null!=this.assistanceContainer.querySelector(".total-basket")&&(this.assistanceContainer.querySelector(".total-basket").innerHTML=this.trans("_N_ Productos",{_N_:t})),void 0!==this.onCalculate&&setTimeout((()=>this.onCalculate(e)),10),e}fetchRecipientAddress(){return new Promise(((e,t)=>{$.ajax({type:"GET", url:this.createApiUrl(`shpa/recipients?shipTo=${(this.choiceComerce&&this.choiceComerce.shipTo?this.choiceComerce.shipTo:["US"]).join(",")}`),dataType:"json",success:t=>e(t),error:e=>t(e)})}))}getOrCreateLocker(e){return new Promise(((t,i)=>{$.ajax({type:"GET",url:this.createApiUrl(`shpa/locker/${e}`),dataType:"json",success:e=>t(e),error:e=>i(e)})}))}createLockerUI(){window.confirmModal(this.trans("Al al continuar estas dándonos tu concentimiento para que te demos de alta en WeShipYou.com."),(()=>{this.assistanceContainer.innerHTML=`
\n
\n ${this.trans("Cargando tus direcciones")}....\n
`,this.getOrCreateLocker("WSY").then((e=>{this.captureRecipientAddressUI()})).catch((e=>{ window.alertModal(this.trans("Ups! algo salio mal"),this.trans("Ha ocurrido un error intentando crear tu casillero en Weshipyou.com. Por favor intenta de nuevo más tarde.")),this.captureRecipientAddressUI()}))}))}removeRecipient(e){return new Promise(((t,i)=>{$.ajax({type:"DELETE",url:this.createApiUrl(`shpa/recipient/${e}`),dataType:"json",success:e=>t(e),error:e=>i(e)})}))}removeRecipientUI(e){window.confirmModal(this.trans("¿Estas seguro que quieres eliminar los datos de esta dirección?"),(()=>{this.assistanceContainer.innerHTML=`
\n
\n ${this.trans("Eliminando")}....\n
`,this.removeRecipient(e).then((()=>this.captureRecipientAddressUI())).catch((e=>{ window.alertModal(this.trans("Ups! algo salio mal"),this.trans("Ha ocurrido un error intentando eliminar esta dirección. Por favor intenta de nuevo más tarde.")),this.captureRecipientAddressUI()}))}))}createOrderUI(){this.assistanceContainer.querySelector(".shpa-step4")||(this.disclaimerContainer=document.createElement("div"),this.disclaimerContainer.classList.add("shpa-step4","col-12","p-0"),this.disclaimerContainer.id=`${this.uniqueSuffix}-discliamer-container`,this.assistanceContainer.appendChild(this.disclaimerContainer)),this.step(4,null), this.disclaimerContainer.innerHTML=`\n
\n
\n
${this.trans("Por favor, indícanos cualquier instrucción especial, detalles de entrega, preferencias de compra o cupones de descuento a aplicar.")}
\n \n
\n
\n
\n \n
\n
\n \n
\n
`, this.disclaimerContainer.querySelector(".generalinstructions").addEventListener("input",(()=>{this.generalInstructions=this.disclaimerContainer.querySelector(".generalinstructions").value})),this.disclaimerContainer.querySelector(".add-shpa-terms-back").addEventListener("click",(()=>this.step(3,null))),this.disclaimerContainer.querySelector(".create-shpa-order-btn").addEventListener("click",(()=>{window.confirmModal(`
\n
${this.trans("Al utilizar este servicio, usted acepta los siguientes términos y condiciones")}
\n
\n ${[{title:this.trans("Descripción del Servicio"), content:this.trans("Remesita ofrece un servicio de Compra Asistida que consiste en realizar compras en su nombre en distintos marketplaces. Usted proporcionará enlaces a los productos que desea comprar, y nuestro equipo se encargará de realizar la compra en el marketplace seleccionado.")},{title:this.trans("Proceso de Cotización"),content:this.trans('Después de que usted cree una orden de compra con los enlaces de los productos deseados, su orden se pondrá en estado de "esperando cotización". Nuestro equipo revisará los productos y generará una cotización basada en el costo total de los productos y el envío al destino especificado por usted.')},{title:this.trans("Aceptación o Cancelación de la Orden"), content:this.trans("Una vez que se genere la cotización, se le notificará del costo total, incluyendo el precio de los productos, el envío, y la comisión de Remesita. Usted podrá aceptar o cancelar la orden en este momento y solo si la acepta entonces se debitará de su Wallet el monto cotizado.")},{title:this.trans("Costo de Gestión de Compra"),content:this.trans("Remesita cobra una comisión por la gestión de la compra, que esta en dependencia de la tienda y del costo total de la compra. Esta comisión depende del tamaño de la compra, el riesgo asociado y otros factores que se consideren relevantes. Te informaremos sobre estos costos cuando un asistente establezca la cotización de tu orden.")},{title:this.trans("Política de Riesgo y Exclusión de Artículos"), content:this.trans("Remesita se reserva el derecho de excluir ciertos artículos de la compra si se consideran de alto riesgo según nuestra propia evaluación heurística. Esta evaluación se realiza para proteger a nuestros clientes y evitar la compra de artículos de baja calidad o de vendedores sin reputación. En caso de que un artículo sea denegado, se le notificará y solo se procederá con la compra de los artículos aprobados.")},{title:this.trans("Limitaciones de Responsabilidad"),content:this.trans("Remesita no se hace responsable por la calidad de los productos comprados, la garantía, o cualquier discrepancia que pueda surgir entre el producto recibido y la descripción proporcionada por el marketplace. Nuestra responsabilidad se limita a la correcta gestión y ejecución de la compra según las especificaciones proporcionadas por usted.")},{title:this.trans("Modificaciones del Servicio"), content:this.trans("Remesita se reserva el derecho de modificar estos términos y condiciones en cualquier momento. Cualquier cambio será comunicado oportunamente, y el uso continuado del servicio implica la aceptación de los nuevos términos.")}].map((e=>`
${e.title}

${e.content}

`)).join("")}\n
\n
`,(()=>{this.disclaimerContainer.innerHTML=`
\n
\n ${this.trans("Preparando orden de compra")}....\n
`,this.createOrder().then((e=>{if(void 0!==e.error)return window.alertModal(this.trans("Ups! lo sentimos"),this.trans(e.error)),this.createOrderUI() ;window.alertModal(this.trans("Listo!"),this.trans("La orden de compra _REF_ ha sido creada. En las proximas 24 horas laborables nuestros asistentes actualizarán la cotización. Todavía no será debitado ningún monto de tu Wallet hasta que no aceptes la cotización.",{_REF_:`${e.reference}`})), this.disclaimerContainer.innerHTML=`
${this.trans("¿Dónde te gustaría comprar?")}
\n ${this.trans("Escoge una tienda")}\n ${this.marketplaces.map((e=>`\n `)).join("")}`, this.render((()=>this.ordersTabBtn.click()))})).catch((e=>{window.alertModal(this.trans("Ups! algo salio mal"),this.trans(e)),this.createOrderUI()}))}))}))}createOrder(){return new Promise(((e,t)=>{const i={source:"web",recipientId:this.recipientChoicedId??null,pickUps:this.pickUpChoices??[],quotationData:this.startData?.quotationData?.items??[],shareLink:this.startData?.shareLink??null,generalInstructions:this.generalInstructions,metadata:null==this.startData?null:{network:{...this.startData?.net??{}},...this.startData?.origin??{},screen:this.startData?.screen??{},extensionVersion:this.startData?.extension?.v??null},items:Object.keys(this.data).map((e=>({id:this.data[e].id,title:this.data[e].title,link:this.data[e].link,price:this.data[e].price,qty:this.data[e].qty??1,rating:this.data[e].rating??3.9,review_count:this.data[e].review_count??10,sales:this.data[e].sales??10,risk:this.data[e].risk,provider:this.data[e].provider??this.choiceComerce.name, marketplace:this.data[e].marketplace??this.choiceComerce.slug,thumbnail:this.data[e].images[0],instructions:this.data[e].instructions??"",size:this.data[e].size_choice??null,variations:this.data[e].variation_choice??null})))};$.ajax({type:"PUT",url:this.createApiUrl("shpa/order"),dataType:"json",data:i,success:i=>(i.error??"").length?t(i.error):e(i),error:e=>{t("Ha ocurrido un error intentando crear la orden de compra. Por favor intenta de nuevo más tarde.")}})}))}fetchOrders(e,t,i){return new Promise(((n,s)=>{$.ajax({type:"GET",url:this.createApiUrl(`shpa/orders?pg=${e}&pgSize=${t}&hideCanceled=${i?1:0}`),dataType:"json",success:e=>n(e),error:e=>s(e)})}))}orderHistoryUI(e){ this.ordersContainer.innerHTML=` \n
\n
\n ${this.trans("Cargando historial de órdenes de compra")}....\n
`;const t=e=>{window.alertModal(this.trans("Ups! algo salio mal"),this.trans("Ha ocurrido un error intentando cargar el historial. Por favor intenta de nuevo más tarde.")),this.ordersContainer.innerHTML=`\n
\n \n

${this.trans("No hay pedidos para mostrar.")}

\n
`},i=n=>{this.history=n.items??[], this.ordersContainer.innerHTML=` \n
\n
\n
\n \n \n
\n
\n
\n ${window.wallet.i18n("Mostrar órdenes canceladas")}\n
\n
\n
\n ${0==this.history.length?`
\n \n

${this.trans("No tienes pedidos para mostrar.")}

\n
`:this.history.map((e=>`\n `)).join("")} \n
\n \n ${(()=>{ const e=[];for(let t=1;t<=n.totalPg;t++)e.push(``);return e})().join("")}\n \n
`,this.ordersContainer.querySelector("#hide-canceled").addEventListener("change",(e=>this.orderHistoryUI(!e.target.checked))),this.ordersContainer.querySelectorAll("button.order-btn").forEach((e=>e.addEventListener("click",(e=>{let t=e.target;for(;"BUTTON"!=t.tagName.toUpperCase();)t=t.parentElement;const i=t.getAttribute("oid"),n=this.history.find((e=>e.id==i));n&&this.orderDetailUI(n)})))),this.ordersContainer.querySelectorAll("button.pg-btn").forEach((n=>n.addEventListener("click",(n=>{let s=n.target;for(;"BUTTON"!=s.tagName.toUpperCase();)s=s.parentElement ;const a=s.getAttribute("pg");this.ordersContainer.querySelector(".history-pagginator").innerHTML='',this.fetchOrders(a,10,e).then(i).catch(t)}))))};this.fetchOrders(1,10,e).then(i).catch(t)}orderDetailUI(e){const t=e.shpaGroupedTrackingEvents;this.detailContainer.style.display="flex",this.tabContainer.style.display="none", this.detailContainer.innerHTML=`\n
\n
\n ${"start"==e.status?`
${this.trans("Espere mientras nuestro equipo realiza la cotización con la tienda y agrega el costo de envío y comisión de gestión")}
`:""}\n ${"cancelled"==e.status?`
${this.trans("La orden ha sido cancelada")}
${this.trans(e.cancelReason)}
`:""}\n
\n \n
\n ${this.trans("Detalles de la Orden")}\n
\n
\n
\n
${this.trans("Orden")}: ${e.reference}
\n
${this.trans("Fecha")}: ${e.createdAt}
\n
${this.trans("Estado")}: ${this.statusData(e.status).label}
\n
${this.trans("Tienda")}: ${e.shpaMarketplace}
\n
${this.trans("Cantidad de Productos")}:
\n
\n
\n ${"delivery"==e.shpaDeliveryMode?`
\n \n
\n ${this.trans("Dirección de envío")}\n
\n
\n
\n ${e.shpaRecipient?"":"Error en la dirección!"} ${e.shpaRecipient?.address?.line1} ${e.shpaRecipient?.address?.line2},${e.shpaRecipient?.address?.city}, ${e.shpaRecipient?.address?.state} ${e.shpaRecipient?.address?.zip}, ${e.shpaRecipient?.address?.country}\n
\n
`:`
\n \n
\n ${this.trans(e.shpaPickups.length>1?"Direcciones de recolección":"Dirección de recolección")}\n
\n
\n
\n
    \n ${e.shpaPickups.map((e=>`
  • ${e}
  • `)).join("")} \n
\n ${e.shpaPickups.length>1?` ${this.trans("Una vez completada la compra se definirá la dirección de recoleccion definitiva")}`:""}\n
\n
`}\n ${"start"!=e.status&&"cancelled"!=e.status?`\n
\n \n
\n ${this.trans("Desglose de Costos")}\n
\n
\n
\n ${e.quotaionBrokenDown.items.map((e=>`\n
\n ${this.trans(e.description.split(":")[0])}:\n ${e.description.split(":")[1]??""}\n
`)).join("")}\n
\n
\n ${this.trans("Cotización total")}: ${"start"==e.status?"x.xx":e.quotationFormatted} SRM\n
\n ${e.shpaPriceUpDesicionWarranty>0?`
\n ${this.trans("Cobertura de apreciación")}: ${e.shpaPriceUpDesicionWarranty.toFixed(2)} SRM
\n
\n ${this.trans("Se ocupará para cubrir una posible subida de precio. En caso contrario será reembolsado a tu wallet.")}\n
`:""}\n
\n ${e.quotationNote?.length&&"quotation"==e.status?`
\n
${2==(e.quotationNote??"").split("
\n
`:""}\n
\n ${this.trans("Prueba de cotización")}: \n
\n
\n
`:""}\n ${(e?.transactions??[]).length?`
\n \n
\n ${this.trans("Transacciones")}\n
\n
\n
\n ${e.transactions.reverse().map(((t,i)=>`
\n
${t.amount.toFixed(2)} SRM
\n
${t.memo.replace("REF:","").replace(e.reference,"").replace("COMPRA ASISTIDA","Cotización aceptada").trim()}
\n
`)).join("")}\n
\n
`:""}\n ${"completed"==e.status?`\n
\n \n
\n ${this.trans("Actualizaciones de la tienda")}\n
\n
\n
\n ${"number"==typeof t.length?` ${this.trans("No se han registrado notificaciones provenientes de la tienda.")}`:Object.keys(t).map(((e,i)=>t[e].length?`
\n
${this.trans("PEDIDO #: _CODE_",{ _CODE_:e })}
\n
\n
\n \n
${this.trans("Confirmado")}\n
\n \n
${this.trans("Enviado")}\n
\n \n
${this.trans("En Tránsito")}\n
\n \n
${this.trans("Entregado")}\n
\n
\n
\n ${t[e][t[e].length-1].message}.
\n \n \n \n \n
\n ${t[e][t[e].length-1]?.items?.length?`
    \n
    CONTENIDO:
    \n ${t[e][t[e].length-1]?.items.map((e=>`
  • ${e}
  • `)).join()}
`:""} \n
(e?.courier??"").length>1&&(e?.trackingNumber??"").length>10))?"":'style="display:none"'}>\n Seguimiento ${t[e].reverse().find((e=>(e?.courier??"").length>1&&(e?.trackingNumber??"").length>10))?.courier??""}: 1&&(e?.trackingNumber??"").length>10))?.trackingUrl??""}" target="_blank">${t[e].reverse().find((e=>(e?.courier??"").length>1&&(e?.trackingNumber??"").length>10))?.trackingNumber??""}\n
\n
\n
`:"")).join("")} \n
\n
`:""}\n \n ${e.endorsements.length?`
\n \n
\n ${this.trans("Transparencias")}\n
\n
\n
\n ${e.endorsements.map((e=>`
\n
\n ${"pdf"==e.attachment.split(".").pop().toLowerCase()?``:``} \n
\n
${e.title}
\n ${e.caption}\n
\n \n
\n
`)).join("")}\n
\n
`:""}\n
\n
\n ${"start"==e.status?`
\n \n
\n
\n \n
`:"cancelled"==e.status||"completed"==e.status||"assigned"==e.status?`
\n \n
`:"quotation"==e.status?`
\n \n
\n
\n \n
\n
\n \n
`:"paid"==e.status||"assigned"==e.status||"paused"==e.status?`
\n \n
\n
\n \n
\n `:""}\n \n
\n
`, this.detailContainer.querySelectorAll(".header-accordion").forEach((e=>{e.addEventListener("click",(()=>{e.parentElement.parentElement.classList.toggle("collapsed")}))})),this.detailContainer.querySelectorAll(".shpa-check-points-item").length>1&&this.detailContainer.querySelectorAll(".shpa-check-points-item").forEach(((e,t)=>{e.querySelector("h5").addEventListener("click",(()=>{this.detailContainer.querySelectorAll(".shpa-check-points-item").forEach(((e,i)=>{t!=i&&e.classList.add("collapsed")})),e.classList.toggle("collapsed")}))})),this.detailContainer.querySelector(".help-btn")&&this.detailContainer.querySelector(".help-btn").addEventListener("click",(()=>{$("#zsiq_float").length?($("#zsiq_float").click(),$("#home").removeClass("hideleft"),$(".activeitem").removeClass("activeitem"),$("#home-handler").addClass("activeitem")):this.detailContainer.querySelector(".RemesitaAsistenciabot").submit()})), this.detailContainer.querySelector(".prev-btn")&&this.detailContainer.querySelector(".prev-btn").addEventListener("click",(()=>{this.detailContainer.innerHTML="",this.tabContainer.style.display="block"})),this.detailContainer.querySelector(".cancel-quotation-btn")&&this.detailContainer.querySelector(".cancel-quotation-btn").addEventListener("click",(()=>{this.cancelOrderUI(e.id)})),this.detailContainer.querySelector(".show-proof")&&this.detailContainer.querySelector(".show-proof").addEventListener("click",(()=>{window.alertModal("Prueba de cotización!",``)})),this.detailContainer.querySelector(".show-products")&&this.detailContainer.querySelector(".show-products").addEventListener("click",(()=>{ window.alertModal("Lista de compra",e.shpaItems.map((e=>`
\n \n
\n
\n ${e.title.length>80?e.title.substr(0,80)+"...":e.title}\n
${this.trans("Cantidad")}: ${e.qty} ${1==e.qty?"artículo":"artículos"}
${this.trans("Precio unitario")}: ${parseFloat(e.price).toFixed(2)} ${e.currency??"USD"}\n
\n ${e.stock?"":'
AGOTADO'}\n
\n
\n
`)).join("")) })),this.detailContainer.querySelector(".accept-quotation-btn")&&this.detailContainer.querySelector(".accept-quotation-btn").addEventListener("click",(()=>{this.detailContainer.querySelector(".accept-quotation-btn").setAttribute("disabled","disabled"),this.detailContainer.querySelector(".accept-quotation-btn").innerHTML='';const t=()=>{this.detailContainer.querySelector(".accept-quotation-btn").removeAttribute("disabled"),this.detailContainer.querySelector(".accept-quotation-btn").innerHTML=`${this.trans("Aceptar")} `;const t=[{value:"continue-under-10",label:`${this.trans("Estoy dispuesto a continuar siempre que el precio no exceda el 10% de la cotización.")}
\n ${this.trans("Desición popular")}`},{value:"continue-under-20", label:`${this.trans("Estoy dispuesto a continuar siempre que el precio no exceda el 20% de la cotización.")}
\n ${this.trans("Desición recomendada")}`},{value:"cancel-and-requote",label:`${this.trans("Cancelar y re-cotizar la orden")}
\n ${this.trans("Agrega de 1h-24h al proceso")}`},{value:"cancel-and-refund",label:this.trans("Cancelar y reembolsar el monto a mi Wallet")}];return window.choiceRowModal(this.trans("¿Que hacemos si cambia el precio?"),`
${this.trans("Ayúdanos a tomar decisiones rápidas para ahorrar tiempo y evitar la cancelación del pedido.")}
`,t,!1,(t=>{ const i="continue-under-10"==t?"Al aceptar la cotización de la orden _REF_ estaremos debitando _AMOUNT_ SRM de tu Wallet, y adicional otro 10% que será liberados si el precio no cambia.":"continue-under-20"==t?"Al aceptar la cotización de la orden _REF_ estaremos debitando _AMOUNT_ SRM de tu Wallet, y adicional otro 20% que será liberados si el precio no cambia.":"Al aceptar la cotización de la orden _REF_ estaremos debitando _AMOUNT_ SRM de tu Wallet, esta accion es irreversible.";window.confirmModal(`
${this.trans(i,{_REF_:e.reference,_AMOUNT_:e.quotationFormatted})}\n
${this.trans("¿Estas seguro que deseas continuar?")}
`,(()=>{window.shpaPaymentProgress=1,window.shpaPaymentProgressTik=setInterval((()=>{const e=window.shpaPaymentProgress>=100||window.shpaPaymentProgress<=0 ;e||(window.shpaPaymentProgress=Math.min(95,window.shpaPaymentProgress+5)), this.detailContainer.querySelector(".add-shpa-buttons")&&(this.detailContainer.querySelector(".add-shpa-buttons").innerHTML=`\n
\n
${this.trans(100==window.shpaPaymentProgress?"Pago completado":0==window.shpaPaymentProgress?"Error procesando pago":"Procesando pago")}
\n
\n
\n
\n
\n ${e?`
\n \n
`:""}\n `), e&&(clearInterval(window.shpaPaymentProgressTik),this.detailContainer.querySelector(".prev-btn")&&this.detailContainer.querySelector(".prev-btn").addEventListener("click",(()=>{this.detailContainer.innerHTML="",this.tabContainer.style.display="block",this.orderHistoryUI()})))}),250),this.doPayOrder(e,t).then((e=>{window.shpaPaymentProgress=100,this.dispatchEvent(new CustomEvent("paid",{detail:e.order}))})).catch((e=>{window.shpaPaymentProgress=0,window.alertModal(this.trans("Ups! algo salio mal"),e)}))}))}),(()=>{this.detailContainer.querySelector(".accept-quotation-btn").removeAttribute("disabled"),this.detailContainer.querySelector(".accept-quotation-btn").innerHTML=`${this.trans("Aceptar")} `}))};"delivery"!=e.shpaDeliveryMode||e.shpaRecipient?t():this.fetchRecipientAddress().then((i=>{this.recipientList=i;const n=[];return i.find((e=>(e.lockerProvider??"").length>0))||n.push({value:"create-wsy-locker", label:`${this.trans("¿Aún no tienes un casillero en WeShipyou.com?")}
\n ${this.trans("Créalo ahora y recibe hasta 3% de CashBack⚡️ en tus Compras Asistidas")}`}),i.forEach((e=>{n.push({value:e.id,label:`${e.name}
\n ${e.address.line1} ${e.address.line2}, ${e.address.city} ,${e.address.state} ${e.address.zip}, ${e.address.country}`})})),window.choiceRowModal(this.trans("Conrfirma la dirección de envío de esta compra"),'
',n,!1,(i=>{if("create-wsy-locker"==i)this.getOrCreateLocker().then((i=>{this.recipientList.push(i),e.shpaRecipient={id:i.id,name:i.name,lockerProvider:i.lockerProvider??null,address:{line1:i.address.line1,line2:i.address.line2,city:i.address.city,state:i.address.state,zip:i.address.zip,country:i.address.country}},t() })).catch((e=>window.alertModal(this.trans("Ups! algo salio mal"),this.trans("Ha ocurrido un error intentando crear tu casillero en Weshipyou.com. Por favor intenta de nuevo más tarde."))));else{const n=this.recipientList.find((e=>e.id==i));e.shpaRecipient={id:n.id,name:n.name,lockerProvider:n.lockerProvider??null,address:{line1:n.address.line1,line2:n.address.line2,city:n.address.city,state:n.address.state,zip:n.address.zip,country:n.address.country}},t()}}))})).catch((e=>{t()}))}))}doPayOrder(e,t){const i="continue-under-10"==t?.1*e.quotation:"continue-under-20"==t?.2*e.quotation:0;return new Promise(((n,s)=>{$.ajax({type:"POST",url:this.createApiUrl(`shpa/order/${e.id}/pay`),data:{priceUpDesicionWarranty:i??0,priceUpDesicion:t,recipientId:e.shpaRecipient?.id??null},dataType:"json",success:e=>n(e),error:e=>s(e?.responseJSON?.error??this.trans("Ocurrio un error procesando el pago. Por favor intenta de nuevo más tarde."))})}))}cancelOrderUI(e){ window.confirmModal(this.trans("¿Estas seguro que deseas cancelar esta orden?"),(()=>{setTimeout((()=>{if(this.detailContainer.querySelector(".cancel-btn")&&(this.detailContainer.querySelector(".cancel-btn").innerHTML=` ${this.trans("Espere")}`,this.detailContainer.querySelector(".cancel-btn").disabled=!0),this.querySelector(".add-shpa-buttons")){this.querySelectorAll(".add-shpa-buttons .col-6").forEach((e=>e.style.display="none"));const e=document.createElement("div");e.classList.add("shpa-item-container"),e.id=`${this.uniqueSuffix}-canceling-indicator`,this.querySelector(".add-shpa-buttons").appendChild(e),e.innerHTML=`
${this.trans("Cancelando")}...
`}this.cancelOrder(e).then((()=>{this.ordersTabBtn.click(),this.detailContainer.innerHTML="",this.tabContainer.style.display="block"})).catch((e=>{this.querySelector(".add-shpa-buttons .col-6").style.display="block", window.alertModal(this.trans("Ups! algo salio mal"),this.trans("Ha ocurrido un error intentando cancelar la orden. Por favor intenta de nuevo más tarde.")),this.detailContainer.querySelector(".cancel-btn")&&(this.detailContainer.querySelector(".cancel-btn").innerHTML=` ${this.trans("Cancelar")}`,this.detailContainer.querySelector(".cancel-btn").disabled=!1),this.querySelectorAll(".add-shpa-buttons .col-6").forEach((e=>e.style.display="block"))}))}),500)}))}cancelOrder(e){return new Promise(((t,i)=>{$.ajax({type:"POST",url:this.createApiUrl(`shpa/order/${e}/cancel`),dataType:"json",success:e=>t(e),error:e=>i(e)})}))}statusData(e){switch(e){case"start":return{label:this.trans("Esperando Cotización"),ico:"clock",badgeColor:"dark"};case"cancelled":return{label:this.trans("Pedido Cancelado"),ico:"cancel",badgeColor:"danger"};case"quotation":return{label:this.trans("Cotización Establecida"),ico:"dollar",badgeColor:"warning"};case"paid":return{ label:this.trans("En breve será procesada"),ico:"clock",badgeColor:"secondary"};case"assigned":return{label:this.trans("Estamos comprando"),ico:"spin mdi-refresh",badgeColor:"warning"};case"paused":return{label:this.trans("Proceso Pausado"),ico:"pause-octagon-outline",badgeColor:"secondary"};case"completed":return{label:this.trans("Completada"),ico:"check-circle",badgeColor:"success"}}return{label:this.trans("Procesando"),ico:"clock",badgeColor:"info"}}choicePickUpLockerUI(){Object.keys(this.data).reduce(((e,t)=>e+parseFloat(this.data[t].price)*this.data[t].qty),0),Object.keys(this.data).reduce(((e,t)=>e+this.data[t].qty),0);const e=`
\n
${this.trans("¿Dónde se te hace más conveniente recoger tu compra de _COMERCE_?",{_COMERCE_:""+this.choiceComerce?.name+""})}
\n
` ;this.assistanceContainer.querySelector(".shpa-step3")||(this.pickupContainer=document.createElement("div"),this.pickupContainer.classList.add("shpa-step3","col-12","p-0"),this.pickupContainer.id=`${this.uniqueSuffix}-pickup-container`,this.assistanceContainer.appendChild(this.pickupContainer)),this.step(3,null);const t=this.choiceComerce.pickUpOn.find((e=>(this.startData?.quotationData?.pickup??"").replace("Ave.","Avenida").indexOf(e.replace("Ave.","Avenida").split(".")[0])>-1)) ;this.pickupContainer.innerHTML=t?`${e}
\n \n
\n `:`${e}
\n ${this.choiceComerce.pickUpOn.map((e=>``)).join("")} \n
\n
\n ${this.trans("Puedes seleccionar más de una opción porque no podemos garantizar que todos los artículos estan disponibles en todas las ubicaciones")}\n
\n `, this.pickupContainer.querySelector("button.next-shpa-btn").addEventListener("click",(()=>{this.pickUpChoices=[],this.pickupContainer.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this.pickUpChoices.push(e.value)})),this.pickUpChoices.length&&this.createOrderUI()})),this.pickupContainer.querySelector("button.prev-shpa-item-btn").addEventListener("click",(()=>this.step(2,null)))}captureRecipientAddressUI(e){Object.keys(this.data).reduce(((e,t)=>e+parseFloat(this.data[t].price)*this.data[t].qty),0) ;const t=Object.keys(this.data).reduce(((e,t)=>e+this.data[t].qty),0),i=`
\n \n
${this.trans("_N_ Productos",{_N_:t})}\n
\n
${this.trans("Adónde quieres enviar tu compra de _COMERCE_?",{_COMERCE_:""+this.choiceComerce?.name+""})}
\n
`;if(this.assistanceContainer.querySelector(".shpa-step3")||(this.recipientContainer=document.createElement("div"), this.recipientContainer.classList.add("shpa-step3","col-12","p-0"),this.recipientContainer.id=`${this.uniqueSuffix}-recipient-container`,this.assistanceContainer.appendChild(this.recipientContainer)),this.step(3,null),e){ this.recipientContainer.innerHTML=` \n ${i}\n
${this.trans("Nueva dirección de recepción para tus compras")}
\n
\n
\n \n
\n \n
\n
\n
\n
\n \n
\n \n
\n
\n
\n \n
\n \n
\n
\n
\n\n
\n \n
\n \n
\n
\n
\n \n
\n \n
\n
\n
\n
\n \n
\n \n
\n
\n
\n
\n
\n \n
\n \n
\n
\n
\n \n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n \n
\n
`, this.step(3,null);const e=()=>this.recipientContainer.querySelector(".recipient-data-error").style.display="none",t=t=>this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-${t}`).addEventListener("input",e);t("name"),t("phone"),t("zip"),t("address1"),t("address2"),t("city"),t("state");const n=this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-country`),s=this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-state`);n&&s&&(n.addEventListener("change",(()=>{switch(n.value){case"US":s.innerHTML=[{n:"Alabama",c:"AL"},{n:"Alaska",c:"AK"},{n:"Arizona",c:"AZ"},{n:"California",c:"CA"},{n:"Colorado",c:"CO"},{n:"Connecticut",c:"CT"},{n:"Delaware",c:"DE"},{n:"Florida",c:"FL"},{n:"Georgia",c:"GA"},{n:"Hawaii",c:"HI"},{n:"Idaho",c:"ID"},{n:"Illinois",c:"IL"},{n:"Indiana",c:"IN"},{n:"Iowa",c:"IA"},{n:"Kansas",c:"KS"},{n:"Kentucky",c:"KY"},{n:"Louisiana",c:"LA"},{n:"Maine",c:"ME"},{n:"Maryland",c:"MD"},{n:"Massachusetts",c:"MA"},{n:"Michigan",c:"MI" },{n:"Minnesota",c:"MN"},{n:"Mississippi",c:"MS"},{n:"Missouri",c:"MO"},{n:"Montana",c:"MT"},{n:"Nebraska",c:"NE"},{n:"Nevada",c:"NV"},{n:"New Hampshire",c:"NH"},{n:"New Jersey",c:"NJ"},{n:"New Mexico",c:"NM"},{n:"New York",c:"NY"},{n:"North Carolina",c:"NC"},{n:"North Dakota",c:"ND"},{n:"Ohio",c:"OH"},{n:"Oklahoma",c:"OK"},{n:"Oregon",c:"OR"},{n:"Pennsylvania",c:"PA"},{n:"Rhode Island",c:"RI"},{n:"South Carolina",c:"SC"},{n:"South Dakota",c:"SD"},{n:"Tennessee",c:"TN"},{n:"Texas",c:"TX"},{n:"Utah",c:"UT"},{n:"Vermont",c:"VT"},{n:"Virginia",c:"VA"},{n:"Washington",c:"WA"},{n:"West Virginia",c:"WV"},{n:"Wisconsin",c:"WI"},{n:"Wyoming",c:"WY"}].map((e=>``)).join(""),setTimeout((()=>$(`#${this.uniqueSuffix}recipient-phone`).mask("+1 (000) 000-0000")),100);break;case"CU":s.innerHTML=[{n:"Pinar del Río",c:"PR"},{n:"Artemisa",c:"AR"},{n:"La Habana",c:"LH"},{n:"Mayabeque",c:"MY"},{n:"Matanzas",c:"MT"},{ n:"Cienfuegos",c:"CF"},{n:"Villa Clara",c:"VC"},{n:"Sancti Spíritus",c:"SS"},{n:"Ciego de Ávila",c:"CA"},{n:"Camagüey",c:"CM"},{n:"Las Tunas",c:"LT"},{n:"Holguín",c:"HO"},{n:"Granma",c:"GR"},{n:"Santiago de Cuba",c:"SC"},{n:"Guantánamo",c:"GU"},{n:"Isla de la Juventud",c:"IJ"}].map((e=>``)).join(""),setTimeout((()=>$(`#${this.uniqueSuffix}recipient-phone`).mask("+5350000000")),100)}})),n.value=this.choiceComerce.shipTo[0],n.dispatchEvent(new Event("change"))),this.recipientContainer.querySelector("button.prev-shpa-btn").addEventListener("click",(()=>this.captureRecipientAddressUI())),this.recipientContainer.querySelector("button.next-shpa-btn").addEventListener("click",(()=>{ const t=this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-name`).value,i=(this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-phone`).value??"").replace(/\(|\)|-|\s/g,"").trim(),n=(this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-zip`).value??"").trim(),s=(this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-address1`).value??"").trim(),a=(this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-address2`).value??"").trim(),r=(this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-city`).value??"").trim(),o=(this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-state`).value??"").trim(),l=(this.recipientContainer.querySelector(`#${this.uniqueSuffix}recipient-country`).value??"USA").trim();t.length<3||i.length<10||s.length<3||r.length<3||o.length<2||n.length<5?this.recipientContainer.querySelector(".recipient-data-error").style.display="block":(e(), this.recipientContainer.querySelector("button.next-shpa-btn").disabled=!0,this.recipientContainer.querySelector("button.next-shpa-btn").innerHTML=` `,this.storeRecipient(t,i,s,a,r,o,n,l).then((()=>this.captureRecipientAddressUI())).catch((e=>{window.alertModal(this.trans("Ups! algo salio mal"),this.trans("Ha ocurrido un error intentando almacenar la dirección de recepción. Por favor intenta de nuevo más tarde.")),this.captureRecipientAddressUI()})))})),setTimeout((()=>{$(`#${this.uniqueSuffix}recipient-zip`).mask("00000"),$(`#${this.uniqueSuffix}recipient-phone`).mask("US"==this.choiceComerce.shipTo[0]?"+1 (000) 000-0000":"CU"==this.choiceComerce.shipTo[0]?"+5350000000":"+0000000000")}),100) }else this.recipientContainer.innerHTML=`
\n
\n ${this.trans("Cargando tus direcciones")}....\n
`,this.fetchRecipientAddress().then((e=>{ const t=e.find((e=>(e.lockerProvider??"").length>0)),n=!t&&this.choiceComerce.shipTo.indexOf("US")>-1?``:"" ;this.recipientContainer.innerHTML=`\n ${i}\n
\n \n ${e.map((e=>`
\n
\n
\n \n
${e.name}
\n ${this.trans("Casillero proveido por _PROVIDER_",{ _PROVIDER_:e.lockerProvider})} \n
${e.address.line1} ${e.address.line2}, ${e.address.city} ,${e.address.state} ${e.address.zip}, ${e.address.country}
\n ⚡️ ${this.trans("Hasta _CB_% de CashCack",{_CB_:100*(e.cashback??e.discount??0) })} \n
\n
\n
\n
${this.trans("¿Quieres usar esta dirección?")}
\n
\n \n ${(e.lockerProvider??"").length?"":``}\n \n
\n
\n
`)).join("")}\n ${n} \n \n\n
\n ` ;const s=this.recipientContainer.querySelectorAll(".swipe-container");if(s){let a,r,o,l=null;function c(e){e.previousElementSibling.style.transform="translateX(0)",e.style.right="-100%"}s.forEach((e=>{const t=e.querySelector(".swipeable-button"),i=e.querySelector(".swipeable-menu");t.addEventListener("click",(e=>{l&&l!==i&&c(l),l=i,t.style.transform="translateX(-100%)",i.style.right="0"})),t.addEventListener("mousedown",(e=>{a=e.clientX,o=!1,l&&l!==i&&c(l);const n=e=>{r=e.clientX;const i=r-a;i<0&&(t.style.transform=`translateX(${i}px)`,o=!0)},s=()=>{document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",s),o&&r-a<-50?(l=i,t.style.transform="translateX(-100%)",i.style.right="0"):(t.style.transform="translateX(0)",i.style.right="-100%")};document.addEventListener("mousemove",n),document.addEventListener("mouseup",s)})),e.querySelector(".cancel-swipeable").addEventListener("click",(()=>l&&c(l))), e.querySelector(".delete-recipient")&&e.querySelector(".delete-recipient").addEventListener("click",(()=>this.removeRecipientUI(e.querySelector(".delete-recipient").getAttribute("rid")))),e.querySelector(".choice-recipient").addEventListener("click",(e=>{this.recipientChoicedId=e.target.getAttribute("rid"),this.createOrderUI()}))}))}!t&&this.choiceComerce.shipTo.indexOf("US")>-1&&this.recipientContainer.querySelector("button.locker-create-btn").addEventListener("click",(()=>this.createLockerUI())),this.recipientContainer.querySelector("button.recipient-add-btn").addEventListener("click",(()=>this.captureRecipientAddressUI(!0))),this.recipientContainer.querySelector("button.prev-shpa-step3-btn").addEventListener("click",(()=>this.step(2,null)))})).catch((e=>{}))}storeRecipient(e,t,i,n,s,a,r,o){return new Promise(((l,c)=>{$.ajax({type:"POST",url:this.createApiUrl("shpa/recipient"),dataType:"json",data:{name:e,phone:t,address:{line1:i,line2:n,city:s,state:a,zip:r,country:o}}, success:e=>(e.error??"").length?c([e.error]):(e.errors??[]).length?c(e.errors):void 0===Object.keys(this.data).find((t=>this.data[t].link==e.link))?l(e):c(this.trans("Este producto ya ha sido agregado")),error:e=>c(e)})}))}notImplemented(){window.alertModal("Hey, maestro impaciente!","Esta funcionalidad está en un campamento de entrenamiento, levantando pesas de código, haciendo flexiones de diseño y corriendo maratones de pruebas. Pronto estará lista para la batalla!")}addItemUI(e){let t=this.assistanceContainer.querySelectorAll(".shpa-item-container").length+1;1==t&&(this.choiceComerce||(this.choiceComerce={logo:null,maximumTikcket:-1,minimumTikcket:1,maximumTikcket:5e3,percentFee:.05,fixFee:1,fixMinimum:10}), this.assistanceContainer.innerHTML=`\n
\n
\n \n
${this.trans("_N_ Productos",{_N_:0})}
\n
${this.trans("Mi lista de compras en _COMERCE_",{_COMERCE_:""+this.choiceComerce?.name+"" })}
\n ${this.importFromBrowserExtension?` ${this.trans("Datos importados desde la extensión del navegador")}`:""}\n
\n \n ${-1==this.choiceComerce.maximumTikcket?this.trans("El costo total de los productos debe superar los _MIN_ USD",{_MIN_:this.choiceComerce.minimumTikcket}):this.trans("El costo total de los productos debe estar en el rango _MIN_ a _MAX_ USD",{_MIN_:this.choiceComerce.minimumTikcket,_MAX_:this.choiceComerce.maximumTikcket })}\n \n
\n
\n ${(this.startData?.quotationData?.items??[]).length?`
\n
${this.trans("Cotización preliminar")}
\n
    \n ${this.startData.quotationData.items.map((e=>`
  • ${e.label}: ${e.value}
  • `)).join("")}\n
  • Comisión de Remesita: ${Math.max(parseFloat(this.startData.quotationData.items[this.startData.quotationData.items.length-1].value)*this.choiceComerce.percentFee+this.choiceComerce.fixFee,this.choiceComerce.fixMinimum).toFixed(2)} SRM
  • \n
  • Total estimado: ${(Math.max(parseFloat(this.startData.quotationData.items[this.startData.quotationData.items.length-1].value)*this.choiceComerce.percentFee+this.choiceComerce.fixFee,this.choiceComerce.fixMinimum)+parseFloat(this.startData.quotationData.items[this.startData.quotationData.items.length-1].value)).toFixed(2)} SRM
  • \n
\n
${this.trans("El precio mostrado es solo un estimado. Al proporcionar la dirección de entrega, pueden añadirse costos de envío e impuestos o aplicarse descuentos. Si el precio final es menor o no se cobra el envío, reembolsaremos la diferencia.")}
\n
`:""}\n
\n \n
\n `, this.assistanceContainer.querySelector(".add-shpa-item-btn").addEventListener("click",(()=>{this.assistanceContainer.querySelector(".add-shpa-item-btn").disabled=!0,this.addItemUI()})),this.assistanceContainer.querySelector(".next-shpa-btn").addEventListener("click",(()=>{this.basketHtml=this.innerHTML,this.generalInstructions="",(this.choiceComerce?.pickUpOn??[]).length?this.choicePickUpLockerUI():this.captureRecipientAddressUI()})));const i=document.createElement("div");i.classList.add("shpa-item-container"),i.id=`${this.uniqueSuffix}-shpa-item${t}`,this.assistanceContainer.querySelector(".item-list-container").appendChild(i),i.innerHTML=`\n \n
\n \n \n
\n \n
\n \n `,window.shpaScrapTiks&&clearInterval(window.shpaScrapTiks),window.shpaScrapProgress=0,window.shpaScrapTiks=setInterval((()=>{window.shpaScrapProgress=Math.min(95,window.shpaScrapProgress+5),i.querySelector(".shpa-item-indicator .progress-bar").style.width=`${window.shpaScrapProgress}%`,i.querySelector(".shpa-item-indicator .progress-bar").setAttribute("aria-valuenow",`${window.shpaScrapProgress}%`),i.querySelector(".shpa-item-indicator .progress-info").innerHTML=` ${this.trans(window.shpaScrapProgress<35?"Conectando con _COMMERCE_":window.shpaScrapProgress<85?"Leyendo datos":"Analizando riesgo",{_COMMERCE_:this.choiceComerce?.name})}....`,window.shpaScrapProgress>=95&&clearInterval(window.shpaScrapTiks)}),500),i.querySelector(".url-cleaner").addEventListener("click",(e=>{i.querySelector(".url-cleaner").style.display="none", i.querySelector('[type="url"]').value="",i.querySelector(".shpa-item-url-help").style.display="none"})),i.querySelector('[type="url"]').addEventListener("input",(e=>{if(i.querySelector(".url-cleaner").style.display=(e.target.value??"").length>0?"flex":"none",i.querySelector(".shpa-item-url-help").style.display="none",e.target.checkValidity()){const n=e.target.value;e.target.disabled=!0,i.querySelector(".shpa-item-url-help").innerHTML="",i.querySelector(".shap-item-input").style.display="none",i.querySelector(".shpa-item-indicator").style.display="block",this.discoverProductLink(n).then((i=>{e.target.disabled=!1,this.data[`_${t}`]={...i,qty:1},this.renderItem(t),clearInterval(window.shpaScrapTiks),window.shpaScrapProgress=0})).catch((t=>{"object"!=typeof t&&(t=[t]),e.target.disabled=!1,i.querySelector(".shpa-item-indicator").style.display="block",i.querySelector(".shap-item-input").style.display="block",i.querySelector(".shpa-item-indicator").style.display="none", i.querySelector(".shpa-item-url-help").innerHTML=`${t.map((e=>` ${e}`)).join("
")}

${this.trans("Si crees que esto es un error, repórtalo para que podamos resolverlo lo antes posible.")}
${this.trans("Reportar Problema")}`,i.querySelector(".shpa-item-url-help").style.display="block"}))}})),i.querySelector(".shpa-item-label button").addEventListener("click",(e=>this.renderItem(t))),e&&(this.data[`_${t}`]=e,this.renderItem(t,!0))}renderItem(e,t){this.data[`_${e}`].qty||(this.data[`_${e}`].qty=1);const i=this.data[`_${e}`];i.variation_choice||(i.variation_choice={});const n=this.querySelector(`#${this.uniqueSuffix}-shpa-item${e}`),s=i.sizes??{} ;this.assistanceContainer.querySelectorAll(".shpa-item-container").forEach((e=>e.style.display="none")),n.style.display="block",this.querySelector(".add-shpa-buttons").style.display="none",this.querySelector(".market-quotation")&&(this.querySelector(".market-quotation").style.display="none"),n.querySelector(".shpa-item-indicator").style.display="none",n.querySelector(".shpa-item-label button").style.display="none",n.querySelector(".shpa-item-data").style.display="block",n.querySelector(".shpa-item-number").innerHTML=`${this.trans("Producto #_N_",{_N_:e})} | ${i.qty} ${this.trans(i.qty>1?"Unidades":"Unidad")}`,n.querySelector(".shpa-item-label .prod-thumbnail").style.backgroundImage="url(/assets/img/loader.gif)",n.querySelector(".shpa-item-label .prod-thumbnail").style.display="none",n.querySelector(".shap-item-input").style.display="none",n.querySelector(".shap-item-input").classList.remove("d-flex"), n.querySelector(".shpa-item-data").innerHTML=` \n
\n \n
\n
${i.title.length>150?i.title.substr(0,150)+"...":i.title}
\n ${this.choiceComerce.reviewSystemCapability?` `:``}\n \n
\n
\n\n
\n ${this.trans("Variantes")} \n
\n
\n ${Object.keys(i.variation_filters??{}).map(((e,t)=>`
\n \n
`)).join("")} \n
\n
\n
\n
\n ${this.trans("Tamaño")} \n
\n
\n ${Object.keys(s).map(((e,t)=>`
\n \n \n
`)).join("")}\n
\n
\n ${Object.keys(s).map(((e,t)=>`\n ${s[e].map((e=>`${Object.keys(e)[0]}: ${e[Object.keys(e)[0]]}`)).join(". ")}\n `)).join("")}\n
\n
\n
\n\n
\n
\n ${this.trans("Cantidad de artículos")} ${(this.startData?.quotationData?.items??[]).length||this.importFromBrowserExtension?`${i.qty}`:""} \n
\n \n \n \n
\n
\n
\n\n
\n
\n ${this.trans("No fuimos capaces de capturar las variantes de este producto. Por favor, escriba en las instrucciones los detalles, talla, color, tamaño, etc.")}\n
\n
\n\n
\n ${this.trans("Instrucciones")} (${this.trans("Obligatorio")}) \n \n \n
\n \n\n
\n
\n
\n
\n
\n
\n `, n.renderRisk=e=>{n.querySelector(".risk-container")&&(this.choiceComerce.reviewSystemCapability||(e=34.9), n.querySelector(".risk-container").innerHTML=`
${this.trans("Evaluación de riesgo")} ${e<=15?this.trans("BAJO"):e<35?this.trans("MODERADO"):this.trans("ALTO")}
\n
\n
\n
\n
\n
\n
\n ${this.choiceComerce.reviewSystemCapability?"":`
\n ${this.trans("No logramos encontrar comentarios de otros compradores, por lo que no podemos detectar señales de riesgo basadas en experiencias anteriores. El riesgo se evalúa únicamente por el monto a pagar y posibles retrasos en la logística para este tipo de productos.")}\n
`}\n \n ${this.trans("Aprende cómo evaluamos el riesgo de tu compra.")}`) },n.renderPriceIput=e=>{ n.querySelector(".risk-container")&&(n.querySelector(".risk-container").innerHTML=`
\n ${this.trans("No fuimos capaces de capturar el precio de cada unidad de este producto, por favor indica aquí para que podamos hacer la evaluación adecuada de riesgo")}\n
\n
\n \n
\n \n
\n \n
\n
\n
`, this.querySelector(`#${this.uniqueSuffix}${e}price`).addEventListener("input",(e=>{parseFloat(e.target.value)>0?n.querySelector(".btn-apply-price").removeAttribute("disabled"):n.querySelector(".btn-apply-price").setAttribute("disabled","disabled")})),this.querySelector(`#${this.uniqueSuffix}${e}priceApplyBtn`).addEventListener("click",(t=>{t.target.setAttribute("disabled","disabled"),t.target.innerHTML='',this.querySelectorAll(".witing-price").forEach((e=>e.classList.remove("witing-price"))),this.data[`_${e}`].price=parseFloat(this.querySelector(`#${this.uniqueSuffix}${e}price`).value),this.data[`_${e}`].priceFaked=!1,n.renderRisk(this.data[`_${e}`].risk)})),setTimeout((()=>$(`#${this.uniqueSuffix}${e}price`).mask("000,000,000,000,000.00",{reverse:!0,placeholder:"1.00"})),100))},n.preloadImage=e=>setTimeout((()=>{let t=new Image;t.onload=()=>{ n.querySelector(".shpa-item-label .prod-thumbnail")&&(n.querySelector(".shpa-item-label .prod-thumbnail").style.backgroundImage=`url(${e??""})`),n.querySelector(".img-fluid")&&(n.querySelector(".img-fluid").src=e)},t.onerror=()=>{n.querySelector(".shpa-item-label .prod-thumbnail")&&(n.querySelector(".shpa-item-label .prod-thumbnail").style.backgroundImage="url(/assets/img/no-pic.png)"),n.querySelector(".img-fluid")&&(n.querySelector(".img-fluid").src="/assets/img/no-pic.png")},t.src=e}),100),n.preloadImage(i.images[0]),i.priceFaked?n.renderPriceIput(e):n.renderRisk(i.risk),Object.keys(s).length&&n.querySelectorAll(".size-choice").forEach((t=>t.addEventListener("change",(t=>{n.querySelectorAll(".size-info").forEach((e=>e.style.display="none"));const i=t.target.getAttribute("size");n.querySelector(`.size${i}info`).style.display="block",this.data[`_${e}`].size_choice=i})))), Object.keys(i.variation_filters??{}).forEach((t=>n.querySelector(`.shpa-item-variation-${t.replace("/s/g","_")}`).addEventListener("change",(s=>{if(this.data[`_${e}`].variation_choice[t.replace("/s/g","_")]=s.target.value,"amazonus"==this.choiceComerce.slug&&this.data[`_${e}`].variations.length){const a=this.data[`_${e}`]?.variations.find((e=>{if((e.matching_filters[t]??"").replace(/\s\s+/g," ")==s.target.value.replace(/\s\s+/g," ")){let i=!0;return Object.keys(e.matching_filters).forEach((s=>{s!=t&&i&&n.querySelector(`.shpa-item-variation-${s.replace("/s/g","_")}`).value!=e.matching_filters[s]&&(i=!1)})),i}return!1}))?.number??"";a&&(n.querySelector(".btn-cancel")&&n.querySelector(".btn-cancel").setAttribute("disabled","disabled"),n.querySelector(".btn-accept")&&n.querySelector(".btn-accept").setAttribute("disabled","disabled"),n.querySelector(".img-fluid")&&(n.querySelector(".img-fluid").src="/assets/img/loader.gif"), this.discoverProductLink(`https://www.amazon.com/dp/${a}`).then((t=>{n.querySelector(".btn-cancel")&&n.querySelector(".btn-cancel").removeAttribute("disabled"),n.querySelector(".btn-accept")&&n.querySelector(".btn-accept").removeAttribute("disabled"),this.data[`_${e}`].link=`https://www.amazon.com/dp/${a}`,this.data[`_${e}`].images=t.images,this.data[`_${e}`].price=t.price??this.data[`_${e}`].price,this.data[`_${e}`].title=t.title,this.data[`_${e}`].risk=t.risk,i.priceFaked?n.renderPriceIput(e):n.renderRisk(i.risk),n.querySelector(".item-title")&&(n.querySelector(".item-title").innerHTML=t.title.length>150?t.title.substr(0,150)+"...":t.title),n.preloadImage(t.images[0]??"")})))}})))),n.querySelector(".qty-sub").addEventListener("click",(t=>{this.data[`_${e}`].qty=Math.max(1,this.data[`_${e}`].qty-1),n.querySelector(".qty").innerHTML=this.data[`_${e}`].qty,n.querySelector(".shpa-item-number").innerHTML=`${this.trans("Producto #_N_",{_N_:e })} | ${this.data[`_${e}`].qty} ${this.trans(this.data[`_${e}`].qty>1?"Unidades":"Unidad")}`,this.validateForm()})),n.querySelector(".qty-add").addEventListener("click",(t=>{const i=this.data[`_${e}`].risk<=15?10:this.data[`_${e}`].risk<=35?5:1;this.data[`_${e}`].qty=Math.min(i,this.data[`_${e}`].qty+1),n.querySelector(".qty").innerHTML=this.data[`_${e}`].qty,n.querySelector(".shpa-item-number").innerHTML=`${this.trans("Producto #_N_",{_N_:e})} | ${this.data[`_${e}`].qty} ${this.trans(this.data[`_${e}`].qty>1?"Unidades":"Unidad")}`,this.validateForm()})),n.querySelector(".shpa-item-instructions").addEventListener("input",(t=>{this.data[`_${e}`].instructions=t.target.value,n.querySelector(".shpa-item-instructions").style.height="auto",n.querySelector(".shpa-item-instructions").style.height=n.querySelector(".shpa-item-instructions").scrollHeight+"px"})),n.querySelector("button.btn-cancel").addEventListener("click",(()=>{ n.querySelector(".shpa-item-data").style.display="none",n.querySelector(".shpa-item-label").style.textDecoration="line-through",this.querySelector(".add-shpa-buttons").style.display="flex",this.assistanceContainer.querySelectorAll(".shpa-item-container").forEach((e=>e.style.display="flex")),this.assistanceContainer.querySelector(".add-shpa-item-btn").disabled=!1,n.querySelector(".shpa-item-label .prod-thumbnail").style.display="flex",delete this.data[`_${e}`],this.validateForm()}));const a=()=>{n.querySelector("button.btn-accept").removeAttribute("disabled"),n.querySelector("button.btn-accept").innerHTML='',n.querySelector(".shpa-item-label button").style.display="block",n.querySelector(".shpa-item-data").style.display="none",this.querySelector(".add-shpa-buttons").style.display="flex",this.querySelector(".market-quotation")&&(this.querySelector(".market-quotation").style.display="block"), this.assistanceContainer.querySelectorAll(".shpa-item-container").forEach((e=>e.style.display="flex")),this.assistanceContainer.querySelector(".add-shpa-item-btn").disabled=!1,n.querySelector(".shpa-item-label .prod-thumbnail").style.display="flex",this.validateForm()};n.querySelector("button.btn-accept").addEventListener("click",(()=>{n.querySelector(".shpa-item-instructions")&&n.querySelector(".shpa-item-instructions").value.length&&(this.data[`_${e}`].instructions=n.querySelector(".shpa-item-instructions").value),(this.data[`_${e}`].instructions??"").trim().length?a():(n.querySelector(".shpa-item-instructions").classList.add("animate","animated","shake","border-danger","bg-danger-light"),setTimeout((()=>n.querySelector(".shpa-item-instructions").classList.remove("animate","animated","shake","border-danger","bg-danger-light")),1e3))})),t&&a(),this.validateForm()}validateInstructions(e,t){return new Promise(((i,n)=>{$.ajax({type:"POST", url:this.createApiUrl("shpa/validate-instructions"),dataType:"json",data:{title:e,instructions:t},success:e=>e.success?i(e):n(e.error),error:e=>n(e)})}))}validateForm(){let e=this.calcTotal(),t=e>0;const i={success:t,total:e,items:Object.keys(this.data).map((e=>this.data[e]))};"function"==typeof this.onValidation&&this.onValidation(i),this.dispatchEvent(new CustomEvent("validation",{detail:i})),null!=this.querySelector(".next-shpa-btn")&&(this.querySelector(".next-shpa-btn").disabled=!t)}setupSHPA(e){void 0!==e.styles&&(this.overrideStyles=e.styles),void 0!==e.i18n&&(this.i18n=e.i18n),void 0!==e.marketplaces&&(this.marketplaces=e.marketplaces),void 0!==e.contanerClass&&(this.contanerClass=e.contanerClass),e.startData&&e.startData.length&&e.startData[0]?.price&&(e.startData={products:e.startData}),void 0!==e.startData&&(this.startData=e.startData),void 0!==e.onStep&&(this.onStep=e.onStep),void 0!==e.onValidation&&(this.onValidation=e.onValidation), void 0!==e.importFromBrowserExtension&&(this.importFromBrowserExtension=e.importFromBrowserExtension),this.startData&&this.startData.seed?fetch("/rest/v1/shpa/seed/"+e.startData.seed).then((e=>e.json())).then((e=>{this.startData=e,this.refresh(this.startData),setTimeout((()=>this.validateForm()),100)})).catch((t=>{this.refresh(e.startData??!1),setTimeout((()=>this.validateForm()),100)})):(this.refresh(e.startData??!1),setTimeout((()=>this.validateForm()),100))}}if(customElements.define("shopping-assistance",e),"undefined"!=typeof jQuery&&(jQuery.fn.setupSHPA=function(e){return this.each((function(){"shopping-assistance"===this.tagName.toLowerCase()&&this.setupSHPA(e)}))}),"undefined"==typeof jsQR){var script=document.createElement("script");script.src="/assets/js/jsQR.min.js",script.async=!0,document.head.appendChild(script)}}