const nameCustomElement="quickview-component";class QuickviewComponent extends window.HTMLElement{connectedCallback(){this.modalElem=document.querySelector("#quickview-modal"),this.closeButtonElem=this.modalElem.querySelector("#quickview-close"),this.quickviewStructureElem=this.modalElem.querySelector("#quickview-structure"),this.buildModal=this.buildModal.bind(this),this.closeModal=this.closeModal.bind(this),this.updateQuickview=this.updateQuickview.bind(this),this.updateQuantity=this.updateQuantity.bind(this),this.addToCart=this.addToCart.bind(this),this.addClickEvents()}addClickEvents(){this.querySelector("[data-quickview-trigger]").addEventListener("click",this.buildModal),this.closeButtonElem.addEventListener("click",this.closeModal)}activeAddToCartEvents(){const addToCartButton=this.modalElem.querySelector("#quickview-add-to-cart");addToCartButton!==null&&addToCartButton.addEventListener("click",this.addToCart)}showError(message){const errorElem=this.modalElem.querySelector("#quickview-error");if(errorElem!==null){errorElem.innerHTML=`${message}`,errorElem.classList.add("active");const disappear=setTimeout(()=>{errorElem.classList.remove("active"),clearTimeout(disappear)},4e3)}}async addToCart(){const variantElemSelected=this.modalElem.querySelector(".variant--selected")||this.modalElem.querySelector("#quickview-variant-list"),variantQuantity=this.modalElem.querySelector("#quantity-input").value,{variantId,variantPrice,variantCompareAtPrice}=variantElemSelected.dataset,options={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:[{id:variantId,quantity:variantQuantity}]})};try{const response=await fetch("/cart/add.js",options);if(response.status==200){const variantData2={...(await response.json()).items[0],variantPrice,variantCompareAtPrice},responseCurrentCart=await fetch("/cart.js");if(responseCurrentCart.status==200){const currentCartData=await responseCurrentCart.json();variantData2.totalPrice=currentCartData.total_price}}else{const cartError=await response.json();cartError.status===404?this.showError(cartError.description):this.showError("Stock insuficiente.")}}catch(error){console.error(`Error: ${error}`),this.showError(`Ocurri\xF3 un error: ${error}`)}}showCartNotification(variant){const notificationElem=document.querySelector("#notification");if(notificationElem!==null){const splitTitle=title2=>[title2.replace(/^\w+\.\d+\s/,""),title2.match(/^\w+\.\d+/)],imageElem=notificationElem.querySelector("#notif-prod-image"),titleElem=notificationElem.querySelector("#notif-prod-title"),skuElem=notificationElem.querySelector("#notif-prod-art-number"),variantOptionElem=notificationElem.querySelector("#notif-prod-variant"),quantityElem=notificationElem.querySelector("#notif-prod-qty"),priceWrapperElem=notificationElem.querySelector("#notif-prod-price"),priceChildElem=notificationElem.querySelector("[data-price]"),subTotalElem=notificationElem.querySelector("#notif-subtotal"),[title,sku]=splitTitle(variant.product_title),variantOption=`${variant.options_with_values[0].name}: ${variant.options_with_values[0].value}`,quantity=variant.quantity,totalPrice=formatMoney(variant.totalPrice,"${{amount}}");let price=variant.variantPrice,compareAtPrice=variant.variantCompareAtPrice;const compareAtPriceExist=compareAtPrice!=="null",discount=Math.round(100-price/compareAtPrice*100);price=formatMoney(price,"${{amount}}"),compareAtPrice=formatMoney(compareAtPrice,"${{amount}}");const fullPriceElem=`
Precio habitual
${compareAtPriceExist?compareAtPrice:price}
`,promoPriceElem=compareAtPriceExist?`
${price}
${price}
Oferta
`:"",discountElem=compareAtPriceExist?`
${discount}% de descuento
`:"",priceComponent=`
${fullPriceElem}
${promoPriceElem}
${discountElem}
`;imageElem.src=variant.featured_image.url,titleElem.textContent=title,skuElem.textContent=sku,variantOptionElem.textContent=variantOption,quantityElem.textContent=quantity,priceChildElem!==null?priceChildElem.innerHTML=priceComponent:priceWrapperElem.innerHTML+=priceComponent,subTotalElem.textContent=totalPrice,notificationElem.classList.add("visible","showme");const hide=setTimeout(()=>{notificationElem.classList.remove("showme");const disappear=setTimeout(()=>{notificationElem.classList.remove("visible"),clearTimeout(disappear)},500);clearTimeout(hide)},4e3)}}activeVariantEvents(){const variantListElem=this.modalElem.querySelectorAll(".quickview__variant-item");variantListElem.length>0&&variantListElem.forEach(variantElem=>{variantElem.addEventListener("click",this.updateQuickview)})}activeQuantityEvents(){const quantityControls=this.modalElem.querySelectorAll(".quickview__quantity-control");quantityControls.length>0&&quantityControls.forEach(control=>{control.addEventListener("click",this.updateQuantity)})}updateQuantity(event){const quantityInput=this.modalElem.querySelector("#quantity-input");quantityInput!==null&&(event.target.classList.contains("control--plus")?quantityInput.value++:quantityInput.value>1?quantityInput.value--:quantityInput.value=1)}updateQuickview(event){event.preventDefault();const variantElemOldSelected=this.modalElem.querySelector(".variant--selected"),variantElemSelected=event.target.closest(".quickview__variant-item"),{variantId,variantImageSrc,variantImageAlt,variantPrice,variantCompareAtPrice,variantTitle}=variantElemSelected.dataset;variantElemOldSelected.classList.remove("variant--selected"),variantElemSelected.classList.add("variant--selected"),this.updateImageComponent(variantImageSrc,variantImageAlt),this.updatePriceComponent(variantPrice,variantCompareAtPrice),this.updateDetailsComponent(variantTitle)}updateDetailsComponent(title){const quickviewVariantValue=this.modalElem.querySelector("#quickview-variant-value");(title!==null||title!==void 0)&&(quickviewVariantValue.textContent=title)}updatePriceComponent(price,compareAtPrice){const compareAtPriceExist=compareAtPrice!=="null",discount=Math.round(100-price/compareAtPrice*100),priceMoney=formatMoney(price,"${{amount}}"),compareAtPriceMoney=formatMoney(compareAtPrice,"${{amount}}"),priceElem=this.modalElem.querySelector("#quickview-price"),compareAtPriceElem=this.modalElem.querySelector("#quickview-compare-at-price"),discountElem=this.modalElem.querySelector("#quickview-discount");compareAtPriceExist?(priceElem.textContent=compareAtPriceMoney,compareAtPriceElem.textContent=priceMoney,discountElem.textContent=`${discount}% de descuento`):priceElem.textContent=priceMoney}updateImageComponent(imageSrc,imageAlt){const imageElem=this.modalElem.querySelector("#quickview-img");imageElem!==null&&(imageElem.src=imageSrc,imageElem.alt=imageAlt)}async buildModal(event){event.preventDefault();const quickviewButton=event.target.localName==="button"?event.target:event.target.closest("button"),{productHandle}=quickviewButton.dataset,productData=await this.getProductData(productHandle);this.quickviewStructureElem.innerHTML=`
${this.buildImageComponent(quickviewButton,productData)}
${this.buildInfoComponent(productData)}
${this.buildMessageComponent(productData)}
${this.buildVariantsComponent(productData)}
${this.buildOptionsComponent(productData)}
`,this.activeVariantEvents(),this.activeQuantityEvents(),this.activeAddToCartEvents(),this.showModal()}buildQuickViewButton(data){return data.metafields.purchase_only_in_store?'Producto a la venta solo en tienda f\xEDsica
':''}buildOptionsComponent(data){return`
`}buildVariantsComponent(data){const firstVariantAvailable=(variantList=>variantList.find(variant=>variant.available?variant:null))(data.variants),buildDetails=optionList=>optionList.map(option=>`
${option.name}:
${firstVariantAvailable.title}
`).join(""),buildVariantsList=(optionList,variantList)=>{const allOptions=[];return optionList.forEach(option=>{allOptions.push(...option.values)}),variantList.reduce((availableVariants,variant)=>{if(variant.available){const variantElem=`
`;availableVariants.push(variantElem)}return availableVariants},[]).join("")};return`
${firstVariantAvailable!==void 0?buildDetails(data.options):""}
${buildVariantsList(data.options,data.variants)}
{const tagFormatted=tag.toLowerCase();messageList.hasOwnProperty(tagFormatted)&&messageListElem.push(`
${messageList[tagFormatted]}
`)}),messageListElem.join("")}buildInfoComponent(data){const splitTitle=title2=>[title2.replace(/^\w+\.\d+\s/,""),title2.match(/^\w+\.\d+/)],[title,sku]=splitTitle(data.title);let price=data.price,compareAtPrice=data.compare_at_price;const compareAtPriceExist=compareAtPrice!==null,discount=Math.round(100-price/compareAtPrice*100);price=formatMoney(price,"${{amount}}"),compareAtPrice=formatMoney(compareAtPrice,"${{amount}}");const fullPriceElem=`
${compareAtPriceExist?compareAtPrice:price}`,promoPriceElem=compareAtPriceExist?`${price}`:"",discountElem=compareAtPriceExist?`${discount}% de descuento`:"";return`
`}buildImageComponent(handleElem,data){const getImageName=url=>{const nameFile=url.split("/").pop().split("?")[0],lastDot=nameFile.lastIndexOf(".");return lastDot!==-1?nameFile.substring(0,lastDot):nameFile},productImageElem=handleElem.closest(".product-card").querySelector(".product-card-image"),productImageName=getImageName(productImageElem.src),imageSrcIndex=data.images.map(imageSrc2=>getImageName(imageSrc2)).findIndex(imageSrc2=>productImageName.includes(imageSrc2)),imageSrc=data.images[imageSrcIndex]||data.featured_image,imageAlt=data.title;return`
`}async getProductData(handle){try{const request=await fetch(`/products/${handle}.js`);if(request.status!==200)return this.showError("Error en la solicitud"),null;const productData=await request.json(),requestMetafields=await fetch(`/products/${handle}?view=metafields`);if(requestMetafields.status==200){const metafieldData=await requestMetafields.json();productData.metafields=metafieldData}return productData}catch(error){console.error(`Error: ${error}`),this.showError(`Ocurri\xF3 un error: ${error}`)}}showModal(){this.modalElem.classList.add("active")}closeModal(){this.modalElem.classList.remove("active")}}window.customElements.get(nameCustomElement)||window.customElements.define(nameCustomElement,QuickviewComponent);
//# sourceMappingURL=/cdn/shop/t/188/assets/quickview-component.js.map?v=19555786808805090561757088793