/*! Copyright (c) Safe As Milk. All rights reserved. */import Cart from"cart-store";import Cookies from"js-cookie";import plugins from"cart-plugins";import{debounce,formatMoney}from"utils";class InteractiveCart extends HTMLElement{#cartDraw;#controlHeightAtValue;#resizeObserver;static#plugins={};connectedCallback(){this.id=this.getAttribute("id"),this.form=this.querySelector("form"),this.cart=Cart.getState().cart,this.freeShippingBar=this.querySelector("free-shipping-bar"),this.#cartDraw=this.closest(".modal--cart"),this.#controlHeightAtValue=null,this.#resizeObserver=null,this.getAttribute("height-control")&&this.#cartDraw&&(this.#controlHeightAtValue=Number(this.getAttribute("height-control")),this.#resizeObserver=new ResizeObserver(debounce(this.#onResize.bind(this),100)),this.#resizeObserver.observe(this.#cartDraw)),this.#render(),this.unsubscribe=Cart.subscribe(state=>{this.cart=state.cart,this.#render(),this.#updateCartDiscounts(),this.#updateCartTotal(),this.#updateFreeShipping()})}disconnectedCallback(){this.unsubscribe(),this.#resizeObserver&&(this.#resizeObserver.disconnect(),this.#resizeObserver=null)}static registerPlugin(priority,fn){if(InteractiveCart.#plugins[priority])throw new Error(`Plugin with priority ${priority} is already registered`);InteractiveCart.#plugins[priority]=fn}#onResize(entries){entries.forEach(()=>{const{parentElement}=this,parentElementComputedStyle=window.getComputedStyle(parentElement),gap=Number(parentElementComputedStyle.getPropertyValue("row-gap").replace("px","")),parentElementTopPadding=Number(parentElementComputedStyle.getPropertyValue("padding-top").replace("px","")),siblingElements=Array.from(this.parentElement.querySelectorAll(".cart-draw__announcement, .cart-draw__head, .free-shipping-bar")),cartControls=this.querySelector(".cart__controls");if(!cartControls)return;const blockedHeight=parentElementTopPadding+siblingElements.reduce((total,element)=>total+element.offsetHeight+gap,0)+cartControls.offsetHeight;this.#cartDraw.classList.toggle("is-scrollable",this.#controlHeightAtValue>window.innerHeight-blockedHeight)})}#render(){this.cart.item_count>0?(this.#renderCart(),Object.entries(InteractiveCart.#plugins).sort(([a],[b])=>a-b).forEach(([,fn])=>{fn.call(this,Cart,this,this.cart)})):this.#renderEmptyCart()}#renderCart(){if(this.querySelector("cart-full"))return;const cartFragment=document.getElementById("template-cart").content.cloneNode(!0),cartNote=cartFragment.querySelector("cart-note"),emptyCart=this.querySelector("cart-empty");emptyCart&&emptyCart.remove(),this.appendChild(cartFragment),cartNote&&(cartNote.querySelector("cart-text-input").value=this.cart.note),this.#updateCartDiscounts(),this.#updateCartTotal()}#renderEmptyCart(){if(this.querySelector("cart-empty"))return;const cartEmptyFragment=document.getElementById("template-empty-cart").content.cloneNode(!0),cartFull=this.querySelector("cart-full");cartFull&&cartFull.remove(),this.appendChild(cartEmptyFragment)}#updateFreeShipping(){this.freeShippingBar&&this.freeShippingBar.setAttribute("value",this.cart.total_price)}#updateCartTotal(){const cartTotal=this.querySelector("cart-total");cartTotal&&(cartTotal.innerHTML=formatMoney(this.cart.total_price,window.theme.money_total_price_format))}#updateCartDiscounts(){const discountsContainer=this.querySelector("cart-discounts");if(!discountsContainer)return;const discounts=discountsContainer.querySelector("discount-list"),discountApplications=this.cart.cart_level_discount_applications,discountItems=discountApplications.length>0&&discountApplications[0].hasOwnProperty("discount_application")?discountApplications.reduce((items,{discount_application:{key,title,total_allocated_amount:amount}})=>{const newItems=items,sameKeyItemIndex=newItems.findIndex(i=>i.key===key);return sameKeyItemIndex>-1?(newItems[sameKeyItemIndex].amount+=amount,newItems):(newItems.push({key,title,amount}),newItems)},[]):discountApplications.reduce((items,{key,title,total_allocated_amount:amount})=>(items.push({key,title,amount}),items),[]);this.classList.toggle("has-cart-discounts",discountItems.length);const discountItemsString=JSON.stringify(discountItems);discounts.setAttribute("items",discountItemsString)}}customElements.define("interactive-cart",InteractiveCart);class CartItems extends HTMLElement{connectedCallback(){this.items=Array.from(this.querySelectorAll("cart-item")),this.giftWrappingProductId=this.getAttribute("gift-wrapping-product-id"),this.unsubscribe=Cart.subscribe(state=>{this.items=this.items.reduce((newItems2,item)=>{const key=item.getAttribute("key");return state.cart.items.find(i=>i.key===key)?(newItems2.push(item),newItems2):(item.remove(),newItems2)},[]);const currentItemsKeys=this.items.map(item=>item.key),newItems=[];state.cart.items.forEach((item,i)=>{if(currentItemsKeys.includes(item.key)){const oldItem=this.items.find(j=>j.key===item.key);currentItemsKeys.indexOf(oldItem.key)!==i&&(i===0?this.prepend(oldItem):newItems[i-1].after(oldItem)),newItems.push(oldItem)}else{const newCartItem=CartItems.#createCartItem(item);i===0?this.prepend(newCartItem):newItems[i-1].after(newCartItem),newItems.push(newCartItem)}}),this.items=newItems})}disconnectedCallback(){this.unsubscribe()}static#createCartItem(item){const cartItem=document.getElementById("template-cart-item").content.cloneNode(!0).querySelector("cart-item");return cartItem.setAttribute("key",item.key),cartItem}}customElements.define("cart-items",CartItems);class CartItem extends HTMLElement{#boundRemoveProduct;#debouncedChangeQuantity;#isRendered;static#plugins={};constructor(){super(),this.#debouncedChangeQuantity=debounce(this.#changeQuantity.bind(this),250),this.#boundRemoveProduct=this.#removeProduct.bind(this)}connectedCallback(){this.key=this.getAttribute("key"),this.item=Cart.getState().cart.items.find(item=>item.key===this.key),this.item&&(this.item.variant_id===Cart.getState().giftWrapping.productId&&(this.giftWrappingItem=!0,this.noQuantityInput=!0,this.noLinks=!0,this.giftWrappingMessageEnabled=Cart.getState().giftWrapping.giftMessageEnabled,this.giftWrappingMessage=Cart.getState().cart.attributes["gift-wrapping-message"]||""),this.image=this.querySelector("cart-item-image-container img"),this.imageContainerRatio=this.getAttribute("image-container-ratio").trim(),this.imageFit=this.hasAttribute("image-fit"),this.details=this.querySelector("cart-item-details"),this.#isRendered=this.hasAttribute("rendered"),this.#isRendered||this.#render(),this.quantity=this.querySelector("quantity-input"),this.removeItemButton=this.querySelector("[cart-item-remove"),setTimeout(()=>{this.quantity&&this.quantity.addEventListener("update",this.#debouncedChangeQuantity),this.removeItemButton&&this.removeItemButton.addEventListener("click",this.#boundRemoveProduct)}),this.unsubscribe=Cart.subscribe((state,prevState)=>{if(state.lineItemsBeingUpdated.length>0&&this.#renderError(),state.lineItemsBeingUpdated.includes(this.key))this.#toggleSpinner(!0);else{const newItem=state.cart.items.find(item=>item.key===this.key);if(newItem&&prevState.lineItemsBeingUpdated.includes(this.key)&&this.#toggleSpinner(!1),!state.lineItemsBeingUpdated.includes(this.key))if(this.quantity&&this.quantity.value!==newItem.quantity)this.quantity.value=newItem.quantity;else{const quantityDisplay=this.querySelector("quantity-display");quantityDisplay&&(quantityDisplay.innerHTML=newItem.quantity)}this.item=newItem,this.#clearTotalPrice(),this.#renderTotalPriceAndDiscounts(),this.#runPostRenderFunctions()}}),setTimeout(()=>this.#runPostRenderFunctions))}disconnectedCallback(){this.unsubscribe&&this.unsubscribe(),this.quantity&&this.quantity.removeEventListener("update",this.#debouncedChangeQuantity),this.removeItemButton&&this.removeItemButton.removeEventListener("click",this.#boundRemoveProduct)}static registerPlugin(priority,fn){if(CartItem.#plugins[priority])throw new Error(`Plugin with priority ${priority} is already registered`);CartItem.#plugins[priority]=fn}#runPostRenderFunctions(){Object.entries(CartItem.#plugins).sort(([a],[b])=>a-b).forEach(([,fn])=>{fn.call(this,Cart,this,this.item)})}#render(){this.querySelectorAll("a[cart-item-url]").forEach(link=>{if(this.noLinks){const div=document.createElement("div");link.hasAttribute("class")&&div.setAttribute("class",link.getAttribute("class")),link.hasAttribute("style")&&div.setAttribute("style",link.getAttribute("style")),div.innerHTML=link.innerHTML,link.replaceWith(div),this.image=this.querySelector("cart-item-image-container img")}else link.setAttribute("href",this.item.url)}),this.#setImage(),this.imageContainerRatio==="natural"?this.image.closest(".o-ratio").style.paddingBottom=`${1/(this.item.featured_image?this.item.featured_image.aspect_ratio:1)*100}%`:this.image.closest(".o-ratio").style.paddingBottom=null,this.#updateSkeleton(),this.querySelector("cart-item-title").innerHTML=this.item.product_title;const metaItemTemplate=document.getElementById("template-cart-item-meta").content,vendor=this.querySelector("cart-item-vendor");if(vendor&&(vendor.appendChild(metaItemTemplate.cloneNode(!0)),vendor.querySelector("property-value").innerHTML=this.item.vendor),this.item.variant_title&&!this.item.variant_title.includes("Default")){const defaultProperty=this.querySelector("cart-item-default-property");defaultProperty.appendChild(metaItemTemplate.cloneNode(!0)),defaultProperty.querySelector("property-value").innerHTML=this.item.variant_title}if(Object.keys(this.item.properties||{}).length>0){const propertyItemTemplate=document.getElementById("template-cart-item-property").content,properties=this.querySelector("cart-item-properties");Object.entries(this.item.properties).forEach(([name,value])=>{if(value!==""&&name.slice(0,1)!=="_"){const propertyTemplate=propertyItemTemplate.cloneNode(!0);let propertyName=name;this.item.gift_card&&name==="Recipient email"?propertyName=window.theme.localize("GIFT_CARD_RECIPIENT_EMAIL"):this.item.gift_card&&name==="Recipient name"?propertyName=window.theme.localize("GIFT_CARD_RECIPIENT_NAME"):this.item.gift_card&&name==="Recipient message"&&(propertyName=window.theme.localize("GIFT_CARD_RECIPIENT_MESSAGE")),propertyTemplate.querySelector("property-name").innerHTML=propertyName,propertyTemplate.querySelector("property-value").innerHTML=value.includes("/uploads/")?`${value.split("/").pop()}`:value,properties.appendChild(propertyTemplate)}})}if(this.item.selling_plan_allocation){const sellingPlanAllocation=this.querySelector("cart-item-selling-plan-allocation");sellingPlanAllocation.appendChild(metaItemTemplate.cloneNode(!0)),sellingPlanAllocation.querySelector("property-value").innerHTML=`${this.item.selling_plan_allocation.selling_plan.name}${this.item.selling_plan_allocation.compare_at_price&&this.item.selling_plan_allocation.compare_at_price!==this.item.selling_plan_allocation.price?` (-${Math.round((1-this.item.selling_plan_allocation.price/this.item.selling_plan_allocation.compare_at_price)*100)}%)`:""}`}const sku=this.querySelector("cart-item-sku");if(sku&&this.item.sku&&(sku.appendChild(metaItemTemplate.cloneNode(!0)),sku.querySelector("property-value").innerHTML=this.item.sku),this.item.unit_price_measurement){const itemUnitPrice=this.querySelector("cart-item-unit-price"),unitPriceTemplate=document.getElementById("template-unit-price").content;itemUnitPrice.appendChild(unitPriceTemplate.cloneNode(!0));const baseUnit=`${this.item.unit_price_measurement.reference_value!==1?this.item.unit_price_measurement.reference_value:""}${this.item.unit_price_measurement.reference_unit}`;itemUnitPrice.querySelector("unit-price").innerHTML=formatMoney(this.item.unit_price,window.theme.money_format),itemUnitPrice.querySelector("base-unit").innerHTML=baseUnit}if(this.giftWrappingItem&&this.giftWrappingMessageEnabled){const giftWrappingMessageTemplate=document.getElementById("template-cart-gift-wrapping-message").content;this.querySelector("cart-item-micro-copy").appendChild(giftWrappingMessageTemplate.cloneNode(!0)),this.classList.add("cart-item--full-details"),this.querySelector("cart-text-input").value=this.giftWrappingMessage}if(this.noQuantityInput){const quantityDisplay=document.createElement("quantity-display");quantityDisplay.classList.add("cart-item__qty-display"),quantityDisplay.innerHTML=this.item.quantity,this.querySelector("cart-item-quantity").appendChild(quantityDisplay)}else{const quantityElement=document.getElementById("template-quantity-input").content.cloneNode(!0);this.quantity=quantityElement.querySelector("quantity-input");const quantityInput=quantityElement.querySelector('input[type="number"]');quantityInput.setAttribute("id",`updates_${this.item.key}`),quantityInput.setAttribute("name","updates[]"),this.querySelector("cart-item-quantity").appendChild(this.quantity),setTimeout(()=>{this.quantity.value=this.item.quantity}),this.removeItemButton=this.querySelector("button[cart-item-remove]")}this.#renderTotalPriceAndDiscounts(),this.setAttribute("rendered","")}#setImage(srcsetWidths=[120,240,360,480]){if(!this.image)return;const imageData=this.item.featured_image;if(imageData&&imageData.url){const{width,height,url}=imageData,imageContainerRatio=this.imageContainerRatio!=="natural"?this.imageContainerRatio.split(":").reduce((ratio,value)=>ratio!==0?value/ratio:value,0):null,aspectRatio=width/height,uncroppedImage=this.imageContainerRatio==="natural"||imageContainerRatio&&this.imageFit;let masterWidth=width,masterHeight=height;uncroppedImage||(masterHeight=Math.round(masterWidth*imageContainerRatio),masterHeight>height&&(masterHeight=height,masterWidth=Math.round(masterHeight/imageContainerRatio)));const srcset=srcsetWidths.reduce((srcSet,srcWidth)=>{const srcHeight=Math.round(uncroppedImage?srcWidth/aspectRatio:srcWidth*imageContainerRatio);return srcWidth>masterWidth||srcHeight>masterHeight?srcSet:`${srcSet}${url}${url.includes("?")?"&":"?"}width=${srcWidth}${uncroppedImage?"":`&height=${srcHeight}&crop=center`} ${srcWidth}w ${srcHeight}h, `},""),masterSrc=uncroppedImage?url:`${url}${url.includes("?")?"&":"?"}width=${masterWidth}&height=${masterHeight}&crop=center`;this.image.setAttribute("src",masterSrc),this.image.setAttribute("srcset",srcset),this.image.setAttribute("width",masterWidth),this.image.setAttribute("height",masterHeight)}this.image.setAttribute("alt",`Image for ${this.item.title}`)}#updateSkeleton(){if(!this.image)return;const skeleton=this.image.previousElementSibling&&this.image.previousElementSibling.tagName.toLowerCase()==="image-skeleton"?this.image.previousElementSibling:null;if(skeleton){const svg=skeleton.querySelector("svg"),rect=svg.querySelector("rect"),width=this.image.getAttribute("width"),height=this.image.getAttribute("height");skeleton.setAttribute("aria-label",`Loading image for ${this.item.title}`),svg.setAttribute("width",width),svg.setAttribute("height",height),svg.setAttribute("viewBox",`0 0 ${width} ${height}`),rect.setAttribute("width",width),rect.setAttribute("height",height)}}#toggleSpinner(visible=!0){if(visible){this.#clearTotalPrice();const quantityInputTemplate=document.getElementById("template-spinner").content;this.querySelector("cart-item-spinner").appendChild(quantityInputTemplate.cloneNode(!0))}else this.querySelector("cart-item-spinner").innerHTML=""}#clearTotalPrice(){const priceContainer=this.querySelector("cart-item-original-line-price").parentElement;if(priceContainer){const priceContainerWidth=priceContainer.offsetWidth,priceContainerHeight=priceContainer.offsetHeight;priceContainer.style.width=`${priceContainerWidth}px`,priceContainer.style.height=`${priceContainerHeight}px`}this.querySelector("cart-item-original-line-price").innerHTML="",this.querySelector("cart-item-final-line-price").innerHTML=""}#renderTotalPriceAndDiscounts(){const originalLinePrice=this.querySelector("cart-item-original-line-price"),finalLinePrice=this.querySelector("cart-item-final-line-price"),priceTemplate=document.getElementById("template-price").content;this.item.original_line_price!==this.item.final_line_price?(originalLinePrice.appendChild(priceTemplate.cloneNode(!0)),originalLinePrice.querySelector(".price").classList.add("price--original"),originalLinePrice.querySelector("money-amount").innerHTML=formatMoney(this.item.original_line_price,window.theme.money_format),finalLinePrice.appendChild(priceTemplate.cloneNode(!0)),finalLinePrice.querySelector(".price").classList.add("price--sale"),finalLinePrice.querySelector("money-amount").innerHTML=formatMoney(this.item.final_line_price,window.theme.money_format)):(originalLinePrice.appendChild(priceTemplate.cloneNode(!0)),originalLinePrice.querySelector("money-amount").innerHTML=formatMoney(this.item.final_line_price,window.theme.money_format));const discounts=this.querySelector("cart-item-discounts").querySelector("discount-list"),discountItems=JSON.stringify(this.item.line_level_discount_allocations.reduce((items,{amount,discount_application:{key,title}})=>(items.push({key,title,amount}),items),[]));discounts.setAttribute("items",discountItems),this.classList.toggle("has-discounts",this.item.line_level_discount_allocations.length>0);const priceContainer=this.querySelector("cart-item-original-line-price").parentElement;priceContainer&&(priceContainer.style.width="",priceContainer.style.height="")}#renderError(errorText=""){const errorContainer=this.querySelector("cart-item-errors");this.classList.toggle("has-errors",errorText),errorContainer.innerHTML=`