1const collectionNavigationSelect=document.querySelector(".collection-navigation-select");collectionNavigationSelect&&collectionNavigationSelect.addEventListener("change",function(event){if(event.target.classList.contains("bundle-select"))return;const selectedValue=event.target.value;window.location.href=selectedValue}),document.querySelector(".shopify-section--mini-cart").addEventListener("click",event=>{const eventPath=event.composedPath?event.composedPath().slice(0,-2):[];if(!eventPath.some(node=>node instanceof DocumentFragment)){for(const element of eventPath)if(element.classList){if(element.classList.contains("line-item-remove-container")){const lineItem=element?.closest(".line-item");if(!lineItem)continue;const removeButton=lineItem?.querySelector(".line-item__remove-button");if(!removeButton)continue;if(lineItem.closest("form").setAttribute("data-loading",""),removeButton.tagName==="BUTTON"&&removeButton.hasAttribute("data-bundle-id")){const bundleId=removeButton.getAttribute("data-bundle-id");fetch(window.Shopify.routes.root+"cart.js").then(response=>response.json()).then(({items})=>{const updates={};return items.forEach(it=>{it.properties._bundle_id===bundleId&&(updates[it.key]=0)}),fetch(window.Shopify.routes.root+"cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates})}).then(response=>response.json().then(json=>{setTimeout(async()=>{const updatedCartContent=await freeGiftHandler(json);console.log("Cart new elements click handler"),document.documentElement.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:{cart:updatedCartContent}})),document.getElementById("mini-cart").open=!0},100)}))})}else removeButton.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}));break}else if(element.classList.contains("subscription-incentive-button")){const lineItem=element?.closest(".line-item");if(!lineItem)continue;const sellingMethodSelect=lineItem.querySelector(".line-item__subscription-select");if(!sellingMethodSelect)continue;event.preventDefault(),lineItem.querySelector(".quantity-selector").setAttribute("data-loading","");const currentOption=sellingMethodSelect.selectedOptions[0];sellingMethodSelect.value=sellingMethodSelect.querySelector("[data-subscription]").value,currentOption.value!==sellingMethodSelect.value&&sellingMethodSelect.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}));break}else if(element.classList.contains("recommendation-atc")){const recommendationCard=element.closest(".cart-recommendation-card");if(!recommendationCard)continue;const variantId=parseInt(recommendationCard.getAttribute("data-variant-id"));if(!variantId)continue;addRecommendationProductToCart(variantId);break}}}}),document.querySelector(".shopify-section--mini-cart").addEventListener("change",event=>{const eventPath=event.composedPath?event.composedPath().slice(0,-2):[];if(!eventPath.some(node=>node instanceof DocumentFragment))for(const element of eventPath){const changeAction=element?.getAttribute("data-change-action");if(changeAction&&changeAction==="update-line-selling-plan"){updateLineSellingPlan(element);break}}});async function updateLineSellingPlan(sellingMethodSelect){const lineItem=sellingMethodSelect.closest(".line-item"),variantId=parseInt(lineItem.getAttribute("data-variant-id")),quantity=parseInt(lineItem.getAttribute("data-quantity")),lineKey=lineItem.getAttribute("data-line-key"),selectedOption=lineItem.querySelector("select option:checked"),sellingPlanId=parseInt(selectedOption.getAttribute("data-option-selling-plan-id")),cartForm=sellingMethodSelect.closest("form");cartForm.style.pointerEvents="none";const subscriptionValue=sellingMethodSelect.options[1].value;sellingMethodSelect.value===sellingMethodSelect.options[0].value&&cartForm.setAttribute("data-loading","");const addToCartBody={items:[{id:variantId,quantity}]};sellingMethodSelect.value===subscriptionValue&&(addToCartBody.items[0].selling_plan=sellingPlanId);try{const cartUpdateJson=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:{[lineKey]:0}})}).then(response=>response.json()),addToCartJson=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(addToCartBody)}).then(response=>response.json()),updatedCartContent=await freeGiftHandler();document.documentElement.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:{cart:updatedCartContent}}))}catch(error){console.error("Error updating the line in the cart",error)}}async function addRecommendationProductToCart(variantId){const addToCartBody={items:[{id:variantId,quantity:1}]};try{const addToCartJson=await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(addToCartBody)}).then(response=>response.json()),updatedCartContent=await freeGiftHandler();setTimeout(()=>{document.documentElement.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:{cart:updatedCartContent}})),document.getElementById("mini-cart").open=!0},1800)}catch(error){console.error("Error adding the recommendation product to the cart",error)}}const mainArticle=document.querySelector(".shopify-section--main-article");mainArticle&&mainArticle.addEventListener("click",event=>{const eventPath=event.composedPath?event.composedPath().slice(0,-2):[];if(!eventPath.some(node=>node instanceof DocumentFragment)){for(const element of eventPath)if(element.classList&&element.classList.contains("associated-product-atc")){const associatedProductCard=element.closest(".associated-product-container");if(!associatedProductCard)continue;const variantId=parseInt(associatedProductCard.getAttribute("data-variant-id"));if(!variantId)continue;addRecommendationProductToCart(variantId);break}}}),document.addEventListener("click",event=>{const eventPath=event.composedPath?event.composedPath().slice(0,-2):[];if(!eventPath.some(node=>node instanceof DocumentFragment))for(const element of eventPath){const clickAction=element?.getAttribute("data-click-action");if(clickAction){if(clickAction==="toggle-mobile-video-play"||clickAction==="toggle-desktop-video-play"){const associatedVideo=cl
1ickAction==="toggle-mobile-video-play"?element.parentElement.querySelector(".image-overlay__mobile--image"):element.parentElement.querySelector(".image-overlay__desktop--image");element.hasAttribute("data-play")?(associatedVideo.classList.contains("video-wrapper")?associatedVideo.querySelector("iframe").contentWindow.postMessage(JSON.stringify({event:"command",func:"pauseVideo",args:""}),"*"):associatedVideo.pause(),element.removeAttribute("data-play")):(associatedVideo.classList.contains("video-wrapper")?associatedVideo.querySelector("iframe").contentWindow.postMessage(JSON.stringify({event:"command",func:"playVideo",args:""}),"*"):associatedVideo.play(),element.setAttribute("data-play",""));break}else if(clickAction==="toggle-mega-menu"){if(event.preventDefault(),element.nextElementSibling.classList.contains("is-closing")||element.nextElementSibling.classList.contains("is-opening"))break;element.getAttribute("aria-expanded")==="true"===!0?(element.setAttribute("aria-expanded","false"),element.nextElementSibling.hidden=!0,element.nextElementSibling.style.zIndex="-1"):(element.setAttribute("aria-expanded","true"),element.nextElementSibling.hidden=!1,element.nextElementSibling.style.zIndex="1");break}}}}),document.addEventListener("DOMContentLoaded",()=>{document.querySelectorAll(".shopify-section--scrolling-text").forEach(scrollingTextSection=>{let totalTextWidth=0;const scrollingTextList=scrollingTextSection.querySelectorAll(".scrolling-text"),scrollingTextContainerList=scrollingTextSection.querySelectorAll(".scrolling-text-container");for(const scrollingText of scrollingTextList)totalTextWidth+=scrollingText.offsetWidth;const textCopyCount=Math.ceil(2e3/totalTextWidth)+1;for(let i=0;i<textCopyCount;i++)for(const scrollingTextContainer of scrollingTextContainerList){const containerCopy=scrollingTextContainer.cloneNode(!0);scrollingTextContainer.parentElement.appendChild(containerCopy)}})}),document.addEventListener("click",event=>{const eventPath=event.composedPath?event.composedPath().slice(0,-2):[];if(!eventPath.some(node=>node instanceof DocumentFragment))for(const element of eventPath){if(!element.hasAttribute("data-recommendation-href"))continue;event.preventDefault();const recommendationHref=element.getAttribute("data-recommendation-href");window.location.href=recommendationHref}});const reviewNodes=document.querySelectorAll(".block-reviews .rating"),addReviewCount=(container,parent)=>{const reviewsElement=container.querySelector("a"),span=document.createElement("span");if(span.classList.add("rating__caption"),reviewsElement?.getAttribute("aria-label")?.split(" ")[0]!==void 0){const reviewsCount=reviewsElement.getAttribute("aria-label").split(" ")[0];return span.innerHTML=`(${reviewsCount})`,span}else{const url=`${themeVariables.routes.rootUrl}products/${container.parentElement.dataset.productHandle}#reviews`;return span.innerHTML=`<a href="${url}">${themeVariables.strings.emptyReviews}</a>`,parent.classList.add("no-reviews"),span}};reviewNodes.forEach(reviewNode=>{new MutationObserver((mutationList,observer)=>{mutationList.forEach(mutation=>{if(mutation.type==="childList"){const container=mutation.addedNodes[1];if(!container)return;const span=addReviewCount(container,reviewNode.parentElement);span&&reviewNode.parentElement.appendChild(span.cloneNode(!0))}})}).observe(reviewNode,{childList:!0})});const productSectionList=document.querySelectorAll(".shopify-section--main-product");productSectionList.length&&productSectionList.forEach(productSection=>{const mainAddToCartButton=productSection.querySelector("#AddToCart"),stickyAddToCartContainer=productSection.querySelector(".sticky-add-to-cart-container");mainAddToCartButton&&stickyAddToCartContainer&&(stickyAddToCartContainer.querySelector("button").addEventListener("click",event=>{event.preventDefault();const clickEvent=new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window});mainAddToCartButton.dispatchEvent(clickEvent)}),new IntersectionObserver(entries=>{entries.forEach(entry=>{entry.isIntersecting?(stickyAddToCartContainer.removeAttribute("data-visible"),document.documentElement.removeAttribute("data-sticky-add-to-cart-visible")):(stickyAddToCartContainer.setAttribute("data-visible",""),document.documentElement.setAttribute("data-sticky-add-to-cart-visible",""))})},{rootMargin:"-80px 0px 100000px 0px",threshold:0}).observe(mainAddToCartButton))});const readMore=class extends HTMLElement{constructor(){super()}connectedCallback(){this.readMoreButton.addEventListener("click",()=>this.onReadMoreClick()),this.readLessButton.addEventListener("click",()=>this.onReadLessClick())}disconnectedCallback(){this.readMoreButton.removeEventListener("click",()=>this.onReadMoreClick())}get readMoreButton(){return this.querySelector("[data-read-more]")}get readLessButton(){return this.querySelector("[data-read-less]")}get lessContentContainer(){return this.querySelector("[data-less]")}get moreContentContainer(){return this.querySelector("[data-more]")}onReadMoreClick(){this.moreContentContainer.hidden=!1,this.lessContentContainer.hidden=!0}onReadLessClick(){this.moreContentContainer.hidden=!0,this.lessContentContainer.hidden=!1}};customElements.get("read-more")||customElements.define("read-more",readMore);const DesktopMediaList=class extends HTMLDivElement{constructor(){super()}connectedCallback(){const galleryUpdatedEvent=new CustomEvent("galleryUpdated");document.dispatchEvent(galleryUpdatedEvent),this.medias.forEach(media=>{media.addEventListener("click",()=>this.onMediaClick(media))})}get medias(){return this.querySelectorAll(".desktop-media-container")}get desktopMediaZoom(){return document.querySelector(".desktop-media-zoom")}onMediaClick(media){const index=media.dataset.index;this.desktopMediaZoom.mediaContainer.setAttribute("data-current-index",index),this.desktopMediaZoom.currentIndex.textContent=index,this.desktopMediaZoom.openModal()}};window.customElements.get("desktop-media-list")||window.customElements.define("desktop-media-list",DesktopMediaList,{extends:"div"});const DesktopMediaZoom=class extends HTMLElement{constructor(){super()}connectedCallback(){this.addEventListener("click",event=>{this.mediaContainer.contains(event.target)||this.closeModal()}),this.closeButton.addEventListener("click",()=>this.closeModal()),this.previousButton.addEventListener("click",()=>this.onPreviousClick()),this.nextButton.addEventListener("click",()=>this.onNextButtonClick()),this.startX=0,this.startY=0,this.addEventListener("pointerdown",event=>{event.target.closest(".desktop-media-item-inner").style.transform.includes("scale(1, 1)")&&(this.startX=event.clientX,this.startY=event.clientY)},{capture:!0}),this.addEventListener("pointerup",event=>{if(event.target.closest(".desktop-media-item-inner").style.transform.includes("scale(1, 1)")){const deltaX=event.clientX-this.startX,deltaY=event.clientY-this.startY;Math.abs(deltaX)>Math.abs(deltaY)&&(deltaX>50?this.onPreviousClick():deltaX<-50&&this.onNextButtonClick())}},{capture:!0})}get mediaContainer(){return this.querySelector(".desktop-media-container")}get mediaCount(){return parseInt(this.mediaContainer.dataset.mediaCount)}get closeButton(){return this.querySelector(".drawer__close-button")}get previousButton(){return this.querySelector(".drawer__control-button[data-action='prev']")}get nextButton(){return this.querySelector(".drawer__control-button[data-action='next']")}get currentIndex(){return this.querySelector(".drawer__control-count-current")}openModal(){this.setAttribute("data-open",""),document.documentElement.classList.add("lock-all"),this.mediaContainer.dis
1patchEvent(new CustomEvent("MediaZoomOpened"))}closeModal(){this.removeAttribute("data-open"),document.documentElement.classList.remove("lock-all")}onPreviousClick(){const currentIndex=this.mediaContainer.dataset.currentIndex;let previousIndex=parseInt(currentIndex)-1;previousIndex<1&&(previousIndex=this.mediaCount),this.mediaContainer.dataset.currentIndex=previousIndex,this.currentIndex.textContent=previousIndex,this.mediaContainer.dispatchEvent(new CustomEvent("MediaZoomOpened"))}onNextButtonClick(){const currentIndex=this.mediaContainer.dataset.currentIndex;let nextIndex=parseInt(currentIndex)+1;nextIndex>this.mediaCount&&(nextIndex=1),this.mediaContainer.dataset.currentIndex=nextIndex,this.currentIndex.textContent=nextIndex,this.mediaContainer.dispatchEvent(new CustomEvent("MediaZoomOpened"))}};window.customElements.get("desktop-media-zoom")||window.customElements.define("desktop-media-zoom",DesktopMediaZoom);function collectBundleItems(bundleId){const items=[];return document.querySelectorAll(`.bundle-children [data-bundle-id="${bundleId}"]`).forEach(el=>{items.push({variantId:parseInt(el.dataset.variantId),quantity:parseInt(el.dataset.quantity),title:el.dataset.title,imageUrl:el.dataset.imageUrl,oneTimePrice:parseFloat(el.dataset.oneTimePrice)/100,oneTimeDiscountPrice:parseFloat(el.dataset.oneTimeDiscountPrice)/100,subscriptionPrice:parseFloat(el.dataset.subscriptionPrice)/100})}),items}function saveBundleToLocalStorage(bundleId,items){localStorage.setItem("editing_bundle_id",bundleId),localStorage.setItem("bundle_builder_items",JSON.stringify(items))}async function clearBundleItemsFromCart(bundleId,bundlePath){const cart=await fetch("/cart.js").then(res=>res.json()),updates={};if(cart.items.forEach(item=>{item.properties&&item.properties._bundle_id===bundleId&&(updates[item.key]=0)}),Object.keys(updates).length===0)return;const updatedCart=await(await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates})})).json(),updatedCartContent=await freeGiftHandler(updatedCart);window.location.pathname===bundlePath&&(window.document.documentElement.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:{cart:updatedCartContent}})),document.getElementById("mini-cart").open=!1)}function redirectToBundleBuilder(bundleId,bundlePath){window.location.pathname.includes(bundlePath)?setTimeout(()=>{const context=document.querySelector("bundle-builder-context");context&&context.dispatchEvent(new CustomEvent("BUNDLE_RESTORE_REQUESTED",{detail:{isEditing:!0}}))},0):setTimeout(()=>{window.location.href=bundlePath},100)}document.addEventListener("click",async e=>{const button=e.target.closest("[data-edit-bundle]");
1if(!button)return;const bundleId=button.dataset.editBundle,bundlePath=button.dataset.path,bundleItems=collectBundleItems(bundleId);saveBundleToLocalStorage(bundleId,bundleItems),await clearBundleItemsFromCart(bundleId,bundlePath),setTimeout(()=>{redirectToBundleBuilder(bundleId,bundlePath)},100)});function getCookieValue(name){const match=document.cookie.match(new RegExp("(^| )"+name+"=([^;]+)"));return match?decodeURIComponent(match[2]):null}function isFirstVisitPeriod(daysThreshold=3){const timestamp=parseInt(getCookieValue("first_visit_time"),10);if(!timestamp||isNaN(timestamp))return!0;const now=Date.now(),msInDay=1440*60*1e3;return(now-timestamp)/msInDay<=daysThreshold}function matchRule(rule,cartItems,cartContent,options={}){const{ignorePathCheck=!1}=options;if(rule.subscription_only&&!cartItems.some(i=>i.selling_plan_allocation)||rule.one_time_only&&cartItems.some(i=>i.selling_plan_allocation)||rule.new_customers_only&&!isFirstVisitPeriod(3)||rule.target_skus?.length&&!rule.target_skus.every(sku=>cartItems.some(i=>i.sku===sku)))return!1;if(rule.target_discount_codes?.length){const appliedCodes=getCartDiscounts(cartContent).map(d=>d.title.toLowerCase()),targetCodes=rule.target_discount_codes.map(c=>c.toLowerCase()),matchesPattern=(code,pattern)=>{if(!code||!pattern)return!1;const regexPattern=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${regexPattern}$`).test(code)},matched=appliedCodes.some(code=>targetCodes.some(pattern=>matchesPattern(code,pattern)));if(console.log("no discounbt match",{rule,appliedCodes}),!matched)return!1}if("minimum_cart_value"in rule&&cartContent.total_price<rule.minimum_cart_value)return!1;const totalQuantity=cartItems.filter(i=>!(i.properties&&i.properties._free_gift)).reduce((sum,i)=>sum+i.quantity,0);return rule.min_cart_items&&totalQuantity<rule.min_cart_items?!1:!(!ignorePathCheck&&rule.target_path&&!window.location.pathname.startsWith(rule.target_path))}async function freeGiftHandler(cartContent){const hasGiftGroups=window.giftGroups?.length>0;if(!hasGiftGroups&&!cartContent)return await fetch("/cart.js").then(res=>res.json());if(!hasGiftGroups)return cartContent;cartContent||(cartContent=await fetch("/cart.js").then(res=>res.json()));const cartItems=cartContent.items,existingGifts=cartItems.filter(item=>item.properties&&item.properties._free_gift),existingGiftSourcePath=existingGifts?.[0]?.properties?._gift_source_path;let bestGift=null;for(const group of window.giftGroups){const{gift_variant_id,rules,gift_priority=99}=group;if(!gift_variant_id||!rules||!rules.length)continue;rules.find(rule=>matchRule(rule,cartItems,cartContent,{ignorePathCheck:!!existingGiftSourcePath}))&&(!bestGift||gift_priority<bestGift.gift_priority)&&(bestGift={variant_id:gift_variant_id,gift_priority})}const giftToKeepId=bestGift?.variant_id,giftsToRemove=existingGifts.filter(gift=>gift.variant_id!==giftToKeepId),giftAlreadyExists=existingGifts.some(gift=>gift.variant_id===giftToKeepId),shouldAddGift=giftToKeepId&&!giftAlreadyExists;if(console.log("shouldAddGift",{shouldAddGift}),console.log("gift what?>?",{giftAlreadyExists,giftsToRemove,giftToKeepId,bestGift}),!shouldAddGift&&!giftsToRemove.length)return cartContent;for(const item of giftsToRemove)try{await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:{[item.key]:0}})})}catch(err){console.error("Error removing gift from cart:",err)}if(shouldAddGift)try{await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:[{id:giftToKeepId,quantity:1,properties:{_free_gift:!0,_gift_source_path:window.location.pathname,_gift_priority:bestGift.gift_priority}}]})})}catch(err){console.error("Error adding gift to cart:",err)}return await new Promise(resolve=>setTimeout(resolve,200)),fetch("/cart.js").then(res=>res.json())}document.addEventListener("DOMContentLoaded",()=>{if(document.querySelectorAll("[data-complementary-select]").forEach(select=>{select.addEventListener("change",function(){const url=select.options[select.selectedIndex].dataset.url;url&&(window.location.href=url)})}),!document.cookie.includes("first_visit_time=")){const now=Date.now();document.cookie=`first_visit_time=${now}; path=/; max-age=${31536e3*2}`}});function getCartDiscounts(cart){const cartLevelDiscounts=cart.cart_level_discount_applications?.map(d=>({title:d.title,type:d.value_type,value:d.value,source:"cart"}))||[],itemLevelDiscounts=cart.items.flatMap(item=>item.line_level_discount_allocations||[]).map(a=>{const d=a.discount_application;return d?.title?{title:d.title,type:d.value_type,value:d.value,source:"item"}:null}
1).filter(Boolean),uniqueMap=new Map;return[...cartLevelDiscounts,...itemLevelDiscounts].forEach(d=>{const key=`${d.title}::${d.source}`;uniqueMap.has(key)||uniqueMap.set(key,d)}),[...uniqueMap.values()]}async function updateAnnouncementBar(discounts){const announcementBar=document.querySelector("announcement-bar"),slideList=announcementBar?.querySelector(".announcement-bar__list");if(!announcementBar||!slideList)return;if(slideList.querySelectorAll("[data-discount-announcement]").forEach(el=>el.remove()),discounts.length===0){if(announcementBar.items=[...slideList.querySelectorAll("announcement-bar-item")],clearInterval(announcementBar._interval),announcementBar.items.length>0){await customElements.whenDefined("announcement-bar-item"),announcementBar.items.forEach((item,i)=>item.selected=i===0);try{await announcementBar.select(0,!0)}catch(err){console.warn("Announcement bar select error (empty):",err)}announcementBar.autoPlay&&announcementBar._startPlayer?.()}return}discounts.forEach(d=>{const slide=document.createElement("announcement-bar-item");slide.setAttribute("data-discount-announcement",""),slide.className="announcement-bar__item",slide.innerHTML=` 2 <div class="announcement-bar__message text--xsmall" style="font-weight: normal;"> 3 <span>Your code ${d.title} has been applied for ${d.type==="percentage"?` ${parseFloat(d.value).toFixed(0)}% off`:""} at checkout</span> 4 </div>`,slideList.prepend(slide)}),announcementBar.items=[...slideList.querySelectorAll("announcement-bar-item")],await customElements.whenDefined("announcement-bar-item"),announcementBar.items.forEach((item,index)=>{item.selected=index===0});const current=announcementBar.items[announcementBar.selectedIndex];if(current&&typeof current.deselect=="function")try{await current.deselect(!1)}catch(err){console.warn("Announcement bar deselect error:",err)}clearInterval(announcementBar._interval);try{await announcementBar.select(0,!0)}catch(err){console.warn("Announcement bar select error:",err)}announcementBar.autoPlay&&announcementBar._startPlayer?.()}function updateMiniCartSavings(cart,discounts){const labelEl=document.querySelector("[data-discount-text]");if(!labelEl)return;const totalSaved=(cart.total_discount||0)/100;let finalText=labelEl.getAttribute("data-discount-text")||"You\u2019ve saved";if(totalSaved>0&&discounts.length>0){const titles=discounts.map(d=>d.title).join(", ");finalText+=` ${titles}`}labelEl.textContent=finalText}document.documentElement.addEventListener("cart:refresh",async()=>{const cart=await fetch("/cart.js").then(r=>r.json()),discounts=getCartDiscounts(cart);console.log("cart discounts",{discounts}),updateAnnouncementBar(discounts),requestAnimationFrame(()=>{updateMiniCartSavings(cart,discounts)})});class TieredProgressBar extends HTMLElement{constructor(){super(),this._els={},this._markers=[],this._labels=[]}connectedCallback(){this._parseAttributes(),this._buildStaticDOM(),this._updateUI(),document.documentElement.addEventListener("cart:updated",this._onCartUpdated.bind(this))}_parseAttributes(){const tiersAttr=this.getAttribute("data-tiers")||"",currency=this.getAttribute("data-currency")||"USD",subtotal=parseInt(this.getAttribute("data-subtotal")||"0",10)||0;this.currency=currency,this.subtotal=subtotal,this.market=this.getAttribute("data-market")||"",this.tiers=tiersAttr.split(",").map(p=>p.trim()).filter(Boolean).map(pair=>{const idx=pair.indexOf(":");if(idx===-1)return null;const amount=parseInt(pair.slice(0,idx).trim(),10)||0,label=pair.slice(idx+1).trim();return{amount,label}}).filter(Boolean).sort((a,b)=>a.amount-b.amount),this.isSingle=this.tiers.length===1,this.maxAmount=this.tiers.length?this.tiers[this.tiers.length-1].amount:0,this.twoStopLayout=this.tiers.length===2&&this.tiers.some(t=>/gift|gwp/i.test(t.label)),this.GUTTER_PCT=this.isSingle||this.twoStopLayout?0:25,this.usablePct=100-this.GUTTER_PCT}_onCartUpdated(event){if(!event.detail?.cart)return;const cart=event.detail.cart;let total=0;for(const item of cart.items||[])item.requires_shipping&&(total+=item.final_line_price||0);let cartLevelDiscount=0;for(const app of cart.cart_level_discount_applications||[])cartLevelDiscount+=app.total_allocated_amount||0;this.subtotal=Math.max(0,total-cartLevelDiscount),(cart.items||[]).some(item=>item.selling_plan_allocation)&&this.market==="us"&&(this.subtotal=this.maxAmount),this._updateUI()}_buildStaticDOM(){if(this.classList.add("tiered-progress"),this.classList.toggle("tiered-progress--single",this.isSingle),!this.tiers.length){this.innerHTML="";return}const track=document.createElement("div");track.className="tiered-progress__track",track.setAttribute("role","progressbar"),track.setAttribute("aria-valuemin","0"),track.setAttribute("aria-valuemax",String(this.maxAmount));const bar=document.createElement("div");bar.className="tiered-progress__bar";
4const fill=document.createElement("div");fill.className="tiered-progress__bar-fill";const markersWrap=document.createElement("div");markersWrap.className="tiered-progress__markers";const labelsWrap=document.createElement("div");labelsWrap.className="tiered-progress__labels",this._markers=[],this._labels=[];for(const t of this.tiers){const left=this._posFor(t.amount),m=document.createElement("div");m.className="tiered-progress__marker is-locked",m.style.left=`${left}%`,m.setAttribute("title",t.label),markersWrap.appendChild(m),this._markers.push(m);const l=document.createElement("div");l.className="tiered-progress__label is-locked",l.style.left=`${left}%`,l.textContent=t.label,labelsWrap.appendChild(l),this._labels.push(l),this._applyEdgeAttr(left,l,m)}bar.appendChild(fill),track.appendChild(bar),track.appendChild(markersWrap),track.appendChild(labelsWrap);const message=document.createElement("div");message.className="tiered-progress__message",this.innerHTML="",this.appendChild(track),this.appendChild(message),this._els={track,fill,message,markersWrap,labelsWrap}}_edgeFor(leftPct){return leftPct<=.5?"start":leftPct>=100-.5?"end":""}_applyEdgeAttr(leftPct,labelEl,markerEl){const edge=this._edgeFor(leftPct);edge&&(labelEl&&labelEl.setAttribute("data-edge",edge),markerEl&&markerEl.setAttribute("data-edge",edge))}_updateUI(){if(!this.tiers.length)return;const subtotal=this.subtotal,maxAmount=this.maxAmount;this._els.track.setAttribute("aria-valuenow",String(Math.min(subtotal,maxAmount)));let nextTier=null,highestUnlocked=null;for(const tier of this.tiers)subtotal>=tier.amount?highestUnlocked=tier:nextTier||(nextTier=tier);const message=nextTier?`Spend ${this._formatMoney(nextTier.amount-subtotal)} more to unlock ${nextTier.label}`:`You unlocked ${highestUnlocked?highestUnlocked.label:this.tiers[0].label}`;this._els.message.textContent=message;let targetPercent;if(this.twoStopLayout){const low=this.tiers[0],high=this.tiers[1],half=this.usablePct/2;if(subtotal<=0)targetPercent=0;else if(subtotal<low.amount)targetPercent=Math.min(half,subtotal/Math.max(1,low.amount)*half);else if(subtotal<high.amount){const span=Math.max(1,high.amount-low.amount),overLow=subtotal-low.amount;targetPercent=half+Math.min(half,overLow/span*half)}else targetPercent=this.usablePct}else targetPercent=Math.round(Math.min(this.usablePct,subtotal/Math.max(1,maxAmount)*this.usablePct));this._els.fill.style.width=`${targetPercent}%`,this.tiers.forEach((t,i)=>{const unlocked=subtotal>=t.amount;this._markers[i].classList.toggle("is-unlocked",unlocked),this._markers[i].classList.toggle("is-locked",!unlocked),this._labels[i].classList.toggle("is-unlocked",unlocked),this._labels[i].classList.toggle("is-locked",!unlocked)})}_posFor(amount){return this.isSingle?100:this.twoStopLayout?amount===this.maxAmount?this.usablePct:this.usablePct/2:Math.max(0,Math.min(1,amount/Math.max(1,this.maxAmount)))*this.usablePct}_formatMoney(cents){const amount=(cents/100).toFixed(2),code=this.currency,symbol=code==="USD"||code==="CAD"||code==="AUD"?"$":code==="GBP"?"\xA3":code==="EUR"?"\u20AC":"";return symbol?`${symbol}${amount}`:`${amount} ${code}`}}customElements.define("tiered-progress-bar",TieredProgressBar); 5//# sourceMappingURL=/cdn/shop/t/329/assets/custom.js.map?v=23582335874399268841789671916
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.