PageSourceSearch

https://www.murad.com/cdn/shop/t/2/assets/global.vbt.js?v=100204466171077718831789581415

js murad.com collected 2026-09-25 04:25:32 UTC 181,387 bytes, 13 lines download raw bytes

1import{enableHorizontalScroll,formatPrice}from"./chunk--chunk-7X5PGIXI.vbt.js";import{addRemoveGwpItems,updateCartDiscountCodes}from"./chunk--chunk-NTJ6SDHE.vbt.js";import{cartDataFncs,getCartData,hasTimeElapsed,setCartDataLocalStorage,shapeCartData}from"./chunk--chunk-3U6TTBU4.vbt.js";import{cartActions,cartAddItems,cartChange}from"./chunk--chunk-AXMOSBZM.vbt.js";import{CART_LINE_ITEM_QUANTITY_MAX_DEFAULT,COMPLETE_REGIMEN_DISCOUNT_CODE_PREFIX,ON_CHANGE_DEBOUNCE_TIMER,PRODUCT_PROPERTY_KEYS,PRODUCT_SELLING_PLAN_DEFAULT_ID,PUB_SUB_EVENTS,PUB_SUB_PAYLOADS,cartDebug,cartDebugHttp,debounce,debugOutlineElements,getCartDebugState,getLocalStorage,publish,setLocalStorage,subscribe}from"./chunk--chunk-CTFUCGD4.vbt.js";import"./chunk--chunk-Z7A6LSGX.vbt.js";function initComponentOnConnectedComponentLoad(componentToInit,handleToWatch,selectorDispatch,element,dataSelect){document.addEventListener(handleToWatch+" loaded",function handler(){const component=new componentToInit(element,dataSelect);component.init&&component.init(),document.dispatchEvent(new CustomEvent(selectorDispatch+" loaded")),this.removeEventListener(handleToWatch+" loaded",handler)})}function initComponentOnConnectedComponentDomEvent(componentToInit,handleToWatch,trigger,selectorDispatch,element,dataSelect){document.querySelectorAll("[data-"+handleToWatch+"]").forEach(elementTrigger=>elementTrigger.addEventListener(trigger,function handler(){const component=new componentToInit(element,dataSelect);component.init&&component.init(),document.dispatchEvent(new CustomEvent(selectorDispatch+" loaded")),this.removeEventListener(trigger,handler)}))}function initComponentOnSelfDomEvent(componentToInit,trigger,selectorDispatch,element,dataSelect){window.innerWidth<768&&trigger==="mouseover"?initComponentOnSelfIntersection(componentToInit,selectorDispatch,element,dataSelect):element.addEventListener(trigger,function handler(){const component=new componentToInit(element,dataSelect);component.init&&component.init(),document.dispatchEvent(new CustomEvent(selectorDispatch+" loaded")),this.removeEventListener(trigger,handler)})}function initComponentOnSelfIntersection(componentToInit,selectorDispatch,element,dataSelect){const component=new componentToInit(element,dataSelect);if(component.init){const observer=new IntersectionObserver(([entry])=>{entry.isIntersecting&&(component.init(),document.dispatchEvent(new CustomEvent(selectorDispatch+" loaded")),observer.disconnect())},{rootMargin:"300px 0px 0px 0px"});observer.observe(element)}}function ComponentConstructor(components){Object.entries(components).forEach(([selector,Component])=>{const dataSelect="data-"+selector;document.querySelectorAll("["+dataSelect+"]").forEach(element=>{if(Array.isArray(Component)){if(Component.filter(option=>typeof option=="string"&&option.includes("url:")).length>0){const urls=Component.map(option=>typeof option=="string"&&option.includes("url:")?option.split("url:")[1]:!1);let shouldInit=!1;for(const url of urls)url&&window.location.href.includes(url)&&(shouldInit=!0);if(shouldInit){initComponentOnSelfIntersection(Component[0],selector,element,dataSelect);return}}Component.forEach((option,i)=>{if(!(i===0||option.includes("url:")))if(option.includes(":")){const triggerType=option.split(":")[0],triggerSelector=option.split(":")[1];triggerType==="load"?initComponentOnConnectedComponentLoad(Component[0],triggerSelector,selector,element,dataSelect):initComponentOnConnectedComponentDomEvent(Component[0],triggerSelector,triggerType,selector,element,dataSelect)}else initComponentOnSelfDomEvent(Component[0],option,selector,element,dataSelect)});return}initComponentOnSelfIntersection(Component,selector,element,dataSelect)})})}var CartRemoveButton=class extends HTMLElement{constructor(){super(),this.addEventListener("click",event=>{event.preventDefault(),this?.classList.toggle("opacity-40"),this?.classList.toggle("pointer-events-none"),cartActions.cartChange({id:this.dataset.key,line:void 0,quantity:0,sellingPlanId:void 0,properties:void 0})})}};customElements.define("cart-remove-button",CartRemoveButton);var CartRemoveRegimenGroup=class extends HTMLElement{constructor(){super(),this.addEventListener("click",event=>{event.preventDefault();
1const itemKeys=(this.dataset.itemKeys||"").split(",").filter(Boolean);if(!itemKeys.length){cartDebug("regimen-group remove skipped: no item keys");return}this?.classList.toggle("opacity-40"),this?.classList.toggle("pointer-events-none");const itemKeyQuantityMap=itemKeys.reduce((acc,itemKey)=>(acc[itemKey]=0,acc),{});cartActions.cartUpdateQuantities(itemKeyQuantityMap)})}};customElements.define("cart-remove-regimen-group",CartRemoveRegimenGroup);var CartLoadingSpinner=class extends HTMLElement{constructor(){super(),this.cartItemKey=this.dataset.cartItemKey}connectedCallback(){this.cartLoadingUnsubscriber=subscribe(PUB_SUB_EVENTS.cartInFlight,payload=>{this.cartItemKey&&payload.id!==this.cartItemKey||(payload.isInFlight===!0?this.enableLoading():this.disableLoading())},"cartLoadingSpinner")}disconnectedCallback(){this.cartLoadingUnsubscriber&&this.cartLoadingUnsubscriber()}enableLoading(){this.classList.remove("hidden")}disableLoading(){this.classList.add("hidden")}};customElements.define("cart-loading-spinner",CartLoadingSpinner);var CartCustomElement=class extends HTMLElement{constructor(){super(),this.cartInFlightDebugUnsubscriber=null}connectedCallback(){this.cartInFlightDebugUnsubscriber=subscribe(PUB_SUB_EVENTS.cartInFlight,payload=>{payload.isInFlight===!0&&this.enableDebugOutline()},"cartInFlight")}disconnectedCallback(){this.cartInFlightDebugUnsubscriber&&this.cartInFlightDebugUnsubscriber()}enableDebugOutline(){getCartDebugState()===!0&&debugOutlineElements([this.firstElementChild],"yellow",0)}};customElements.define("cart-custom-element",CartCustomElement);var CartInFlight=class extends HTMLElement{constructor(){super(),this.cartLoadingUnsubscriber=null,this.cartItemKey=this.dataset.cartItemKey,this.spinner=this.querySelector(".loading__spinner_spinner"),this.childToHide=this.querySelector(".loading__spinner_child"),this.mask=this.querySelector(".loading__spinner_mask"),this.showSpinner=this.dataset.cartInFlightShowSpinner==="true",this.maskChild=this.dataset.cartInFlightMaskChild==="true",this.dimChild=this.dataset.cartInFlightDimChild==="true",this.hideChild=this.dataset.cartInFlightHideChild==="true",this.classToDimChild=this.hideChild?"opacity-0":"opacity-40"}connectedCallback(){this.cartLoadingUnsubscriber=subscribe(PUB_SUB_EVENTS.cartInFlight,payload=>{this.cartItemKey&&payload.id!==this.cartItemKey||(payload.isInFlight===!0?this.enableLoading():this.disableLoading())},"cartInFlight")}disconnectedCallback(){this.cartLoadingUnsubscriber&&this.cartLoadingUnsubscriber()}enableLoading(){getCartDebugState()===!0&&debugOutlineElements([this.childToHide],"blue",0),this.showSpinner&&this.spinner?.classList.remove("hidden"),this.showSpinner&&this.spinner?.classList.add("flex"),this.maskChild&&this.mask?.classList.remove("hidden"),this.dimChild&&this.childToHide?.classList.add(this.classToDimChild)}disableLoading(){this.spinner?.classList.add("hidden"),this.spinner?.classList.remove("flex"),this.mask?.classList.add("hidden"),this.childToHide?.classList.remove(this.classToDimChild)}};customElements.define("cart-in-flight",CartInFlight);var CartInFlightOverlay=class extends HTMLElement{constructor(){super(),this.cartLoadingUnsubscriber=null,this.hideOverlayTimeout=null,this.spinner=this.querySelector(".cart-in-flight-overlay__spinner"),this.mask=this.querySelector(".cart-in-flight-overlay__mask"),this.childToHide=this.querySelector(".cart-in-flight-overlay__child"),this.showSpinner=this.dataset.cartInFlightShowSpinner==="true",this.maskChild=this.dataset.cartInFlightMaskChild==="true",this.dimChild=this.dataset.cartInFlightDimChild==="true",this.hideChild=this.dataset.cartInFlightHideChild==="true",this.persistAfterInFlight=this.dataset.cartInFlightPersistAfterInFlight==="true";const hideDelayMs=Number.parseInt(this.dataset.cartInFlightPersistHideDelayMs||"5000",10);this.persistHideDelayMs=Number.isNaN(hideDelayMs)?5e3:hideDelayMs,this.classToDimChild=this.hideChild?"opacity-0":"opacity-40"}connectedCallback(){this.cartLoadingUnsubscriber=subscribe(PUB_SUB_EVENTS.cartInFlight,payload=>{if(payload.isInFlight===!0&&payload.action=="add"){this.enableLoading();return}this.disableLoading()},"cartInFlightOverlay")}disconnectedCallback(){this.cartLoadingUnsubscriber&&this.cartLoadingUnsubscriber(),this.clearHideOverlayTimeout()}clearHideOverlayTimeout(){this.hideOverlayTimeout&&(clearTimeout(this.hideOverlayTimeout),this.hideOverlayTimeout=null)}showOverlay(){getCartDebugState()===!0&&debugOutlineElements([this.mask],"blue",0),this.showSpinner&&this.spinner?.classList.remove("hidden"),this.showSpinner&&this.spinner?.classList.add("flex"),this.maskChild&&this.mask?.classList.remove("hidden"),this.dimChild&&this.childToHide?.classList.add(this.classToDimChild)}hideOverlay(){this.spinner?.classList.add("hidden"),this.spinner?.classList.remove("flex"),this.mask?.classList.add("hidden"),this.childToHide?.classList.remove(this.classToDimChild)}enableLoading(){this.clearHideOverlayTimeout(),this.showOverlay()}disableLoading(){if(this.clearHideOverlayTimeout(),this.persistAfterInFlight){this.hideOverlayTimeout=setTimeout(()=>{this.hideOverlay(),this.hideOverlayTimeout=null},this.persistHideDelayMs);return}this.hideOverlay()}};customElements.define("cart-in-flight-overlay",CartInFlightOverlay);
1var CartItems=class extends HTMLElement{constructor(){super(),this.cartDebugState=getCartDebugState()}connectedCallback(){this.cartLoadingUnsubscriber=subscribe(PUB_SUB_EVENTS.cartInFlight,payload=>{payload.isInFlight===!0?this.enableLoading({key:payload.id,line:payload.line}):this.disableLoading({key:payload.id,line:payload.line})},"cartItems"),this.cartDebugState===!0&&this.addDebugUI()}disconnectedCallback(){this.cartLoadingUnsubscriber&&this.cartLoadingUnsubscriber()}addStylesheet(styleString){var styleEl=document.createElement("style");styleEl.innerText=styleString,this.prepend(styleEl)}addDebugUI(){this.addStylesheet(`
2      .debug-controls {
3        border: 2px solid yellow;
4      }
5      .debug-controls button {
6        padding: 4px;
7      }
8    `);const debugControls=document.createElement("div");debugControls.classList.add("debug-controls");const refreshCart=document.createElement("button");refreshCart.textContent="Refresh Cart",refreshCart.addEventListener("click",()=>{cartActions.cartRefresh()}),debugControls.append(refreshCart);const clearCart=document.createElement("button");clearCart.textContent="Clear Cart",clearCart.addEventListener("click",()=>{cartActions.cartClear()}),debugControls.append(clearCart),this.prepend(debugControls)}enableLoading({key,line}){this.classList.add("pointer-events-none"),document.activeElement?.blur()}disableLoading({key,line}){this.classList.remove("pointer-events-none")}};customElements.define("cart-items",CartItems);var CURRENCY_PREFIXES={AUD:"$",CAD:"$",EUR:"\u20AC",GBP:"\xA3",MYR:"RM",USD:"$"},FreeShippingBar=class extends HTMLElement{constructor(){super(),this.cartSubtotal=this.toCents(this.dataset.cartSubtotal),this.cartItemCount=parseInt(this.dataset.cartItemCount??"0"),this.hasSubscription=this.dataset.hasSubscription==="true",this.currencyCode=this.dataset.currencyCode||"USD",this.currencySymbol=this.dataset.currencySymbol||"$",this.promotions=this.getJson("[data-promotions]",[]).map((promotion,index)=>({index,threshold:Math.max(this.toCents(promotion.threshold),0),label:promotion.label||promotion.description||"",description:promotion.description||promotion.label||"",type:`${promotion.type||"discount"}`})).filter(promotion=>promotion.label||promotion.description).sort((a,b)=>a.threshold-b.threshold||a.index-b.index).slice(0,3),this.strings={addMore:this.dataset.addMore||"Add [amount] more to unlock [promotion]",earnedAddMore:this.dataset.earnedAddMore||"You've earned [earned]. Add [amount] more to unlock [promotion]",earnedOnly:this.dataset.earnedOnly||"You've earned [earned].",allUnlocked:this.dataset.allUnlocked||"Congrats! You've unlocked [earned].",defaultPromotion:this.dataset.defaultPromotion||"this promotion",earnedSeparator:this.dataset.earnedSeparator||" and "},this.elProgress=this.querySelector("[data-progress]"),this.elMessage=this.querySelector("[data-message]"),this.elMarkers=this.querySelector("[data-progress-markers]"),this.elProgressWrap=this.querySelector("[data-progress-wrap]")}connectedCallback(){this.updateElements({subtotal:this.cartSubtotal,itemCount:this.cartItemCount,hasSubscription:this.hasSubscription}),this.cartUpdateUnsubscriber=subscribe(PUB_SUB_EVENTS.cartMutationComplete,payload=>{this.onCartUpdate(payload.cartData.cartRaw)},"freeShippingBar")}disconnectedCallback(){this.cartUpdateUnsubscriber&&this.cartUpdateUnsubscriber()}getJson(selector,fallback){try{const el=this.querySelector(selector);return el?JSON.parse(el.textContent):fallback}catch(err){return console.error("FreeShippingBar: invalid JSON config",err),fallback}}toCents(value){const parsedValue=parseInt(value??"0");return Number.isFinite(parsedValue)?parsedValue:0}onCartUpdate(cartRaw){this.updateElements({subtotal:this.toCents(cartRaw.items_subtotal_price??cartRaw.total_price),itemCount:parseInt(cartRaw.item_count??"0"),hasSubscription:cartRaw.items?.some(item=>item.selling_plan_allocation)})}formatMoney(cents){const amount=Math.max(cents,0)/100,maximumFractionDigits=amount%1===0?0:2,currencyPrefix=CURRENCY_PREFIXES[this.currencyCode.toUpperCase()];try{if(currencyPrefix){const formattedAmount=new Intl.NumberFormat(document.documentElement.lang||void 0,{maximumFractionDigits}).format(amount);return`${currencyPrefix}${formattedAmount}`}return new Intl.NumberFormat(document.documentElement.lang||void 0,{style:"currency",currency:this.currencyCode,maximumFractionDigits}).format(amount)}catch{const formattedAmount=amount.toFixed(maximumFractionDigits);return`${this.currencySymbol}${formattedAmount}`}}isFreeShippingPromotion(promotion){return promotion.type.toLowerCase().replace(/[\s-]+/g,"_")==="free_shipping"}isPromotionUnlocked(promotion,subtotal,hasSubscription){return this.isFreeShippingPromotion(promotion)&&hasSubscription?!0:subtotal>=promotion.threshold}getPromotionDescription(promotion){return promotion?.description||promotion?.label||this.strings.defaultPromotion}
8formatList(items){const filteredItems=items.filter(Boolean);return filteredItems.length<=1?filteredItems:filteredItems.length===2?[filteredItems[0],this.strings.earnedSeparator,filteredItems[1]]:filteredItems.flatMap((item,index)=>index===0?[item]:index===filteredItems.length-1?[",",this.strings.earnedSeparator,item]:[", ",item])}appendTextFragment(parent,text,isStrong=!1){if(text){if(isStrong){const strong=document.createElement("strong");strong.textContent=text,parent.append(strong);return}parent.append(document.createTextNode(text))}}appendTemplate(parent,template,replacements){const tokenPattern=/\[(amount|promotion|earned)\]/g;let lastIndex=0,match;for(;(match=tokenPattern.exec(template))!==null;){this.appendTextFragment(parent,template.slice(lastIndex,match.index));const replacement=replacements[match[1]];(Array.isArray(replacement)?replacement:[replacement]).forEach(item=>{if(typeof item=="string"){this.appendTextFragment(parent,item);return}this.appendTextFragment(parent,item.text,item.strong)}),lastIndex=tokenPattern.lastIndex}this.appendTextFragment(parent,template.slice(lastIndex))}renderMessage(nextPromotion,earnedPromotions,allUnlocked,subtotal,hasVisiblePromotions=!0){if(!this.elMessage)return;this.elMessage.replaceChildren();const earnedItems=this.formatList(earnedPromotions.map(promotion=>({text:this.getPromotionDescription(promotion),strong:!0})));if(!hasVisiblePromotions&&earnedItems.length){this.appendTemplate(this.elMessage,this.strings.earnedOnly,{earned:earnedItems});return}if(allUnlocked){this.appendTemplate(this.elMessage,this.strings.allUnlocked,{earned:earnedItems});return}const nextPromotionItem={text:this.getPromotionDescription(nextPromotion),strong:!0};if(earnedItems.length){this.appendTemplate(this.elMessage,this.strings.earnedAddMore,{amount:this.formatMoney(nextPromotion.threshold-subtotal),promotion:nextPromotionItem,earned:earnedItems});return}this.appendTemplate(this.elMessage,this.strings.addMore,{amount:this.formatMoney(nextPromotion.threshold-subtotal),promotion:nextPromotionItem})}updateElements({subtotal=0,itemCount=0,hasSubscription=!1}){if(!this.promotions.length){this.style.display="none";return}const visiblePromotions=hasSubscription?this.promotions.filter(promotion=>!this.isFreeShippingPromotion(promotion)):this.promotions,maxThreshold=Math.max(...visiblePromotions.map(promotion=>promotion.threshold),0),percent=maxThreshold===0?100:Math.min(Math.max(subtotal/maxThreshold*100,itemCount>0?1:0),100);this.elProgress&&(this.elProgress.style.width=`${percent}%`);const promotionsWithState=visiblePromotions.map(promotion=>({...promotion,unlocked:this.isPromotionUnlocked(promotion,subtotal,hasSubscription)})),allPromotionsWithState=this.promotions.map(promotion=>({...promotion,unlocked:this.isPromotionUnlocked(promotion,subtotal,hasSubscription)})),nextPromotion=allPromotionsWithState.find(promotion=>!promotion.unlocked),allUnlocked=!nextPromotion,earnedPromotions=allPromotionsWithState.filter(promotion=>promotion.unlocked);this.renderMessage(nextPromotion,earnedPromotions,allUnlocked,subtotal,visiblePromotions.length>0),this.elProgressWrap&&this.elProgressWrap.classList.toggle("hidden",!visiblePromotions.length),this.elMarkers&&this.elMarkers.replaceChildren(...promotionsWithState.map(promotion=>this.createMarker(promotion,maxThreshold)))}createMarker(promotion,maxThreshold){const marker=document.createElement("div"),position=maxThreshold===0?0:Math.min(promotion.threshold/maxThreshold*100,100),edge=position<=2?"start":position>=98?"end":"";marker.className=`free-shipping-progress__marker${promotion.unlocked?" is-unlocked":""}`,marker.style.setProperty("--marker-position",`${position}%`),edge&&(marker.dataset.edge=edge);const threshold=document.createElement("span");threshold.className="free-shipping-progress__threshold eyebrow-2 text-text-primary",threshold.textContent=this.formatMoney(promotion.threshold);const dot=document.createElement("span");dot.className="free-shipping-progress__dot";const bubble=document.createElement("span");bubble.className="free-shipping-progress__bubble body-copy-3 text-text-primary";const bubbleText=document.createElement("span");return bubbleText.className="free-shipping-progress__bubbleText",bubbleText.textContent=promotion.label||promotion.description,bubble.append(bubbleText),marker.append(threshold,dot,bubble),marker}};customElements.define("free-shipping-bar",FreeShippingBar);var InputSelectSubscription=class extends HTMLElement{constructor(){super(),this.productFormId=this.dataset.productFormId,this.defaultSellingPlanId=this.dataset.defaultSellingPlanId,this.itemKey=this.dataset.itemKey,this.line=this.dataset.line,this.quantity=this.dataset.quantity,this.productId=this.dataset.productId,this.elSelect=this.querySelector("select"),this.elOptions=this.querySelectorAll("option"),this.elFacadeSpan=this.querySelector("[data-input-select-subscription-facade] > span"),this.elMask=this.querySelector("[data-input-select-subscription-mask]"),this.elAdditionalSubscriptionInfo=document.querySelector(`[data-input-select-subscription-additionalSubscriptionInfo="${this.itemKey}"]`),this.elAdditionalSubscriptionInfoSpan=this.elAdditionalSubscriptionInfo?.querySelector("span"),this.stringSeparatorForAdditionalSubscriptionInfo="- "}connectedCallback(){this.defaultSellingPlanId&&this.updateProductFormSellingPlan(this.defaultSellingPlanId),this.updateFacadeTextContent(),this.elSelect?.addEventListener("change",this.handleSelectChange)}disconnectedCallback(){this.elSelect?.removeEventListener("change",this.handleSelectChange)}updateFacadeTextContent=()=>{for(let el of this.elOptions)if(el.selected){let separateSubscriptionDurationAndAdditionalInfo=(el.textContent??"").split(this.stringSeparatorForAdditionalSubscriptionInfo),textFromSelectOptionWithoutAdditionalInfo=separateSubscriptionDurationAndAdditionalInfo[0];this.elFacadeSpan&&(this.elFacadeSpan.textContent=textFromSelectOptionWithoutAdditionalInfo);let additionalInfo=separateSubscriptionDurationAndAdditionalInfo[1];this.elAdditionalSubscriptionInfo&&this.elAdditionalSubscriptionInfoSpan&&(a
8dditionalInfo?(this.elAdditionalSubscriptionInfoSpan.textContent=additionalInfo,this.elAdditionalSubscriptionInfo.classList.remove("hidden")):(this.elAdditionalSubscriptionInfoSpan.textContent="",this.elAdditionalSubscriptionInfo.classList.add("hidden")));break}};updateProductFormSellingPlan=(sellingPlanId=PRODUCT_SELLING_PLAN_DEFAULT_ID)=>{publish(PUB_SUB_EVENTS.productSellingPlanChange,{productFormId:this.productFormId,sellingPlanId},"input-select-subscription")};updateCartLineItemSellingPlan=(sellingPlanId=PRODUCT_SELLING_PLAN_DEFAULT_ID)=>{this.elSelect&&(this.elSelect.disabled=!0),this.elMask&&this.elMask.classList.remove("hidden"),cartChange({id:this.itemKey,quantity:this.quantity,sellingPlanId,properties:{[PRODUCT_PROPERTY_KEYS.isSubscription]:!!sellingPlanId}})};handleSelectChange=event=>{console.log(event.target.value),event.stopPropagation(),this.updateFacadeTextContent();let options=event.target.options,selectedIndex=event.target.selectedIndex,sellingPlanId=options[selectedIndex].getAttribute("data-option-sellingPlanId");const cartItems=this.closest("cart-items");this.itemKey&&cartItems?this.updateCartLineItemSellingPlan(sellingPlanId):this.updateProductFormSellingPlan(sellingPlanId)}};customElements.define("input-select-subscription",InputSelectSubscription);var InputSelectSubscriptionRegimenGroup=class extends HTMLElement{constructor(){super(),this.itemKeys=(this.dataset.itemKeys||"").split(",").filter(Boolean),this.itemQuantities=(this.dataset.itemQuantities||"").split(",").filter(Boolean),this.elSelect=this.querySelector("select"),this.elOptions=this.querySelectorAll("option"),this.elFacadeSpan=this.querySelector("[data-input-select-subscription-regimen-group-facade] > span"),this.elMask=this.querySelector("[data-input-select-subscription-regimen-group-mask]")}connectedCallback(){this.updateFacadeTextContent(),this.elSelect?.addEventListener("change",this.handleSelectChange)}disconnectedCallback(){this.elSelect?.removeEventListener("change",this.handleSelectChange)}updateFacadeTextContent=()=>{for(const el of this.elOptions)if(el.selected&&this.elFacadeSpan){this.elFacadeSpan.textContent=el.textContent??"";break}};normalizeSellingPlanId=rawSellingPlanId=>{if(!rawSellingPlanId)return PRODUCT_SELLING_PLAN_DEFAULT_ID;const parsedSellingPlanId=parseInt(rawSellingPlanId,10);return Number.isNaN(parsedSellingPlanId)?PRODUCT_SELLING_PLAN_DEFAULT_ID:parsedSellingPlanId};normalizeSellingPlanIds=rawSellingPlanIds=>rawSellingPlanIds?rawSellingPlanIds.split(",").map(rawSellingPlanId=>{const parsedSellingPlanId=parseInt(rawSellingPlanId,10);return Number.isNaN(parsedSellingPlanId)?PRODUCT_SELLING_PLAN_DEFAULT_ID:parsedSellingPlanId}):[];waitForCartMutationResult=()=>new Promise(resolve=>{let settled=!1;const finish=()=>{settled||(settled=!0,unsubscribeComplete(),unsubscribeError(),resolve())},unsubscribeComplete=subscribe(PUB_SUB_EVENTS.cartMutationComplete,()=>finish(),"input-select-subscription-regimen-group"),unsubscribeError=subscribe(PUB_SUB_EVENTS.cartMutationError,()=>finish(),"input-select-subscription-regimen-group")});updateCartLineItemsSellingPlan=async({fallbackSellingPlanId=PRODUCT_SELLING_PLAN_DEFAULT_ID,sellingPlanIds=[],itemKeys=this.itemKeys,itemQuantities=this.itemQuantities}={})=>{const hasItemSpecificSellingPlanIds=sellingPlanIds.length>0;if(!itemKeys.length){cartDebug("regimen-group selling plan update skipped: no item keys");return}cartDebug("regimen-group selling plan update",{itemCount:itemKeys.length,fallbackSellingPlanId,hasItemSpecificSellingPlanIds}),this.elSelect&&(this.elSelect.disabled=!0),this.elMask&&this.elMask.classList.remove("hidden");for(let i=0;i<itemKeys.length;i+=1){const itemKey=itemKeys[i],quantity=parseInt(itemQuantities[i]??"1",10)||1,itemSellingPlanId=hasItemSpecificSellingPlanIds?sellingPlanIds[i]:fallbackSellingPlanId;if(hasItemSpecificSellingPlanIds&&itemSellingPlanId===void 0){cartDebug("regimen-group selling plan update skipped: missing item plan",{itemKey,itemIndex:i});continue}cartChange({id:itemKey,line:void 0,quantity,sellingPlanId:itemSellingPlanId,properties:{[PRODUCT_PROPERTY_KEYS.isSubscription]:!!itemSellingPlanId}}),await this.waitForCartMutationResult()}};handleSelectChange=event=>{event.stopPropagation(),this.updateFacadeTextContent();const options=event.target.options,selectedIndex=event.target.selectedIndex,selectedOption=options[selectedIndex],fallbackSellingPlanId=this.normalizeSellingPlanId(selectedOption.dataset.optionSellingPlanId),sellingPlanIds=this.normalizeSellingPlanIds(selectedOption.dataset.optionSellingPlanIds),optionItemKeys=(selectedOption.dataset.optionItemKeys||"").split(",").filter(
8Boolean),optionItemQuantities=(selectedOption.dataset.optionItemQuantities||"").split(",").filter(Boolean),resolvedItemKeys=optionItemKeys.length?optionItemKeys:this.itemKeys,resolvedItemQuantities=optionItemQuantities.length?optionItemQuantities:this.itemQuantities;cartDebug("regimen-group subscription select changed",{selectedIndex,fallbackSellingPlanId,sellingPlanIds,optionItemKeysCount:optionItemKeys.length,resolvedItemKeysCount:resolvedItemKeys.length}),this.updateCartLineItemsSellingPlan({fallbackSellingPlanId,sellingPlanIds,itemKeys:resolvedItemKeys,itemQuantities:resolvedItemQuantities})}};customElements.define("input-select-subscription-regimen-group",InputSelectSubscriptionRegimenGroup);var SubscriptionWidget=class extends HTMLElement{constructor(){super(),this.productFormId=this.dataset.productFormId,this.elSelect=this.querySelector("input-select-subscription select"),this.elInputOnetime=this.querySelector("input#purchaseType--onetime"),this.elInputSubscription=this.querySelector("input#purchaseType--subscription")}updateProductFormSellingPlan=(sellingPlanId=PRODUCT_SELLING_PLAN_DEFAULT_ID)=>{publish(PUB_SUB_EVENTS.productSellingPlanChange,{productFormId:this.productFormId,sellingPlanId},"subscription-widget")};handleChangePurchaseTypeOneTime=event=>{const value=event.target.value;cartDebug("SubscriptionWidget handleChangePurchaseType:",value),this.updateProductFormSellingPlan(PRODUCT_SELLING_PLAN_DEFAULT_ID)};handleChangePurchaseTypeSubscription=event=>{const value=event.target.value;if(cartDebug("SubscriptionWidget handleChangePurchaseType:",value),this.elSelect){let options=this.elSelect.options,selectedIndex=this.elSelect.selectedIndex,sellingPlanId=options[selectedIndex].getAttribute("data-option-sellingPlanId");this.updateProductFormSellingPlan(sellingPlanId)}};connectedCallback(){this.elInputSubscription?.addEventListener("input",this.handleChangePurchaseTypeSubscription),this.elInputOnetime?.addEventListener("input",this.handleChangePurchaseTypeOneTime)}disconnectedCallback(){this.elInputSubscription?.removeEventListener("input",this.handleChangePurchaseTypeSubscription),this.elInputOnetime?.removeEventListener("input",this.handleChangePurchaseTypeOneTime)}};customElements.define("subscription-widget",SubscriptionWidget);var QuantityInput=class extends HTMLElement{constructor(){super(),this.productFormId=this.dataset.productFormId,this.input=this.querySelector("input"),this.changeEvent=ne
8w Event("change",{bubbles:!0}),this.buttonIncrease=this.querySelector("button[data-quantity-increase]"),this.buttonDecrease=this.querySelector("button[data-quantity-decrease]"),this.min=parseInt(this.dataset.min??"1")}connectedCallback(){this.input?.addEventListener("change",this.onInputChange.bind(this)),this.querySelectorAll("button").forEach(button=>button.addEventListener("click",this.onButtonClick.bind(this))),this.updateQuantityButtonsState()}disconnectedCallback(){this.input?.removeEventListener("change",this.onInputChange.bind(this)),this.querySelectorAll("button").forEach(button=>button.removeEventListener("click",this.onButtonClick.bind(this)))}resetQuantityInput(id){cartDebug("resetQuantityInput",id),this.input&&(this.input.value=this.input.getAttribute("value")??this.min.toString(),cartDebug("Quantity RESET to:",this.input.value),this.updateQuantityButtonsState())}handleInvalidInput(event,index,message){event.target.setCustomValidity(message),event.target.reportValidity(),this.resetQuantityInput(index),event.target.select()}validateQuantity(event){const inputValue=parseInt(event.target.value),index=event.target.dataset.index,key=event.target.dataset.key,min=parseInt(event.target.dataset.min),max=parseInt(event.target.dataset.max),step=parseInt(event.target.step);let message="";inputValue<min?message=window.quickOrderListStrings.min_error.replace("[min]",min):inputValue>max?message=window.quickOrderListStrings.max_error.replace("[max]",max):inputValue%step!==0&&(message=window.quickOrderListStrings.step_error.replace("[step]",step)),message?(cartDebug({message}),this.handleInvalidInput(event,index,message)):(event.target.setCustomValidity(""),event.target.reportValidity(),this.productFormId?publish(PUB_SUB_EVENTS.productQuantityChange,{productFormId:this.productFormId,quantity:inputValue}):cartChange({id:key,quantity:inputValue}))}onInputChange(event){this.updateQuantityButtonsState(),cartDebug("Quantity changed to:",event.target.value),this.validateQuantity(event)}onButtonClick(event){if(event.preventDefault(),!this.input)return;const previousValue=this.input.value;event.target.name==="plus"?this.min>parseInt(this.input.step)&&parseInt(this.input.value)<=this.min?this.input.value=this.min.toString():this.input.stepUp():this.input.stepDown(),previousValue!==this.input.value&&this.input.dispatchEvent(this.changeEvent),this.min===parseInt(previousValue)&&event.target.name==="minus"&&(this.input.value=this.min.toString())}updateQuantityButtonsState(){const value=this.input?.value,min=this.input?.dataset.min,max=this.input?.dataset.max;if(value){if(min){let valAtMin=parseInt(value)<=parseInt(min);this.buttonDecrease?.classList.toggle("opacity-50",valAtMin),this.buttonDecrease?.classList.toggle("pointer-events-none",valAtMin)}if(max){let valAtMax=parseInt(value)>=parseInt(max);this.buttonIncrease?.classList.toggle("opacity-50",valAtMax),this.buttonIncrease?.classList.toggle("pointer-events-none",valAtMax)}}}};customElements.define("quantity-input",QuantityInput);var QuantityInputRegimenGroup=class extends HTMLElement{constructor(){super(),this.itemKeys=(this.dataset.itemKeys||"").split(",").filter(Boolean),this.input=this.querySelector("input"),this.changeEvent=ne
8w Event("change",{bubbles:!0}),this.buttonIncrease=this.querySelector("button[data-quantity-increase]"),this.buttonDecrease=this.querySelector("button[data-quantity-decrease]"),this.min=parseInt(this.dataset.min??"1"),this.onInputChangeHandler=this.onInputChange.bind(this),this.onButtonClickHandler=this.onButtonClick.bind(this)}connectedCallback(){this.input?.addEventListener("change",this.onInputChangeHandler),this.querySelectorAll("button").forEach(button=>button.addEventListener("click",this.onButtonClickHandler)),this.updateQuantityButtonsState()}disconnectedCallback(){this.input?.removeEventListener("change",this.onInputChangeHandler),this.querySelectorAll("button").forEach(button=>button.removeEventListener("click",this.onButtonClickHandler))}resetQuantityInput(){cartDebug("resetQuantityInput (regimen group)"),this.input&&(this.input.value=this.input.getAttribute("value")??this.min.toString(),cartDebug("Quantity RESET to:",this.input.value),this.updateQuantityButtonsState())}handleInvalidInput(message){this.input?.setCustomValidity(message),this.input?.reportValidity(),this.resetQuantityInput(),this.input?.select()}validateQuantity(event){const inputValue=parseInt(event.target.value),min=parseInt(event.target.dataset.min),max=parseInt(event.target.dataset.max),step=parseInt(event.target.step);let message="";inputValue<min?message=window.quickOrderListStrings.min_error.replace("[min]",min):inputValue>max?message=window.quickOrderListStrings.max_error.replace("[max]",max):inputValue%step!==0&&(message=window.quickOrderListStrings.step_error.replace("[step]",step)),message?(cartDebug({message}),this.handleInvalidInput(message)):(event.target.setCustomValidity(""),event.target.reportValidity(),this.updateQuantityForGroup(inputValue))}updateQuantityForGroup(newQuantity){if(!this.itemKeys.length){cartDebug("regimen-group quantity update skipped: no item keys");return}const itemKeyQuantityMap=this.itemKeys.reduce((acc,itemKey)=>(acc[itemKey]=newQuantity,acc),{});cartActions.cartUpdateQuantities(itemKeyQuantityMap)}onInputChange(event){this.updateQuantityButtonsState(),cartDebug("Quantity changed to:",event.target.value),this.validateQuantity(event)}onButtonClick(event){if(event.preventDefault(),!this.input)return;const previousValue=this.input.value;event.target.name==="plus"?this.min>parseInt(this.input.step)&&parseInt(this.input.value)<=this.min?this.input.value=this.min.toString():this.input.stepUp():this.input.stepDown(),previousValue!==this.input.value&&this.input.dispatchEvent(this.changeEvent),this.min===parseInt(previousValue)&&event.target.name==="minus"&&(this.input.value=this.min.toString())}updateQuantityButtonsState(){const value=this.input?.value,min=this.input?.dataset.min,max=this.input?.dataset.max;if(value){if(min){let valAtMin=parseInt(value)<=parseInt(min);this.buttonDecrease?.classList.toggle("opacity-50",valAtMin),this.buttonDecrease?.classList.toggle("pointer-events-none",valAtMin)}if(max){let valAtMax=parseInt(value)>=parseInt(max);this.buttonIncrease?.classList.toggle("opacity-50",valAtMax),this.buttonIncrease?.classList.toggle("pointer-events-none",valAtMax)}}}};customElements.define("quantity-input-regimen-group",QuantityInputRegimenGroup);var DATA_IDENTIFIER="[data-quick-add]",LABELS={add:"Add [fallback copy]",remove:"Remove [fallback copy]",max:"Max [fallback copy]"},QuickAdd=class extends HTMLElement{constructor(){super(),this.productFormId=this.dataset.productFormId,this.sellingPlanId=this.dataset.defaultSellingPlanId?parseInt(this.dataset.defaultSellingPlanId):PRODUCT_SELLING_PLAN_DEFAULT_ID,this.variantId=parseInt(this.dataset.quickAddVariantId??"0"),this.extraVariantIds=(this.dataset.quickAddExtraVariantIds??"").split(",").map(id=>parseInt(id.trim(),10)).filter(id=>Number.isInteger(id)&&id>0&&id!==this.variantId),this.redirectToCheckout=this.dataset.quickAddRedirectToCheckout==="true",this.addQuantity=parseInt(this.dataset.quickAddQuantity??"1"),this.maxQuantity=parseInt(this.dataset.quickAddMaxQuantity??`${CART_LINE_ITEM_QUANTITY_MAX_DEFAULT}`),this.quantityInCart=0,this.size=this.dataset.quickAddSize,this.groupSelector=this.dataset.groupSelector,this.itemCartKey=this.dataset.quickAddItemCartKey,this.itemInCartClass=this.dataset.quickAddItemInCartClass??"item-in-cart",this.labelAdd=this.dataset.quickAddLabelAdd??LABELS.add,this.labelAddDesktop=this.dataset.quickAddLabelAddDesktop??this.labelAdd,this.labelAddMobile=this.dataset.quickAddLabelAddMobile??this.labelAdd,this.labelRemove=this.dataset.quickAddLabelRemove??LABELS.remove,this.labelMax=this.dataset.quickAddLabelMax??LABELS.max,this.isFreeSample=this.hasAttribute("data-quick-add-free-sample"),this.hideCartControls=this.hasAttribute("data-quick-add-hide-cart-control
8s"),this.cartMessage=this.dataset.quickAddCartMessage??null,this.freeSampleMax=parseInt(this.dataset.quickAddFreeSampleMax??"0"),this.freeSampleCartCount=parseInt(this.dataset.quickAddFreeSampleCartCount??"0"),this.variantPrice=null,this.onVariantChange=this.onVariantChange.bind(this),this.button=this.querySelector("button"),this.buttonLabel=this.button?.querySelector("[data-quick-add-button-label]"),this.buttonAction="add",this.buttonAction=this.addItem,this.cartUpdateUnsubscriber=null,this.quantityChangeUnsubscriber=null}async connectedCallback(){this.quantityInCart=await cartDataFncs.getVariantQuantitySellingPlanInCart(this.variantId,this.sellingPlanId),this.updateElements(),this.cartUpdateUnsubscriber=subscribe(PUB_SUB_EVENTS.cartMutationComplete,async payload=>{await this.onCartUpdate(payload.cartData)},"quickAdd"),this.productFormId&&(this.quantityChangeUnsubscriber=subscribe(PUB_SUB_EVENTS.productQuantityChange,({productFormId,quantity})=>{this.onQuantityChange(productFormId,quantity)},"quickAdd"),this.quantityChangeUnsubscriber=subscribe(PUB_SUB_EVENTS.productSellingPlanChange,async({productFormId,sellingPlanId})=>{this.onSellingPlanChange(productFormId,sellingPlanId)},"quickAdd"),document.addEventListener("murad:variant:change",this.onVariantChange))}disconnectedCallback(){this.removeEventListeners(),document.removeEventListener("murad:variant:change",this.onVariantChange),this.cartUpdateUnsubscriber&&this.cartUpdateUnsubscriber(),this.quantityChangeUnsubscriber&&this.quantityChangeUnsubscriber()}async onVariantChange({detail}){const variantId=parseInt(detail?.variantId??"0",10);!this.productFormId||!Number.isInteger(variantId)||variantId<=0||(this.variantId=variantId,this.dataset.quickAddVariantId=`${variantId}`,this.extraVariantIds=(this.dataset.quickAddExtraVariantIds??"").split(",").map(id=>parseInt(id.trim(),10)).filter(id=>Number.isInteger(id)&&id>0&&id!==this.variantId),this.quantityInCart=await cartDataFncs.getVariantQuantitySellingPlanInCart(this.variantId,this.sellingPlanId),this.variantPrice=detail?.price??this.variantPrice,await this.updateElements())}updateVariantPrice(price){price&&this.querySelectorAll("[data-price-update-el]").forEach(el=>{el.querySelector("promo-price")||(el.innerHTML=price)})}onQuantityChange(productFormId,quantity){cartDebug("QuickAdd onQuantityChange",productFormId,this.productFormId,quantity),this.productFormId&&this.productFormId===productFormId&&(this.addQuantity=quantity,this.updateElements())}showPriceForSellingPlan(sellingPlanId){sellingPlanId===PRODUCT_SELLING_PLAN_DEFAULT_ID?(this.querySelectorAll(".product_atc_label_price_subscription").forEach(el=>{el.classList.add("hidden")}),this.querySelectorAll(".product_atc_label_price_onetime").forEach(el=>{el.classList.remove("hidden")})):(this.querySelectorAll(".product_atc_label_price_subscription").forEach(el=>{el.classList.remove("hidden")}),this.querySelectorAll(".product_atc_label_price_onetime").forEach(el=>{el.classList.add("hidden")}))}async onSellingPlanChange(productFormId,sellingPlanId){this.productFormId&&this.productFormId===productFormId&&(cartDebug("QuickAdd onSellingPlanChange",productFormId,this.productFormId,sellingPlanId),this.sellingPlanId=sellingPlanId,this.showPriceForSellingPlan(sellingPlanId),this.quantityInCart=await cartDataFncs.getVariantQuantitySellingPlanInCart(this.variantId,this.sellingPlanId),this.updateElements())}getAddLabelMarkup(){return this.labelAddDesktop===this.labelAddMobile?this.labelAddDesktop:`<span class="hidden lg:inline">${this.labelAddDesktop}</span><span class="lg:hidden">${this.labelAddMobile}</span>`}updateElements=async()=>{if(this.button&&this.buttonLabel){let buttonAction=this.addItem;this.isFreeSample?(this.buttonLabel.innerHTML=this.labelAdd,buttonAction=this.addItem,this.button.disabled=!1,this.button.classList.remove(this.itemInCartClass),this.freeSampleCartCount>0&&(this.itemCartKey?(this.buttonLabel.innerHTML=this.labelRemove,buttonAction=this.removeItem,this.button.classList.add(this.itemInCartClass)):this.freeSampleCartCount>=this.freeSampleMax&&(this.button.disabled=!0))):this.quantityInCart>=this.maxQuantity?(this.buttonLabel.innerHTML=this.labelMax,this.button.disabled=!0):(this.buttonLabel.innerHTML=this.getAddLabelMarkup(),this.button.disabled=!1,this.showPriceForSellingPlan(this.sellingPlanId)),this.addEventListeners(buttonAction),this.updateV
8ariantPrice(this.variantPrice)}};disableSiblingElements=()=>{document.querySelectorAll(`${this.groupSelector} ${DATA_IDENTIFIER} button`).forEach(el=>{el!==this&&(el.classList.add("pointer-events-none"),el.disabled=!0)})};showLoadingUI(){this.isFreeSample&&this.disableSiblingElements(),this.button&&(this.button.classList.add("pointer-events-none"),this.button.style.opacity="0.8",this.button.disabled=!0),this.querySelector(".loading__spinner")?.classList.remove("hidden")}hideLoadingUI(){this.button&&(this.button.classList.remove("pointer-events-none"),this.button.style.opacity="",this.button.disabled=!1),this.querySelector(".loading__spinner")?.classList.add("hidden")}countFreeSamples(items){return items.filter(item=>item.properties[PRODUCT_PROPERTY_KEYS.freeSample]).length}isThisItemInCart(items){return items.some(item=>item.variant_id===this.variantId)}getItemCartKey=items=>{let item=items.find(item2=>item2.variant_id===this.variantId);return item?item.key:null};getItemCartIndex=items=>items.findIndex(item=>item.variant_id===this.variantId);onCartUpdate=async cartData=>{this.quantityInCart=await cartDataFncs.getVariantQuantitySellingPlanInCart(this.variantId,this.sellingPlanId,cartData),this.freeSampleCartCount=this.countFreeSamples(cartData.cartRaw.items),this.itemCartKey=this.getItemCartKey(cartData.cartRaw.items),this.hideLoadingUI(),this.updateElements()};addEventListeners(buttonAction){this.removeEventListeners(),this.buttonAction=buttonAction,this.button?.addEventListener("click",this.buttonAction)}removeEventListeners(){this.button?.removeEventListener("click",this.buttonAction)}removeItem=event=>{event.preventDefault(),this.showLoadingUI(),cartChange({id:this.itemCartKey,quantity:0})};addItem=event=>{event.preventDefault(),this.showLoadingUI();const variantArray=[{id:this.variantId,quantity:this.addQuantity,selling_plan:this.sellingPlanId,properties:{...this.isFreeSample?{[PRODUCT_PROPERTY_KEYS.freeSample]:!0}:{},...this.hideCartControls?{_cart_hide_controls:!0}:{},...this.cartMessage?{[PRODUCT_PROPERTY_KEYS.cartMessage]:this.cartMessage}:{},[PRODUCT_PROPERTY_KEYS.size]:this.size,[PRODUCT_PROPERTY_KEYS.isSubscription]:!!this.sellingPlanId}},...this.extraVariantIds.map(id=>({id,quantity:1,selling_plan:null,properties:{[PRODUCT_PROPERTY_KEYS.isSubscription]:!1,[PRODUCT_PROPERTY_KEYS.cartMessage]:"Free Gift with Purchase",[PRODUCT_PROPERTY_KEYS.parentVariantId]:String(this.variantId),...this.hideCartControls?{_cart_hide_controls:!0}:{}}}))];publish(PUB_SUB_EVENTS.cartAddRequest,{variantArray,openDrawer:!this.redirectToCheckout,redirectToCheckout:this.redirectToCheckout,redirectUrl:`${window.Shopify.routes.root}checkout`})}};customElements.define("quick-add",QuickAdd);var UpsellModalTrigger=class extends HTMLElement{constructor(){super(),this.productFormId=this.dataset.productFormId}connectedCallback(){this.unsubscribe=subscribe(PUB_SUB_EVENTS.productSellingPlanChange,({productFormId,sellingPlanId})=>{if(!this.productFormId||productFormId!==this.productFormId)return;const isSubscription=!!sellingPlanId;this.classList.toggle("hidden",isSubscription),this.closest("[data-cta-container]")?.querySelector("[data-upsell-modal-quick-add-wrapper]")?.classList.toggle("hidden",!isSubscription)},"upsellModalTrigger")}disconnectedCallback(){this.unsubscribe?.()}};customElements.define("upsell-modal-trigger",UpsellModalTrigger);var CartFreeSamples=class extends HTMLElement{constructor(){super(),this.cartItemCount=parseInt(this.dataset.cartItemCount??"0"),this.cartOriginalTotalPrice=parseInt(this.dataset.cartOriginalTotalPrice??"0")}async connectedCallback(){this.updateElements(this.cartItemCount,this.cartOriginalTotalPrice),this.cartUpdateUnsubscriber=subscribe(PUB_SUB_EVENTS.cartMutationComplete,payload=>{this.onCartUpdate(payload.cartData)},"quickAdd")}disconnectedCallback(){this.cartUpdateUnsubscriber&&this.cartUpdateUnsubscriber()}onCartUpdate=cartData=>{const{cartRaw}=cartData,{item_count,original_total_price}=cartRaw;this.updateElements(item_count,original_total_price)};updateElements=async(cartItemCount,cartOriginalTotalPrice)=>{cartItemCount>0&&cartOriginalTotalPrice>0?this.classList.remove("hidden"):this.classList.add("hidden")}};customElements.define("cart-free-samples",CartFreeSamples);var DYNAMIC_YIELD_INTERSECTION_EVENT_NAME="sectionIsVisible",VisibilityDetector=class extends HTMLElement{constructor(){super(),this.dyEventName=DYNAMIC_YIELD_INTERSECTION_EVENT_NAME,this.visibilityDetectorId=this.dataset.visibilityDetectorId??null,this.triggeringSectionName=this.dataset.triggeringSectionName??null,this.triggeringSectionId=this.dataset.triggeringSectionId??null,this.doFireDyEvent=!!this.dataset.f
8ireDyVisibilityEvent,this.intersectionObsMinRatio=parseInt(this.dataset.intersectionObsMinRatio??"0"),this.intersectionObsTopMargin=parseInt(this.dataset.intersectionObsTopMargin??"0"),this.intersectionObserver=null}fireDYEvent({eventName="",eventProps={}}){var eventPayload={name:eventName,properties:eventProps};try{window.DY?.API("event",eventPayload)}catch(err){console.error(err)}}fireDYEventOnIntersection(){const eventProps={visibilityDetectorId:this.visibilityDetectorId,sectionName:this.triggeringSectionName,sectionId:this.triggeringSectionId};this.fireDYEvent({eventName:this.dyEventName,eventProps})}injectDummyElement(){let dummyEl=document.createElement("div");dummyEl.style.width="1px",dummyEl.style.height="1px",dummyEl.style.position="absolute",dummyEl.style.top="0",dummyEl.style.left="0",dummyEl.style.pointerEvents="none",dummyEl.style.opacity="0.01",dummyEl.id=`${this.dyEventName}_${this.triggeringSectionName}`,this.visibilityDetectorId&&dummyEl.setAttribute("data-visibility-detector-id",this.visibilityDetectorId),this.triggeringSectionName&&dummyEl.setAttribute("data-triggering-section-name",this.triggeringSectionName),this.triggeringSectionId&&dummyEl.setAttribute("data-triggering-section-id",this.triggeringSectionId),this.appendChild(dummyEl)}monitorIntersection({targetNode=this,callbackIntersectionChange=(...args)=>{},threshold=this.intersectionObsMinRatio,root=null,rootMargin=`0px 0px ${this.intersectionObsTopMargin}px 0px`}){let options={root,rootMargin,threshold},intersectionCallback=(entries,observer)=>{entries.forEach(entry=>{let{isIntersecting,intersectionRatio}=entry;callbackIntersectionChange({isIntersecting,intersectionRatio}),entry.isIntersecting&&observer.disconnect()})};this.intersectionObserver=new IntersectionObserver(intersectionCallback,options),this.intersectionObserver?.observe(targetNode)}connectedCallback(){this.monitorIntersection({targetNode:this,callbackIntersectionChange:({isIntersecting,intersectionRatio})=>{isIntersecting&&(this.injectDummyElement(),this.doFireDyEvent&&this.fireDYEventOnIntersection())}})}disconnectedCallback(){this.intersectionObserver?.disconnect()}};customElements.define("visibility-detector",VisibilityDetector);var LOCAL_STORAGE_KEY_YOTPO_STAR_WIDGET_ANSWERED_QUESTIONS="muradYotpoStarWidgetAnsweredQuestions",YOTPO_STAR_WIDGET_ANSWERED_QUESTIONS_STALE_AFTER_MS=1e3*60*60,DEBOUNCE_MS_YOTPO_QA_DATA=300;function getCachedAnsweredQuestions(productId){const localStorageCachedVal=getLocalStorage(LOCAL_STORAGE_KEY_YOTPO_STAR_WIDGET_ANSWERED_QUESTIONS);if(!localStorageCachedVal)return null;const answeredQuestionsThisProduct=localStorageCachedVal[productId];return answeredQuestionsThisProduct&&!hasTimeElapsed(answeredQuestionsThisProduct.lastUpdated,YOTPO_STAR_WIDGET_ANSWERED_QUESTIONS_STALE_AFTER_MS)?answeredQuestionsThisProduct.answeredQuestionCount:null}function setCachedAnsweredQuestions(productId,answeredQuestions=0){const localStorageCachedVal=getLocalStorage(LOCAL_STORAGE_KEY_YOTPO_STAR_WIDGET_ANSWERED_QUESTIONS);setLocalStorage(LOCAL_STORAGE_KEY_YOTPO_STAR_WIDGET_ANSWERED_QUESTIONS,{...localStorageCachedVal,[productId]:{answeredQuestionCount:answeredQuestions,lastUpdated:new Date().toISOString()}})}async function getYotpoQAData(yotpoAppKey,productId){try{const cachedAnsweredQuestionsThisProduct=getCachedAnsweredQuestions(productId);if(cachedAnsweredQuestionsThisProduct){publish(PUB_SUB_EVENTS.yotpoQADataComplete,{answeredQuestionCount:cachedAnsweredQuestionsThisProduct});return}if(!yotpoAppKey||!productId)throw new Error("yotpo-star-widget: missing Yotpo App Key or Product ID");const answeredQuestionCount=(await(await fetch(`https://api.yotpo.com/products/${yotpoAppKey}/${productId}/qna_bottomline`)).json()).response.total_answers;setCachedAnsweredQuestions(productId,answeredQuestionCount),publish(PUB_SUB_EVENTS.yotpoQADataComplete,{answeredQuestionCount})}catch(err){console.error("getYotpoQAData",err)}}var debounceGetYotpoQAData=debounce(({yotpoAppKey,productId})=>{getYotpoQAData(yotpoAppKey,productId)},DEBOUNCE_MS_YOTPO_QA_DATA);subscribe(PUB_SUB_EVENTS.yotpoQADataRequest,debounceGetYotpoQAData,"yotpo-star-widget");var YotpoStarWidget=class extends HTMLElement{constructor(){super(),this.yotpoAppKey=this.dataset.yotpoAppKey??"",this.productId=this.dataset.productId??"",this.answeredQuestionsLabel=this.dataset.answeredQuestionsLabel??"",this.metafieldStarRating=parseInt(this.dataset.metafieldStarRating??"0"),this.hideYotpo=!!this.dataset.hideYotpo,this.widgetObserver=null,this.reviewsQuestionsWasHandled=!1,this.summaryWasHandled=!1,this.unsubscriberReviewSummary=null,this.unsubscriberQAData=null}doShowWidget(totalAnsweredQuestions=0){const hasQuestions=totalAnsweredQuestions>0,hasReviews=this.metafieldStarRating>0,hideYotpo=this.hideYotpo;return!!((hasQuestions||hasReviews)&&!hideYotpo)}createOnClickHandler(yotpoReviewsQATabIndex=0){return e=>{const yotpoSection=document.querySelector(".yotpo-widget-instance .yotpo-reviews-main-widget");yotpoSection&&(window.scrollTo({behavior:"smooth",top:yotpoSection.getBoundingClientRect().top+window.scrollY-135}),document.querySelectorAll(".ugc-storefront-widgets-tabs-container__tab")?.[yotpoReviewsQATabIndex]?.click())}}modifyReviewsButton(reviewsButtonEl){reviewsButtonEl?.addEventListener("click",this.createOnClickHandler(0))}addQAButton(totalAnsweredQuestions=0){const qaInsert=this.querySelector("[data-qa-insert]");if(!qaInsert||totalAnsweredQuestions===0)return;const qaButton=qaInsert.querySelector("button");qaButton&&(qaButton.addEventListener("click",this.createOnClickHandler(1)),qaButton.textContent=`${totalAnsweredQuestions} ${this.answeredQuestionsLabel}`,qaInsert.classList.remove("hidden"),qaInsert.classList.add("flex"))}cloneReviewsSummary(){const otherReviewsSummary=document.querySelector(".yotpo-star-rating-reviews-summary-link");if(otherReviewsSummary){const clonedReviewsSummary=otherReviewsSummary.cloneNode(!0),otherReviewsSummaryClickable=otherReviewsSummary.querySelector(".yotpo-star-rating-reviews-summary-text");return clonedReviewsSummary.addEventListener("click",evt=>{evt.preventDefault(),otherReviewsSummaryClickable?.click()}),this.querySelector(".yotpo-reviews-star-ratings-widget > div")?.appendChild(clonedReviewsSummary),!0}return!1}
8doesHaveReviewSummary(){return!!this.querySelector("div.yotpo-star-rating-reviews-summary-link")}prepReviewsSummary(){return this.doesHaveReviewSummary()?!0:this.cloneReviewsSummary()}async mutationCallback(mutationRecordArray,observer){if(this.querySelector("#yotpo-reviews-star-ratings-widget")&&(this.reviewsQuestionsWasHandled||(this.reviewsQuestionsWasHandled=!0,publish(PUB_SUB_EVENTS.yotpoQADataRequest,{yotpoAppKey:this.yotpoAppKey,productId:this.productId})),!this.summaryWasHandled)){const hasReviewSummary=this.doesHaveReviewSummary();hasReviewSummary&&(this.summaryWasHandled=hasReviewSummary,publish(PUB_SUB_EVENTS.yotpoReviewSummaryLoaded,{node:this}),observer.disconnect())}}watchForYotpoWidget(){const observerTargetNode=this,observerOptions={subtree:!0,childList:!0};this.widgetObserver=new MutationObserver((mutationRecordArray,observer)=>this.mutationCallback(mutationRecordArray,observer)),this.widgetObserver.observe(observerTargetNode,observerOptions)}onYotpoReviewSummaryLoaded(node){this.prepReviewsSummary()}onYotpoQADataComplete(answeredQuestionCount){this.doShowWidget(answeredQuestionCount)&&(this.modifyReviewsButton(this.querySelector("button.yotpo-sr-bottom-line-button")),this.addQAButton(answeredQuestionCount),this.classList.remove("hidden"),this.classList.add("flex"))}connectedCallback(){this.unsubscriberReviewSummary=subscribe(PUB_SUB_EVENTS.yotpoReviewSummaryLoaded,({node})=>{this.onYotpoReviewSummaryLoaded(node)},"yotpo-star-widget"),this.unsubscriberQAData=subscribe(PUB_SUB_EVENTS.yotpoQADataComplete,({answeredQuestionCount})=>{this.onYotpoQADataComplete(answeredQuestionCount)},"yotpo-star-widget"),this.watchForYotpoWidget()}disconnectedCallback(){this.unsubscriberReviewSummary&&this.unsubscriberReviewSummary(),this.unsubscriberQAData&&this.unsubscriberQAData(),this.widgetObserver&&this.widgetObserver.disconnect()}};customElements.define("yotpo-star-widget",YotpoStarWidget);var API_URL_PATH_COMPLEMENTARY_REGIMEN="/api/recommendations/completeRegimen",LOCAL_STORAGE_KEY_REGIMEN_MAP="muradComplementaryRegimen_regimenMap",LOCAL_STORAGE_KEY_PRODUCT_MAP="muradComplementaryRegimen_productMap",REGIMEN_DATA_STALE_AFTER=1e3*60*60*1,DEFAULT_CATEGORIES=["cleanser","treatment","moisturizer","exfoliantPeel"],CATEGORY_LABELS={cleanser:"Cleanse",treatment:"Treat",eyeTreatment:"Treat",moisturizer:"Hydrate",exfoliantPeel:"Nourish"},CATEGORY_DESCRIPTIONS={cleanser:"Remove buildup and prep skin to absorb what comes next",treatment:"Actives that work where skin needs them most",eyeTreatment:"Actives that work where skin needs them most",moisturizer:"Lock in moisture, strengthen, and support renewal",exfoliantPeel:"Targeted rituals that elevate your everyday routine"},LABELS2={addComplete:"Add Complete Regimen to Bag *",addSome:"Add Regimen to Bag *",addOne:"Add to Bag *"},ELEMENTS_TO_HIDE_ON_INTERSECTION=["[data-sticky-cta-mobile]","#fw-player","#reamazejs-container","#attentive_overlay"];function getCachedRegimenData(targetSku,categories){const cachedRegimen=getLocalStorage(LOCAL_STORAGE_KEY_REGIMEN_MAP);if(cachedRegimen){const categoriesSortedString=[...categories].sort().join(","),targetRegimen=cachedRegimen[targetSku]?.[categoriesSortedString];if(targetRegimen){const{regimenSkus,discounts,lastModified}=targetRegimen;if(!hasTimeElapsed(lastModified,REGIMEN_DATA_STALE_AFTER))return{regimenSkus,discounts:discounts||[]}}}return null}function getCachedRegimenProducts(regimenSkus=[]){const cachedProductList=getLocalStorage(LOCAL_STORAGE_KEY_PRODUCT_MAP);if(regimenSkus&&cachedProductList){const productList=regimenSkus.map(sku=>cachedProductList[sku]);if(productList.every(product=>product!==void 0))return productList}return null}function cacheRegimen(targetSku="",categories=DEFAULT_CATEGORIES,regimenSkus=[],discounts=[]){const lastModified=new Date().toISOString(),cacheEntry={regimenSkus,discounts,lastModified},cachedRegimen=getLocalStorage(LOCAL_STORAGE_KEY_REGIMEN_MAP)||{};cachedRegimen[targetSku]||(cachedRegimen[targetSku]={});const categoriesSortedString=[...categories].sort().join(",");cachedRegimen[targetSku][categoriesSortedString]=cacheEntry,setLocalStorage(LOCAL_STORAGE_KEY_REGIMEN_MAP,cachedRegimen)}function cacheProductData(productList=[]){const cachedProductList=getLocalStorage(LOCAL_STORAGE_KEY_PRODUCT_MAP)||{};productList.forEach(product=>{cachedProductList[product.sku]=product}
8),setLocalStorage(LOCAL_STORAGE_KEY_PRODUCT_MAP,cachedProductList)}async function fetchComplementaryRegimen(skinQuizDomain,sku="",categories=DEFAULT_CATEGORIES){if(!skinQuizDomain)throw new Error("No skin quiz domain provided");const options={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sku,categories})};try{const res=await fetch(`${skinQuizDomain}${API_URL_PATH_COMPLEMENTARY_REGIMEN}`,options),json=await res.json();if(res.ok)return json;throw json.message?new Error(json.message):new Error(`Error retrieving recommendations: ${res.status} - ${res.statusText}`)}catch(err){throw err}}function centsToDollars(value){if(value==null||value==="")return null;const amount=Number(value);return Number.isNaN(amount)?null:amount/100}async function fetchVariantPricingByIds(variantIds=[]){const uniqueVariantIds=[...new Set(variantIds)].map(id=>Number(id)).filter(id=>Number.isFinite(id)&&id>0);if(uniqueVariantIds.length===0)return{};const requests=uniqueVariantIds.map(async variantId=>{const res=await fetch(`/variants/${variantId}.js`);if(!res.ok)throw new Error(`Failed variant lookup for ${variantId}: ${res.status}`);const variant=await res.json(),price=centsToDollars(variant?.price);return price==null?null:{variantId,pricing:{price,compareAtPrice:centsToDollars(variant?.compare_at_price),available:variant?.available??!0}}});return(await Promise.allSettled(requests)).reduce((prev,result)=>result.status==="fulfilled"&&result.value?{...prev,[result.value.variantId]:result.value.pricing}:prev,{})}function computeApplicableDiscountForCount(discounts,count){return!discounts||discounts.length===0?null:[...discounts].sort((a,b)=>b.minQuantity-a.minQuantity).find(d=>count>=d.minQuantity)||null}function computeApplicableDiscount(regimen,discounts){if(!discounts||discounts.length===0)return null;const uniqueInCart=regimen.filter(p=>p.quantityInCart>0).length;return[...discounts].sort((a,b)=>b.minQuantity-a.minQuantity).find(d=>uniqueInCart>=d.minQuantity)||null}function formatPrice2(subtotal,discount){if(discount){const discounted=subtotal*(1-discount.percentage/100),savings=subtotal-discounted;return{original:`$${subtotal.toFixed(2)}`,discounted:`$${discounted.toFixed(2)}`,savings:`Save $${savings.toFixed(2)} (${discount.percentage}% off)`}}else return{value:`$${subtotal.toFixed(2)}`}}function calculateSelectedProductsPrice(selectedProducts){return selectedProducts.reduce((sum,product)=>sum+(product.price||0),0)}function calculateInCartPrice(regimen){return regimen.reduce((sum,product)=>product.quantityInCart>0?sum+(product.price||0):sum,0)}function extractCompleteRegimenValue(discounts){const firstCode=discounts?.[0]?.code??"";if(!firstCode.startsWith(COMPLETE_REGIMEN_DISCOUNT_CODE_PREFIX))return"complete_regimen";const codeParts=firstCode.split("_");return codeParts.length>=3?`${codeParts[1]}_${codeParts[2]}`:"complete_regimen"}function getSelectedProducts(checkboxList){const selectedProducts=[];return checkboxList.forEach(checkbox=>{const cb=checkbox;cb.checked&&cb.dataset.variantId&&selectedProducts.push({id:parseInt(cb.dataset.variantId),size:cb.dataset.size,price:parseFloat(cb.dataset.price)})}),selectedProducts}function createAddProductPayload(variantArray,complementaryRegimenObj,targetSku,concernLabel,concernColor,discounts){const completeRegimenValue=extractCompleteRegimenValue(discounts);return variantArray.map(variant=>{const{id,size}=variant,thisProduct=complementaryRegimenObj[id],{name,category}=thisProduct||{},CATEGORY_LABELS2={cleanser:"Cleanse",treatment:"Treat",eyeTreatment:"Treat",moisturizer:"Hydrate",exfoliantPeel:"Nourish"};return{id,quantity:1,selling_plan:null,properties:{[PRODUCT_PROPERTY_KEYS.size]:size,[PRODUCT_PROPERTY_KEYS.completeRegimen]:completeRegimenValue,[PRODUCT_PROPERTY_KEYS.skinConcernLabel]:`${concernLabel}`,[PRODUCT_PROPERTY_KEYS.skinConcernColor]:`${concernColor}`,[PRODUCT_PROPERTY_KEYS.productCategory]:`${CATEGORY_LABELS2[category]??category}`}}})}function addItemsToCart(variantArray){cartDebugHttp("[CR][Shopify HTTP] cartAddItems request",{itemCount:Array.isArray(variantArray)?variantArray.length:0,variantIds:Array.isArray(variantArray)?variantArray.map(item=>item.id):[]}),cartAddItems(variantArray),cartDebugHttp("[CR][Shopify HTTP] cartAddItems dispatched")}function updateAddToCartButtonState(addToCartButton,selectedProducts,complementaryRegimen,selectItemsLabel,targetSku,targetSkuAlwaysAdd){if(!addToCartButton)return;const completeRegimenIsInCart=complementaryRegimen.every(product=>product.quantityInCart>0);let nonTargetSelected=selectedProducts;targetSkuAlwaysAdd&&(nonTargetSelected=selectedProducts.filter(p=>p.sku!==targetSku)),nonTargetSelected.length===0||completeRegimenIsInCart?disableATCButton(addToCartButton):enableATCButton(addToCartButton);const buttonLabel=addToCartButton.querySelector("[data-button-label]");buttonLabel&&(completeRegimenIsInCart?buttonLabel.textContent="Your regimen is complete":nonTargetSelected.length>0?buttonLabel.textContent=`Add ${selectedProducts.length===complementaryRegimen.length?"ALL":""} ${selectedProducts.length===2?"both":selectedProducts.length} TO BAG`:buttonLabel.textContent=selectItemsLabel)}function disableATCButton(button){button&&(button.disabled=!0,button.classList.add("pointer-events-none"),button.classList.add("opacity-50"))}function enableATCButton(button){button&&(button.classList.remove("pointer-events-none"),button.classList.remove("opacity-50"),button.disabled=!1)}function showLoadingUI(button,spinner){disableATCButton(button),spinner?.classList.remove("hidden")}function hideLoadingUI(button,spinner){enableATCButton(button),spinner?.classList.add("hidden")}function updateTotalPrice(elements,addingPrice,inCartPrice,selectedProducts,complementaryRegimen,categoriesCount,discountInfo){const{elPrice
8Label,elPriceValue,elPriceOriginal,elPriceDiscounted,elPriceSavings,elBundle,elBundleLabel,elBundleValue,elBundleOriginal,elBundleDiscounted,elBundleSavings}=elements;if(!elPriceLabel||!elPriceValue)return;const completeRegimenIsInCart=complementaryRegimen.every(product=>product.quantityInCart>0),uniqueInCart=complementaryRegimen.filter(p=>p.quantityInCart>0).length,effectiveCount=uniqueInCart+selectedProducts.length,renderPrice=(els,subtotal,effectiveCount2)=>{const discount=discountInfo.computeDiscount(effectiveCount2),formatted=discountInfo.formatPrice(subtotal,discount);discount?(els.elOriginal.textContent=formatted.original,els.elOriginal.classList.remove("hidden"),els.elDiscounted.textContent=formatted.discounted,els.elDiscounted.classList.remove("hidden"),els.elSavings.textContent=formatted.savings,els.elSavings.classList.remove("hidden"),els.elValue.textContent="",els.elValue.classList.add("hidden")):(els.elOriginal.classList.add("hidden"),els.elDiscounted.classList.add("hidden"),els.elSavings.classList.add("hidden"),els.elValue.textContent=formatted.value,els.elValue.classList.remove("hidden"))},hideDiscountEls=()=>{elPriceOriginal?.classList.add("hidden"),elPriceDiscounted?.classList.add("hidden"),elPriceSavings?.classList.add("hidden"),elPriceValue?.classList.remove("hidden")},hideBundle=()=>{elBundle?.classList.add("hidden")};if(addingPrice>0&&selectedProducts.length>0){const addingCount=selectedProducts.length;if(uniqueInCart>0)elPriceLabel.textContent=`Adding ${addingCount}: `;else{const allLabel=effectiveCount===categoriesCount?"all ":"";elPriceLabel.textContent=`Price for ${allLabel}${addingCount}: `}if(renderPrice({elOriginal:elPriceOriginal,elDiscounted:elPriceDiscounted,elSavings:elPriceSavings,elValue:elPriceValue},addingPrice,effectiveCount),uniqueInCart>0&&elBundle&&elBundleLabel){const bundleTotal=inCartPrice+addingPrice,allLabel=effectiveCount===categoriesCount?"all ":"";elBundleLabel.textContent=`Total for ${allLabel}${effectiveCount} regimen items: `,renderPrice({elOriginal:elBundleOriginal,elDiscounted:elBundleDiscounted,elSavings:elBundleSavings,elValue:elBundleValue},bundleTotal,effectiveCount),elBundle.classList.remove("hidden")}else hideBundle()}else hideDiscountEls(),hideBundle(),elPriceLabel.textContent="\xA0",elPriceValue.textContent="\xA0"}function updateProductTiles(productTiles,regimen,targetSku,targetSkuAlwaysAdd){productTiles.forEach((tile,i)=>{const t=tile,productData=regimen[i];if(productData){t.dataset.variantId=String(productData.variantId||"");const checkbox=t.querySelector("input[type='checkbox']"),elInCartMessageWrapper=tile.querySelector(".product_in_cart_message_wrapper"),elProductDetailsWrapper=tile.querySelector(".product_details_wrapper"),elListHidenWhenInCart=tile.querySelectorAll(".hide_when_product_in_cart");if(elInCartMessageWrapper&&elProductDetailsWrapper&&(productData.quantityInCart>0?(elInCartMessageWrapper.classList.remove("hidden"),elProductDetailsWrapper.classList.add("opacity-50"),elListHidenWhenInCart.forEach(el=>el.classList.add("hidden"))):(elInCartMessageWrapper.classList.add("hidden"),elProductDetailsWrapper.classList.remove("opacity-50"),elListHidenWhenInCart.forEach(el=>el.classList.remove("hidden")))),checkbox){const cb=checkbox;cb.dataset.variantId=String(productData.variantId),cb.dataset.size=productData.size,cb.dataset.price=String(productData.price),targetSkuAlwaysAdd&&targetSku===productData.sku&&productData.quantityInCart===0?(cb.disabled=!0,cb.classList.add("hidden"),cb.checked=!0):productData.quantityInCart>0?(cb.disabled=!0,cb.classList.add("hidden"),cb.checked=!1):(cb.disabled=!1,cb.classList.remove("hidden"),cb.checked=!0)}for(const key in productData){const thisTileElement=t.querySelector(`.product_${key}`);if(thisTileElement)switch(key){case"category":thisTileElement.textContent=CATEGORY_LABELS[productData[key]]||productData[key];break;case"price":thisTileElement.textContent=`$${Number(productData[key]).toFixed(2)}`;break;case"imgUrl":thisTileElement instanceof HTMLImageElement&&(thisTileElement.src=productData[key],thisTileElement.classList.remove("hidden"));break;case"pdpUrl":thisTileElement instanceof HTMLAnchorElement&&(thisTileElement.href=productData[key]);break;
8case"desc":thisTileElement.textContent=CATEGORY_DESCRIPTIONS[productData.category]||productData.desc||"";break;default:thisTileElement.textContent=String(productData[key])}}const thisItemPreface=tile.querySelector(".product_name_this_item_preface");thisItemPreface&&productData.sku===targetSku&&thisItemPreface.classList.remove("hidden");const inCartPreface=tile.querySelector(".product_in_cart");if(inCartPreface)if(productData.quantityInCart>0){inCartPreface.classList.remove("hidden");const inCartCount=inCartPreface.querySelector(".product_in_cart_count");inCartCount&&(inCartCount.textContent=productData.quantityInCart)}else inCartPreface.classList.add("hidden")}else tile.style.display="none"})}function updateDiscountBanner(banner,discounts,effectiveCount,discountInfo){if(!banner||!discounts||discounts.length===0)return;banner.classList.remove("hidden");const applicableDiscount=discountInfo.computeDiscount(effectiveCount),tiersEl=banner.querySelector("[data-discount-tiers]");tiersEl&&(tiersEl.innerHTML="",[...discounts].sort((a,b)=>a.minQuantity-b.minQuantity).forEach(tier=>{const eligible=effectiveCount>=tier.minQuantity,li=document.createElement("li");li.className="flex flex-row items-center gap-2 py-[2px] select-none";const iconWrapper=document.createElement("span");iconWrapper.className=["flex-shrink-0 w-[18px] h-[18px] rounded-full border-2","flex items-center justify-center transition-colors duration-200",eligible?"bg-text-primary border-text-primary":"border-text-secondary opacity-40"].join(" "),eligible&&(iconWrapper.innerHTML='<svg viewBox="0 0 12 12" fill="none" class="w-[18px] h-[18px]"><path d="M2 6l3 3 5-5" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>');const label=document.createElement("span");label.className=`body-copy-1 transition-colors duration-200 ${eligible?"text-text-primary":"text-text-primary opacity-60"}`,label.textContent=tier.description,li.appendChild(iconWrapper),li.appendChild(label),tiersEl.appendChild(li)}));const noticeEl=banner.querySelector("[data-discount-applied-notice]");noticeEl&&(applicableDiscount?(noticeEl.classList.remove("hidden"),noticeEl.textContent=`${applicableDiscount.percentage}% discount auto-applied to your regimen`):noticeEl.classList.add("hidden"))}function setupIntersectionObserver(elementToObserve,elListToHideSelectors=[]){const getElListToHide=()=>elListToHideSelectors.map(selector=>document.querySelector(selector)).filter(el=>el!==null),prepElsToHide=()=>{elListToHide.forEach(el=>el.classList.add("transition-opacity"))};let elListToHide=getElListToHide();if(prepElsToHide(),elListToHideSelectors.length===0||!elementToObserve)return null;const observer=new IntersectionObserver(([entry])=>{elListToHide.length<elListToHideSelectors.length&&(elListToHide=getElListToHide(),prepElsToHide()),entry.intersectionRatio>=.5&&window.innerWidth<1024?(elListToHide.forEach(el=>el.classList.add("opacity-0")),elListToHide.forEach(el=>setTimeout(()=>el.classList.add("visually-hidden"),150))):(elListToHide.forEach(el=>el.classList.remove("opacity-0")),elListToHide.forEach(el=>setTimeout(()=>el.classList.remove("visually-hidden"),150)))},{threshold:.5});return observer.observe(elementToObserve),observer}function disconnectIntersectionObserver(observer){observer&&observer.disconnect()}function reduceTheNoise(elementToObserve){return setupIntersectionObserver(elementToObserve,ELEMENTS_TO_HIDE_ON_INTERSECTION)}var ComplementaryRegimen=class extends HTMLElement{constructor(){super(),this.section=this.querySelector("section[data-complementary-regimen-main-section]"),this.checkboxList=this.querySelectorAll("input[type='checkbox']"),this.addToCartButton=this.querySelector("button[data-complementary-regimen-atc-button]"),this.form=this.querySelector("[data-complementary-regimen-form]"),this.featureImage=this.querySelector("[data-feature-image]"),this.addToCartSection=this.querySelector("[data-complementary-regimen-atc-section]"),this.atcLoadingSpinner=this.addToCartSection?.querySelector("loading__spinner"),this.loadingSpinnerTitle=this.querySelector(".loading_spinner_title"),this.statusMessageTimeoutId=null,this.statusMessageEl=null,this.sku=this.dataset.sku,this.personalization_group_id=this.dataset.personalizationGroupId,this.targetSku=this.personalization_group_id||this.sku,this.targetSkuAlwaysAdd=this.dataset.targetSkuAlwaysAdd==="true",this.limitCompleteRegimenBundlesToOne=this.dataset.limitCompleteRegimenBundlesToOne==="true",this.concernLabel=this.dataset.concernLabel||"",this.concernColor=this.dataset.concernColor||"#000000",this.categories=this.dataset.categories?this.dataset.categories.split(",").map(cat=>cat.trim()):DEFAULT_CATEGORIES,this.disableCompleteRegimenDiscountWhenOnSale=this.dataset.disableCompleteRegimenDiscountWhenOnSale==="true",this.hasSalePricedRecommendedItems=!1,this.salePricedVariantIds=[],this.mainProduct={},this.complementaryRegimen=[],this.complementaryRegimenObj={},this.discounts=[],this.activeDiscountCode=null,this.cartToken=null,this.storefrontAccessToken=this.dataset.storefrontAccessToken||null,this.storefrontEndpoint="/api/2026-04/graphql.json",this.skinQuizDomain=this.dataset.skinQuizDomain,console.log("node env","development","skin quiz domain",this.skinQuizDomain),this.cartUpdateUnsubscriber=null,this.intersectionObserver=null,this.strings={addComplete:this.dataset.labelAddComplete??LABELS2.addComplete,addSome:this.dataset.labelAddSome??LABELS2.addSome,addOne:this.dataset.labelAddOne??LABELS2.addOne,regimenCompleteATC:this.dataset.labelRegimenComplete??"Your regimen is complete",regimenCompletePrice:this.dataset.labelRegimenCompletePrice??"",selectItemsToAdd:this.dataset.labelSelectItemsToAdd??"Select items to add",removedConflictingRegimen:this.dataset.labelRemovedConflictingRegimen??"Removed items from a different c
8omplete regimen before adding your current selection.",unableToUpdateRegimen:this.dataset.labelUnableToUpdateRegimen??"Could not update complete regimen items in your cart. Please try again."}}async handleRegimenData(){let complementaryRegimen=[];const cachedRegimenData=getCachedRegimenData(this.targetSku,this.categories),cachedRegimenProducts=getCachedRegimenProducts(cachedRegimenData?.regimenSkus);if(cachedRegimenData&&cachedRegimenProducts)complementaryRegimen=cachedRegimenProducts,this.discounts=cachedRegimenData.discounts||[];else{const res=await fetchComplementaryRegimen(this.skinQuizDomain,this.targetSku,this.categories);if(!res.data||!res.data.regimenSkus||!res.data.productList)throw new Error("Invalid regimen data from server");const{regimenSkus,productList,discounts}=res.data;this.discounts=discounts||[],cacheRegimen(this.targetSku,this.categories,regimenSkus,this.discounts),cacheProductData(productList),complementaryRegimen=productList}return this.complementaryRegimen=complementaryRegimen,this.complementaryRegimenObj=complementaryRegimen.reduce((prev,curr)=>({...prev,[curr.variantId]:curr}),{}),complementaryRegimen}getRegimenVariantQuantitiesInCart(variantIdArray=[""],cartRaw){const completeRegimenValue=extractCompleteRegimenValue(this.discounts),regimenItemsInCart=cartRaw.items.filter(item=>item.properties?.[PRODUCT_PROPERTY_KEYS.completeRegimen]===completeRegimenValue&&variantIdArray.includes(item.variant_id));return variantIdArray.map(id=>{const item=regimenItemsInCart.find(item2=>item2.variant_id===id);return item?item.quantity:0})}async updateQuantitiesInCart(cartData){if(cartData||(cartDebugHttp("[CR][Shopify HTTP] getCartData request (updateQuantitiesInCart)"),cartData=await getCartData(),cartDebugHttp("[CR][Shopify HTTP] getCartData response (updateQuantitiesInCart)",{hasToken:!!cartData?.cartRaw?.token})),!cartData){console.warn("No cart data available to update quantities in cart");return}cartData?.cartRaw?.token&&(this.cartToken=cartData.cartRaw.token);const variantQuantities=this.getRegimenVariantQuantitiesInCart(this.complementaryRegimen.map(product=>product.variantId),cartData.cartRaw);this.complementaryRegimen=this.complementaryRegimen.map((product,i)=>({...product,quantityInCart:variantQuantities[i]}))}updateATC(){const selectedWithProductData=getSelectedProducts(this.checkboxList).map(selected=>{const product=this.complementaryRegimenObj[selected.id];return{...selected,sku:product?.sku}});this.updateTotalPriceDisplay(selectedWithProductData),this.updateATCButtonDisplay(selectedWithProductData),this.updateDiscountBannerDisplay(selectedWithProductData)}updateATCButtonDisplay(selectedProducts){updateAddToCartButtonState(this.addToCartButton,selectedProducts,this.complementaryRegimen,this.strings.selectItemsToAdd,this.targetSku,this.targetSkuAlwaysAdd)}updateTotalPriceDisplay(selectedProducts){const selectedPrices=selectedProducts.map(p=>this.complementaryRegimenObj[p.id]?.price||0),addingPrice=calculateSelectedProductsPrice(selectedProducts.map(p=>({price:selectedPrices[selectedProducts.indexOf(p)]}))),inCartPrice=calculateInCartPrice(this.complementaryRegimen),effectiveDiscounts=this.getEffectiveDiscounts();updateTotalPrice({elPriceLabel:this.querySelector("[data-total-price-label]"),elPriceValue:this.querySelector("[data-total-price-value]"),elPriceOriginal:this.querySelector("[data-total-price-original]"),elPriceDiscounted:this.querySelector("[data-total-price-discounted]"),elPriceSavings:this.querySelector("[data-total-price-savings]"),elBundle:this.querySelector("[data-total-price-bundle]"),elBundleLabel:this.querySelector("[data-total-price-bundle-label]"),elBundleValue:this.querySelector("[data-total-price-bundle-value]"),elBundleOriginal:this.querySelector("[data-total-price-bundle-original]"),elBundleDiscounted:this.querySelector("[data-total-price-bundle-discounted]"),elBundleSavings:this.querySelector("[data-total-price-bundle-savings]")},addingPrice,inCartPrice,selectedProducts,this.complementaryRegimen,this.categories.length,{computeDiscount:count=>computeApplicableDiscountForCount(effectiveDiscounts,count),formatPrice:(subtotal,discount)=>formatPrice2(subtotal,discount)})}updateProductTiles(){const productTiles=this.querySelectorAll(".complementary_regimen__product_tile");updateProductTiles(productTiles,this.complementaryRegimen,this.targetSku,this.targetSkuAlwaysAdd)}updateDiscountBannerDisplay(selectedProducts){const banner=this.querySelector("[data-discount-banner]"),effectiveDiscounts=this.getEffectiveDiscounts();if(banner&&effectiveDiscounts.length===0){banner.classList.add("hidden");return}const effectiveCount=this.complementaryRegimen.filter(p=>p.quantityInCart>0).length+selectedProducts.length;updateDiscountBanner(banner,effectiveDiscounts,effectiveCount,{computeDiscount:count=>computeApplicableDiscountForCount(effectiveDiscounts,count)}
8)}shouldSuppressRegimenDiscounts(){return this.disableCompleteRegimenDiscountWhenOnSale&&this.hasSalePricedRecommendedItems}getEffectiveDiscounts(){return this.shouldSuppressRegimenDiscounts()?[]:this.discounts||[]}async evaluateSalePricingGuard(){if(!this.disableCompleteRegimenDiscountWhenOnSale)return;const variantIds=this.complementaryRegimen.map(product=>Number(product?.variantId)).filter(id=>Number.isFinite(id)&&id>0);if(variantIds.length!==0)try{const pricingByVariantId=await fetchVariantPricingByIds(variantIds);this.salePricedVariantIds=variantIds.filter(variantId=>{const pricing=pricingByVariantId[variantId];return!pricing||pricing.compareAtPrice==null?!1:pricing.compareAtPrice>pricing.price}),this.hasSalePricedRecommendedItems=this.salePricedVariantIds.length>0,cartDebug("[CR] sale-pricing discount guard evaluation",{enabled:this.disableCompleteRegimenDiscountWhenOnSale,hasSalePricedRecommendedItems:this.hasSalePricedRecommendedItems,salePricedVariantIds:this.salePricedVariantIds})}catch(err){this.salePricedVariantIds=[],this.hasSalePricedRecommendedItems=!1,cartDebug("[CR] failed sale-pricing guard evaluation",err)}}ensureStatusMessageElement(){if(this.statusMessageEl)return this.statusMessageEl;const messageEl=document.createElement("div");return messageEl.setAttribute("data-complementary-regimen-status",""),messageEl.setAttribute("aria-live","polite"),messageEl.className="hidden mt-2 body-copy-2 text-text-primary",this.addToCartSection?this.addToCartSection.appendChild(messageEl):this.appendChild(messageEl),this.statusMessageEl=messageEl,this.statusMessageEl}showStatusMessage(message){if(!message)return;const messageEl=this.ensureStatusMessageElement();messageEl&&(messageEl.textContent=message,messageEl.classList.remove("hidden"),this.statusMessageTimeoutId&&window.clearTimeout(this.statusMessageTimeoutId),this.statusMessageTimeoutId=window.setTimeout(()=>{this.statusMessageEl&&this.statusMessageEl.classList.add("hidden")},6e3))}getCurrentCompleteRegimenValue(){if(!this.discounts||this.discounts.length===0)return null;const value=extractCompleteRegimenValue(this.discounts);return value&&value.trim()!==""?value:null}async getConflictingCompleteRegimenItemKeys(){const currentValue=this.getCurrentCompleteRegimenValue();if(!currentValue)return[];cartDebugHttp("[CR][Shopify HTTP] getCartData request (conflictingRegimenCheck)");const cartData=await getCartData(!0);return cartDebugHttp("[CR][Shopify HTTP] getCartData response (conflictingRegimenCheck)",{itemCount:cartData?.cartRaw?.items?.length??0}),(cartData?.cartRaw?.items??[]).filter(item=>{const itemValue=item?.properties?.[PRODUCT_PROPERTY_KEYS.completeRegimen];return itemValue!=null&&itemValue!==""&&itemValue!==currentValue}).map(item=>item.key).filter(Boolean)}async removeCartItemsByKey(itemKeys){if(!Array.isArray(itemKeys)||itemKeys.length===0)return;cartDebugHttp("[CR][Shopify HTTP] getCartData request (resolve conflicting regimen keys)",{itemCount:itemKeys.length});const freshCartItems=(await getCartData(!0))?.cartRaw?.items??[],itemKeySet=new Set(itemKeys),updates=freshCartItems.reduce((prev,item)=>itemKeySet.has(item.key)?{...prev,[item.key]:0}:prev,{}),keysToRemove=Object.keys(updates);if(keysToRemove.length===0){cartDebugHttp("[CR][Shopify HTTP] conflicting regimen items no longer in cart; skipping",{requestedItemCount:itemKeys.length});return}cartDebugHttp("[CR][Shopify HTTP] cart/update request (remove conflicting regimen items)",{requestedItemCount:itemKeys.length,resolvedItemCount:keysToRemove.length});const res=await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({updates})});if(!res.ok){const errorText=await res.text();throw new Error(`Failed removing conflicting complete regimen items (count ${keysToRemove.length}, status ${res.status}) ${errorText}`)}cartDebugHttp("[CR][Shopify HTTP] cart/update response (remove conflicting regimen items)",{resolvedItemCount:keysToRemove.length,status:res.status})}async removeCompleteRegimenDiscountCodeIfPresent(){cartDebugHttp("[CR][Shopify HTTP] getCartData request (removeC
8ompleteRegimenDiscountCodeIfPresent)");const cartData=await getCartData(!0);this.cartToken=cartData?.cartRaw?.token||this.cartToken;const discountCodeList=Array.isArray(cartData?.cartRaw?.discount_codes)?cartData.cartRaw.discount_codes.map(entry=>entry?.code):[],discountCodeSingle=cartData?.cartRaw?.discount_code,activeCompleteCode=discountCodeList.find(code=>typeof code=="string"&&code.startsWith(COMPLETE_REGIMEN_DISCOUNT_CODE_PREFIX))||(typeof discountCodeSingle=="string"&&discountCodeSingle.startsWith(COMPLETE_REGIMEN_DISCOUNT_CODE_PREFIX)?discountCodeSingle:null);return!activeCompleteCode||!this.cartToken?!1:(cartDebugHttp("[CR][Shopify HTTP] updateCartDiscountCodes request (clear complete-regimen code)",{discountCode:activeCompleteCode}),await updateCartDiscountCodes(this.cartToken,[],{endpoint:this.storefrontEndpoint,storefrontToken:this.storefrontAccessToken}),this.activeDiscountCode=null,cartDebugHttp("[CR][Shopify HTTP] updateCartDiscountCodes response (clear complete-regimen code)"),!0)}async addItemsToCart(){showLoadingUI(this.addToCartButton,this.atcLoadingSpinner);try{const selectedCheckboxes=getSelectedProducts(this.checkboxList),variantArray=createAddProductPayload(selectedCheckboxes,this.complementaryRegimenObj,this.targetSku,this.concernLabel,this.concernColor,this.discounts);if(this.limitCompleteRegimenBundlesToOne){const conflictingItemKeys=await this.getConflictingCompleteRegimenItemKeys();conflictingItemKeys.length>0&&(await this.removeCartItemsByKey(conflictingItemKeys),this.showStatusMessage(this.strings.removedConflictingRegimen))}addItemsToCart(variantArray);const simulatedRegimen=this.complementaryRegimen.map(product=>{const match=variantArray.find(v=>v.id===product.variantId);return match?{...product,quantityInCart:(product.quantityInCart||0)+(match.quantity||1)}:product})}catch(err){hideLoadingUI(this.addToCartButton,this.atcLoadingSpinner),this.showStatusMessage(this.strings.unableToUpdateRegimen),console.error("Failed to add complementary regimen items:",err)}}async syncDiscountCode(regimenOverride=null){if(!this.discounts||this.discounts.length===0)return;if(this.shouldSuppressRegimenDiscounts()){await this.removeCompleteRegimenDiscountCodeIfPresent(),this.activeDiscountCode=null;return}const effectiveDiscounts=this.getEffectiveDiscounts();if(!effectiveDiscounts||effectiveDiscounts.length===0)return;const regimen=regimenOverride||this.complementaryRegimen,newCode=computeApplicableDiscount(regimen,effectiveDiscounts)?.code||null;if(newCode!==this.activeDiscountCode)try{if(cartDebugHttp("[CR][Shopify HTTP] discount code transition",{oldCode:this.activeDiscountCode,newCode}),!this.cartToken){cartDebugHttp("[CR][Shopify HTTP] getCartData request (syncDiscountCode)");const freshCartData=await getCartData();this.cartToken=freshCartData?.cartRaw?.token||null,cartDebugHttp("[CR][Shopify HTTP] getCartData response (syncDiscountCode)",{hasToken:!!this.cartToken})}if(this.cartToken){const codes=newCode?[newCode]:[];cartDebugHttp("[CR][Shopify HTTP] updateCartDiscountCodes request",{cartToken:this.cartToken,codes,endpoint:this.storefrontEndpoint}),await updateCartDiscountCodes(this.cartToken,codes,{endpoint:this.storefrontEndpoint,storefrontToken:this.storefrontAccessToken}),cartDebugHttp("[CR][Shopify HTTP] updateCartDiscountCodes response",{appliedCodes:codes})}this.activeDiscountCode=newCode,cartActions.cartRefresh()}catch(err){cartDebugHttp("[CR][Shopify HTTP] updateCartDiscountCodes error",err),console.error("Failed to apply regimen discount code via Storefront API:",err)}}async onCartUpdate(cartData){hideLoadingUI(this.addToCartButton,this.atcLoadingSpinner),cartDebug("complementary-regimen onCartUpdate",cartData),await this.updateQuantitiesInCart(cartData),this.updateProductTiles(),this.updateATC(),await this.syncDiscountCode()}addEventListeners(){this.checkboxList.forEach(checkbox=>{checkbox.addEventListener("change",this.updateATC.bind(this))}),this.addToCartButton?.addEventListener("click",this.addItemsToCart.bind(this))}async connectedCallback(){this.intersectionObserver=reduceTheNoise(this);try{const complementaryRegimen=await this.handleRegimenData();await this.evaluateSalePricingGuard(),this.mainProduct=complementaryRegimen.find(product=>
8product.sku===this.targetSku),await this.updateQuantitiesInCart(),this.updateProductTiles(),this.form&&this.form.classList.remove("hidden"),this.featureImage&&this.featureImage.classList.remove("hidden"),this.updateATC(),this.addEventListeners(),this.cartUpdateUnsubscriber=subscribe(PUB_SUB_EVENTS.cartMutationComplete,async payload=>{await this.onCartUpdate(payload.cartData)},"complementary-regimen")}catch(err){this.section?.style.setProperty("min-height","unset"),this.style.display="none",console.error(err)}finally{this.loadingSpinnerTitle?.classList.add("hidden")}}disconnectedCallback(){this.checkboxList.forEach(checkbox=>{checkbox.removeEventListener("change",this.updateATC.bind(this))}),this.addToCartButton?.removeEventListener("click",this.addItemsToCart.bind(this)),this.cartUpdateUnsubscriber&&this.cartUpdateUnsubscriber(),this.intersectionObserver&&disconnectIntersectionObserver(this.intersectionObserver),this.statusMessageTimeoutId&&window.clearTimeout(this.statusMessageTimeoutId)}};customElements.define("complementary-regimen",ComplementaryRegimen);var CountdownTimerSession=class extends HTMLElement{constructor(){super(),this.intervalId=null,this.hasRedirected=!1,this.hasHiddenComponent=!1,this.hasReplacedContent=!1,this.startTimeMs=Date.now(),this.displayEl=this.querySelector("[data-countdown-display]"),this.contentEl=this.querySelector("[data-countdown-content]"),this.startMinutes=this.parseStartMinutes(this.dataset.startMinutes),this.hideOnExpireEnabled=this.parseBoolean(this.dataset.hideOnExpireEnabled),this.replaceWithTextEnabled=this.parseBoolean(this.dataset.replaceWithTextEnabled),this.replaceWithText=this.dataset.replaceWithText?.trim()??"",this.redirectEnabled=this.parseBoolean(this.dataset.redirectEnabled),this.redirectUrl=this.dataset.redirectUrl?.trim()??"";const sectionId=this.dataset.sectionId||"header-bare",path=window.location.pathname||"/";this.storageKey=`murad:countdown-timer-session:${sectionId}:${path}`,this.durationMs=this.startMinutes*60*1e3}connectedCallback(){this.initializeStartTime(),this.updateDisplay(),this.showReadyState(),this.intervalId&&clearInterval(this.intervalId),this.intervalId=window.setInterval(()=>{this.updateDisplay()},1e3)}disconnectedCallback(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}parseStartMinutes(value){const parsed=Number.parseInt(value??"",10);return!Number.isFinite(parsed)||parsed<1?5:parsed}parseBoolean(value){return value===!0||value==="true"||value==="1"}initializeStartTime(){try{const existingValue=window.localStorage.getItem(this.storageKey);if(existingValue){const existingTime=Number.parseInt(existingValue,10);if(Number.isFinite(existingTime)&&existingTime>0){this.startTimeMs=existingTime;return}}this.startTimeMs=Date.now(),window.localStorage.setItem(this.storageKey,this.startTimeMs.toString())}catch{this.startTimeMs=Date.now()}}showReadyState(){this.classList.remove("invisible")}getRemainingMs(){const elapsedMs=Date.now()-this.startTimeMs;return Math.max(this.durationMs-elapsedMs,0)}formatMMSS(msRemaining){const totalSeconds=Math.floor(msRemaining/1e3),minutes=Math.floor(totalSeconds/60),seconds=totalSeconds%60;return`${String(minutes).padStart(2,"0")}:${String(seconds).padStart(2,"0")}`}updateDisplay(){const remainingMs=this.getRemainingMs();if(this.displayEl&&(this.displayEl.textContent=this.formatMMSS(remainingMs)),remainingMs===0){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.hideOnExpireEnabled&&!this.hasHiddenComponent&&(this.classList.add("hidden"),this.setAttribute("aria-hidden","true"),this.hasHiddenComponent=!0),this.contentEl&&!this.hideOnExpireEnabled&&this.replaceWithTextEnabled&&this.replaceWithText&&!this.hasReplacedContent){const replacementEl=document.createElement("span");replacementEl.className="eyebrow-1 whitespace-nowrap",replacementEl.textContent=this.replaceWithText,this.contentEl.replaceChildren(replacementEl),this.hasReplacedContent=!0}this.redirectEnabled&&this.redirectUrl&&!this.hasRedirected&&(this.hasRedirected=!0,window.location.assign(this.redirectUrl))}}};customElements.define("countdown-timer-session",CountdownTimerSession);var LOCAL_STORAGE_KEY_YOTPO_POINTS_EXPIRING="muradYotpoPointsExpiring",YOTPO_POINTS_EXPIRING_STALE_AFTER_MS=1e3*60*15;function getCachedPointsData(customerEmail){const cachedEntry=getLocalStorage(LOCAL_STORAGE_KEY_YOTPO_POINTS_EXPIRING)?.[customerEmail];return!cachedEntry||hasTimeElapsed(cachedEntry.lastModified,YOTPO_POINTS_EXPIRING_STALE_AFTER_MS)?null:{pointsBalance:cachedEntry.points
8Balance,nextExpireOn:cachedEntry.nextExpireOn,nextExpireAmount:cachedEntry.nextExpireAmount}}function setCachedPointsData(customerEmail,pointsBalance,nextExpireOn,nextExpireAmount){const cachedVal=getLocalStorage(LOCAL_STORAGE_KEY_YOTPO_POINTS_EXPIRING);setLocalStorage(LOCAL_STORAGE_KEY_YOTPO_POINTS_EXPIRING,{...cachedVal,[customerEmail]:{pointsBalance,nextExpireOn,nextExpireAmount,lastModified:new Date().toISOString()}})}function isOnRedeemUrlPage(redeemUrl){const normalize=path=>{try{return new URL(path,window.location.origin).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}};return normalize(window.location.pathname)===normalize(redeemUrl)}var YotpoPointsExpiringWidget=class extends HTMLElement{constructor(){super(),this.enabled=this.dataset.enabled==="true",this.minPoints=Number.parseInt(this.dataset.minPoints,10)||0,this.customerEmail=this.dataset.customerEmail?.trim()??"",this.apiUrl=this.dataset.apiUrl?.trim()??"",this.apiKey=this.dataset.apiKey?.trim()??"",this.template=this.dataset.template??"",this.redeemUrl=this.dataset.redeemUrl?.trim()||"/pages/rewards"}connectedCallback(){!this.enabled||!this.customerEmail||!this.apiUrl||!this.apiKey||(this.forceFetch=isOnRedeemUrlPage(this.redeemUrl),this.fetchAndMaybeReplace())}async fetchAndMaybeReplace(){if(!this.forceFetch){const cached=getCachedPointsData(this.customerEmail);if(cached){this.maybeRender(cached.pointsBalance,cached.nextExpireOn,cached.nextExpireAmount);return}}try{const res=await fetch(`${this.apiUrl}/api/customers/points-expiration`,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json","x-api-key":this.apiKey},body:JSON.stringify({customer_email:this.customerEmail})});if(!res.ok)return;const{data}=await res.json(),pointsBalance=Number(data?.points_balance),nextExpireOn=data?.next_points_expire_on??null,nextExpireAmount=Number(data?.next_points_expire_amount);setCachedPointsData(this.customerEmail,pointsBalance,nextExpireOn,nextExpireAmount),this.maybeRender(pointsBalance,nextExpireOn,nextExpireAmount)}catch(err){console.error("yotpo-points-expiring-widget",err)}}maybeRender(pointsBalance,nextExpireOn,nextExpireAmount){if(pointsBalance===0){this.hidePointsDisplay();return}!Number.isFinite(pointsBalance)||pointsBalance<this.minPoints||!nextExpireOn||!Number.isFinite(nextExpireAmount)||this.renderExpiringLink(nextExpireAmount,nextExpireOn)}hidePointsDisplay(){const display=this.querySelector("[data-yotpo-points-display]");display&&display.classList.add("hidden")}renderExpiringLink(nextExpireAmount,nextExpireOn){if(nextExpireAmount===null||nextExpireOn===null)return;const target=this.querySelector("[data-yotpo-points-rewards-link]");if(!target)return;const copy=this.template.replace("|points|",nextExpireAmount.toLocaleString()).replace("|date|",this.formatDate(nextExpireOn)),link=document.createElement("a");link.href=this.redeemUrl,link.className="yotpo-rewards-points-expiring body-copy-3 text-text-secondary-alt underline",link.textContent=copy,target.replaceChildren(link)}formatDate(dateString){const[year,month,day]=dateString.split("-").map(Number);return new Date(year,month-1,day).toLocaleDateString(document.documentElement.lang||"en-US",{month:"short",day:"numeric",year:"numeric"})}};customElements.define("yotpo-points-expiring-widget",YotpoPointsExpiringWidget);var LOCAL_STORAGE_KEY_QUIZ_METAFIELD="muradQuizRecommendations_metafield",LOCAL_STORAGE_KEY_QUIZ_LOCAL_SESSIONS="muradQuizRecommendations_localSessions",MAX_CART_ITEMS_TO_PROBE=8,CONCERN_LABELS={concern_unknown:"Your Regimen",for_breakouts:"Breakouts",for_brightening:"Brightening",for_darkSpots:"Dark Spots",for_dryness:"Dryness",for_liftingFirming:"Lifting & Firming",for_linesWrinkles:"Lines & Wrinkles",for_oilinessPores:"Oiliness & Pores",for_scars:"Scars",for_sensitiveEczema:"Sensitive & Eczema-Prone"};function readMetafieldValue(embeddedJson){if(embeddedJson)try{const parsed=JSON.parse(embeddedJson);return setLocalStorage(LOCAL_STORAGE_KEY_QUIZ_METAFIELD,parsed),parsed}catch(err){console.error("quiz-recommendations: failed to parse embedded metafield JSON",err)}return getLocalStorage(LOCAL_STORAGE_KEY_QUIZ_METAFIELD)}function determineKnownUserRegimen(metafieldValue){const sessions=metafieldValue?.quizSessions;
8if(!Array.isArray(sessions))return null;for(let i=sessions.length-1;i>=0;i--){const entry=sessions[i];if(entry?.didComplete===!0&&Array.isArray(entry.regimenList)&&entry.regimenList.length>0)return entry}return null}function getBestKnownUserEntry(embeddedMetafieldJson){const metafieldValue=readMetafieldValue(embeddedMetafieldJson),localValue=getLocalStorage(LOCAL_STORAGE_KEY_QUIZ_LOCAL_SESSIONS),metafieldEntry=determineKnownUserRegimen(metafieldValue),localEntry=determineKnownUserRegimen(localValue);return metafieldEntry?localEntry&&new Date(localEntry.dateComplete)>new Date(metafieldEntry.dateComplete)?localEntry:metafieldEntry:localEntry}function normalizeProduct(product){return product?{variantId:product.variantId,sku:product.sku,name:product.name,category:product.category,tags:product.tags??[],price:product.price,compareAtPrice:product.compareAtPrice??null,size:product.size,desc:product.desc,imgUrl:product.imgUrl,pdpUrl:product.pdpUrl,rating:product.rating,available:product.isInStock??product.available??!0,rolloverImgUrl:product.rolloverImgUrl,award:product.award,awardAltText:product.awardAltText,upsellText:product.upsellText}:null}function flattenRegimenMap(regimen){return Object.values(regimen??{}).filter(Boolean).map(normalizeProduct)}async function probeCartItemRegimens(skinQuizDomain,cartItems=[]){const distinctItems=[],seenSkus=new Set;for(const item of cartItems)if(!(!item?.sku||seenSkus.has(item.sku))&&(seenSkus.add(item.sku),distinctItems.push(item),distinctItems.length>=MAX_CART_ITEMS_TO_PROBE))break;const results=await Promise.allSettled(distinctItems.map(async cartItem=>{const cachedRegimenData=getCachedRegimenData(cartItem.sku,DEFAULT_CATEGORIES),cachedRegimenProducts=getCachedRegimenProducts(cachedRegimenData?.regimenSkus);if(cachedRegimenData&&cachedRegimenProducts)return{cartItem,productList:cachedRegimenProducts.map(normalizeProduct)};const res=await fetchComplementaryRegimen(skinQuizDomain,cartItem.sku,DEFAULT_CATEGORIES);if(!res?.data?.regimenSkus||!res?.data?.productList)throw new Error(`Invalid completeRegimen response for sku ${cartItem.sku}`);const{regimenSkus,productList,discounts}=res.data;return cacheRegimen(cartItem.sku,DEFAULT_CATEGORIES,regimenSkus,discounts||[]),cacheProductData(productList),{cartItem,productList:productList.map(normalizeProduct),discounts:discounts||[]}}));return distinctItems.map((cartItem,i)=>results[i].status==="fulfilled"?results[i].value:null).filter(Boolean)}function buildCartSkuSet(cartData){return new Set((cartData?.items??[]).map(item=>item.sku))}function dedupeProducts(candidateProducts,cartSkuSet){const seen=new Set,result=[];for(const product of candidateProducts??[])product?.sku&&product.available!==!1&&(cartSkuSet.has(product.sku)||seen.has(product.sku)||(seen.add(product.sku),result.push(product)));return result}async function loadSlider(){return(await import("./chunk--Slider-D6YNBQKI.vbt.js")).default}async function loadTabs(){return(await import("./chunk--Tabs-XDGVW46J.vbt.js")).default}var SLIDER_OPTIONS_BASE={arrows:!1,pagination:!1,fixedWidth:"275px",gap:"1.5rem",padding:{left:"1rem",right:"5%"},breakpoints:{1024:{fixedWidth:"320px",arrows:!0},1440:{fixedWidth:"360px"}}};function buildSliderOptions(sliderType,compact){if(compact){const{breakpoints,...base}=SLIDER_OPTIONS_BASE;return{...base,type:sliderType||"slide"}}return{...SLIDER_OPTIONS_BASE,type:sliderType||"slide"}}var TAGS_EXCLUDED_FROM_QUICK_ADD=["coming-soon","waitlist"];function buildQuickAdd(quickAddTemplate,product){const node=quickAddTemplate.content.firstElementChild.cloneNode(!0);return node.dataset.quickAddVariantId=String(product.variantId??""),product.size&&(node.dataset.quickAddSize=product.size),node}function populateSimpleTile(tileTemplate,quickAddTemplate,product){const node=tileTemplate.content.firstElementChild.cloneNode(!0);node.dataset.variantId=String(product.variantId??""),node.dataset.variantSku=product.sku??"",node.dataset.productTitle=product.name??"";const imgEl=node.querySelector(".qr-imgUrl");imgEl instanceof HTMLImageElement&&product.imgUrl&&(imgEl.src=product.imgUrl,imgEl.alt=product.name??"",imgEl.classList.remove("hidden"));const rolloverEl=node.querySelector(".qr-rolloverImgUrl");rolloverEl instanceof HTMLImageElement&&product.rolloverImgUrl&&(rolloverEl.src=product.rolloverImgUrl,rolloverEl.alt=`${product.name??""} rollover image`,rolloverEl.classList.remove("hidden"),rolloverEl.classList.add("lg:block"));const awardEl=node.querySelector(".qr-award");awardEl instanceof HTMLImageElement&&product.award&&(awardEl.src=product.award,awardEl.alt=product.awardAltText??"",awardEl.classList.remove("hidden"));const upsellEl=node.querySelector(".qr-upsellText");upsellEl&&product.upsellText&&(upsellEl.textContent=product.upsellText.toUpperCase(),upsellEl.classList.remove("hidden"));const categoryEl=node.querySelector(".qr-category");categoryEl&&(categoryEl.textContent=product.category??"");const nameEl=node.querySelector(".qr-name");nameEl&&(nameEl.textContent=product.name??"");const sizeEl=node.querySelector(".qr-size");
8sizeEl&&(sizeEl.textContent=product.size??"");const priceEl=node.querySelector(".qr-price");priceEl&&(priceEl.textContent=product.price!=null?formatPrice(product.price):"");const compareAtEl=node.querySelector(".qr-compareAtPrice");compareAtEl&&(product.compareAtPrice&&product.compareAtPrice>product.price?(compareAtEl.textContent=formatPrice(product.compareAtPrice),compareAtEl.classList.remove("hidden")):compareAtEl.classList.add("hidden")),node.querySelectorAll(".qr-pdpUrl").forEach(el=>{el instanceof HTMLAnchorElement&&(el.href=product.pdpUrl??"#")});const ratingEl=node.querySelector(".qr-rating");ratingEl&&(ratingEl.textContent=product.rating!=null?String(product.rating):"");const quickAddSlot=node.querySelector(".qr-quickAddSlot"),isExcludedFromQuickAdd=(product.tags??[]).some(tag=>TAGS_EXCLUDED_FROM_QUICK_ADD.includes(tag));return quickAddSlot&&!isExcludedFromQuickAdd&&quickAddSlot.appendChild(buildQuickAdd(quickAddTemplate,product)),node}function buildSimpleTilePanel(tileTemplate,quickAddTemplate,products,arrowsTemplate,sliderType,compactArrows){const splide=document.createElement("div");splide.setAttribute("data-slider",JSON.stringify(buildSliderOptions(sliderType,compactArrows))),compactArrows?splide.className="splide":(splide.className="splide arrows-wider arrows-auto-hide",splide.appendChild(arrowsTemplate.content.firstElementChild.cloneNode(!0)));const track=document.createElement("div");track.className="splide__track";const list=document.createElement("div");return list.className="splide__list",products.forEach(product=>{const slide=document.createElement("div");slide.className="splide__slide",slide.appendChild(populateSimpleTile(tileTemplate,quickAddTemplate,product)),list.appendChild(slide)}),track.appendChild(list),splide.appendChild(track),splide}function buildBundlePanel(bundleData,showDiscountBanner){const el=document.createElement("quiz-recommendation-bundle");return el.dataset.anchorSku=bundleData.anchorCartItem?.sku??"",el.dataset.anchorName=bundleData.anchorCartItem?.product_title??"",el.dataset.showDiscountBanner=String(showDiscountBanner),el.dataset.products=JSON.stringify(bundleData.productList),el.dataset.discounts=JSON.stringify(bundleData.discounts??[]),el}function buildOverrideTabPanel(pristineSlides,cartSkuSet,maxSlots,arrowsTemplate,sliderType,compactArrows){const qualifying=pristineSlides.filter(slide=>{const sku=slide.querySelector("[data-product-card]")?.dataset.variantSku;return!(sku&&cartSkuSet.has(sku))}).slice(0,maxSlots);if(qualifying.length===0)return null;const splide=document.createElement("div");splide.setAttribute("data-slider",JSON.stringify(buildSliderOptions(sliderType,compactArrows))),compactArrows?splide.className="splide":(splide.className="splide arrows-wider arrows-auto-hide",splide.appendChild(arrowsTemplate.content.firstElementChild.cloneNode(!0)));const track=document.createElement("div");track.className="splide__track";const list=document.createElement("div");return list.className="splide__list",qualifying.forEach(slide=>list.appendChild(slide.cloneNode(!0))),track.appendChild(list),splide.appendChild(track),splide}function applyCta(ctaEl,cta){if(ctaEl instanceof HTMLAnchorElement){if(!cta){ctaEl.classList.add("hidden");return}ctaEl.textContent=cta.text,ctaEl.href=cta.href,ctaEl.classList.remove("hidden")}}async function revealCuratedTab(container,pristineSlides,cartSkuSet,maxSlots,cta,sliderType,compactArrows){applyCta(container.querySelector("[data-quiz-recommendations-cta]"),cta);const splideEl=container.querySelector(".splide"),listEl=container.querySelector(".splide__list");if(!splideEl||!listEl){container.classList.add("hidden");return}splideEl.splide?.destroy();const promoIndex=pristineSlides.findIndex(slide=>slide.matches("[data-quiz-recommendations-promo-slide]")),promoSlide=promoIndex===-1?null:pristineSlides[promoIndex],promoIsFirst=promoIndex===0,qualifying=(promoSlide?pristineSlides.filter((_,index)=>index!==promoIndex):pristineSlides).filter(slide=>{const sku=slide.querySelector("[data-product-card]")?.dataset.variantSku;return!(sku&&cartSkuSet.has(sku))}).slice(0,maxSlots);if(qualifying.length===0&&!promoSlide){container.classList.add("hidden");return}listEl.innerHTML="",promoSlide&&promoIsFirst&&listEl.appendChild(promoSlide.cloneNode(!0)),qualifying.forEach(sli
8de=>listEl.appendChild(slide.cloneNode(!0))),promoSlide&&!promoIsFirst&&listEl.appendChild(promoSlide.cloneNode(!0)),splideEl.setAttribute("data-slider",JSON.stringify(buildSliderOptions(sliderType,compactArrows)));const SliderClass=await loadSlider();new SliderClass(splideEl,"data-slider"),container.classList.remove("hidden")}function hideCuratedTab(container){container.querySelector(".splide")?.splide?.destroy(),container.classList.add("hidden")}var CART_TAB_NAME_CHAR_BUDGET=60,CART_TAB_NAME_MIN_CHARS=12;function truncateProductName(name,tabCount){const safeName=name??"",maxChars=Math.max(CART_TAB_NAME_MIN_CHARS,Math.floor(CART_TAB_NAME_CHAR_BUDGET/Math.max(tabCount,2)));return safeName.length<=maxChars?safeName:`${safeName.slice(0,maxChars-1).trimEnd()}\u2026`}async function renderTabs(rootEl,tabs,heading,cta){if(rootEl.innerHTML="",!tabs.length){rootEl.classList.add("hidden");return}if(rootEl.classList.remove("hidden"),heading){const headingRow=document.createElement("div");headingRow.className="flex items-center justify-between gap-4 mb-6 ml-4 pr-4";const headingEl=document.createElement("h2");if(headingEl.className="subheadline text-text-primary",headingEl.textContent=heading,headingRow.appendChild(headingEl),cta){const ctaEl=document.createElement("a");ctaEl.target="_blank",ctaEl.className="max-w-[40%] eyebrow-1 underline text-text-primary text-right",applyCta(ctaEl,cta),headingRow.appendChild(ctaEl)}rootEl.appendChild(headingRow)}const tabsWrapper=document.createElement("div");tabsWrapper.setAttribute("data-tabs","click");const tablist=document.createElement("div");tablist.setAttribute("role","tablist"),tablist.className="flex gap-6 mb-4 ml-4 pr-16 overflow-x-scroll overflow-y-hidden no-scrollbar select-none",enableHorizontalScroll(tablist),tabs.forEac
8h((tab,i)=>{const button=document.createElement("button");if(button.type="button",button.setAttribute("role","tab"),button.className=`min-h-8 flex items-center shrink-0 ${i===0?"active":""} group`,button.setAttribute("data-tab-toggle",`qr-tab--${i}`),typeof tab.title!="string"&&tab.title.image){const imgEl=document.createElement("img");imgEl.src=tab.title.image,imgEl.alt="",imgEl.className="w-20 h-20 rounded-full object-cover shrink-0 scale-150",imgEl.draggable=!1,button.appendChild(imgEl)}const textWrapper=document.createElement("div");textWrapper.className="h-full p-4 border-text-primary-translucent border-r-2 border-t-2 rounded-tr group-[.active]:border-text-primary group-[.active]:bg-gradient-to-b group-[.active]:from-body-alt group-[.active]:via-body-alt/80 group-[.active]:to-transparent";const h2=document.createElement("h2");if(typeof tab.title=="string")h2.className="whitespace-nowrap subheadline text-text-primary-alt group-[.active]:text-text-primary group-[.active]:font-semibold",h2.textContent=tab.title;else{h2.className="whitespace-nowrap";const prefixEl=document.createElement("span");prefixEl.className="block eyebrow-2 text-text-primary-alt group-[.active]:text-text-primary",prefixEl.textContent=tab.title.prefix;const nameEl=document.createElement("span");nameEl.className="block product-name text-text-primary-alt group-[.active]:text-text-primary group-[.active]:font-semibold",nameEl.textContent=truncateProductName(tab.title.name,tabs.length),h2.appendChild(prefixEl),h2.appendChild(nameEl)}textWrapper.appendChild(h2),button.appendChild(textWrapper),tablist.appendChild(button)}
8),tabsWrapper.appendChild(tablist),tabs.forEach((tab,i)=>{const panelWrapper=document.createElement("div");panelWrapper.setAttribute("role","tabpanel"),panelWrapper.className=i===0?"active":"",panelWrapper.setAttribute("data-tab-content",`qr-tab--${i}`),panelWrapper.appendChild(tab.panel),tabsWrapper.appendChild(panelWrapper)}),rootEl.appendChild(tabsWrapper);const TabsClass=await loadTabs();new TabsClass(tabsWrapper,"data-tabs").init();const sliderEls=rootEl.querySelectorAll("[data-slider]");if(sliderEls.length>0){const SliderClass=await loadSlider();sliderEls.forEach(el=>new SliderClass(el,"data-slider"))}tabsWrapper.addEventListener("tabs:activated",event=>{event.target?.querySelectorAll?.("[data-slider]").forEach(el=>{el.splide?.refresh()})})}var LOG_PREFIX="[quiz-recommendations]",DEBUG=!1;function log(...args){DEBUG&&console.log(LOG_PREFIX,...args)}var QuizRecommendations=class extends HTMLElement{constructor(){super(),this.rootEl=this.querySelector("[data-quiz-recommendations-root]"),this.tileTemplate=document.querySelector("template[data-quiz-recommendations-simple-tile]"),this.quickAddTemplate=document.querySelector("template[data-quiz-recommendations-quick-add-template]"),this.arrowsTemplate=document.querySelector("template[data-quiz-recommendations-arrows-template]"),this.curatedContainer=this.querySelector("[data-quiz-recommendations-curated]"),this.curatedPristineSlides=Array.from(this.curatedContainer?.querySelectorAll(".splide__slide")??[]).map(slide=>slide.cloneNode(!0)),this.overrideSourceContainer=this.querySelector("[data-quiz-recommendations-override-source]"),this.overridePristineSlides=Array.from(this.overrideSourceContainer?.querySelectorAll(".splide__slide")??[]).map(slide=>slide.cloneNode(!0)),this.overrideMode=this.dataset.overrideMode||"",this.overrideTabTitle=this.dataset.overrideTabTitle||"",this.quizCtaTakeText=this.dataset.quizCtaTakeText||"",this.quizCtaRetakeText=this.dataset.quizCtaRetakeText||"",this.quizCtaLoginText=this.dataset.quizCtaLoginText||"",this.showQuizCtaWithCartItems=this.dataset.showQuizCtaWithCartItems==="true",this.skinQuizDomain=this.dataset.skinQuizDomain||"",this.maxSlots=parseInt(this.dataset.maxSlots??"",10)||6,this.carouselType=this.dataset.carouselType||"slide",this.showDiscountBanner=this.dataset.showDiscountBanner==="true",this.forceCuratedForAll=this.dataset.forceCuratedForAll==="true",this.hasCustomer=this.dataset.hasCustomer==="true",this.knownUserTitle=this.dataset.knownUserTitle||"",this.knownUserTabPrefix=this.dataset.knownUserTabPrefix||"",this.cartBasedTitle=this.dataset.cartBasedTitle||"",this.cartBasedTabPrefix=this.dataset.cartBasedTabPrefix||"",this.cartBasedTabShowImage=this.dataset.cartBasedTabShowImage==="true",this.compactArrows=this.dataset.context==="cart_drawer";const metafieldScript=this.querySelector("script[data-quiz-recommendations-metafield]");this.embeddedMetafieldJson=this.hasCustomer?metafieldScript?.textContent?.trim():void 0,this.cartUpdateUnsubscriber=null,log("init:",{hasCustomer:this.hasCustomer,metafieldEmbedded:!!this.embeddedMetafieldJson,curatedSlideCount:this.curatedPristineSlides.length,forceCuratedForAll:this.forceCuratedForAll,maxSlots:this.maxSlots,carouselType:this.carouselType,showDiscountBanner:this.showDiscountBanner,skinQuizDomain:this.skinQuizDomain})}async connectedCallback(){if(!this.rootEl||!this.tileTemplate||!this.quickAddTemplate||!this.arrowsTemplate){console.error("quiz-recommendations: missing required child elements"),this.style.display="none";return}try{await this.renderCurrentState(),this.cartUpdateUnsubscriber=subscribe(PUB_SUB_EVENTS.cartMutationComplete,async()=>{await this.renderCurrentState()},"quiz-recommendations")}catch(err){this.style.display="none",console.error("quiz-recommendations: failed to initialize",err)}}disconnectedCallback(){this.cartUpdateUnsubscriber&&this.cartUpdateUnsubscriber()}async renderCurrentState(){const rootEl=this.rootEl;if(!rootEl)return;const cartData=await getCartData(),cartSkuSet=buildCartSkuSet(cartData),cartItemCount=cartData?.items?.length??0,cartHasItems=cartItemCount>0,knownUserEntry=getBestKnownUserEntry(this.embeddedMetafieldJson),cta=!knownUserEntry&&cartHasItems&&!this.showQuizCtaWithCartItems?void 0:this.getQuizCta(!!knownUserEntry);return this.overrideMode==="replace"&&this.overridePristineSlides.length>0?(log('status: override mode "replace" (forces override list for all shoppers)',{cartItemCount}),this.renderCuratedTab(rootEl,cartSkuSet,"override replace",cta)):this.forceCuratedForAll?(log("status: forced curated for all shoppers (kill-switch on)",{cartItemCount}),this.renderCuratedTab(rootEl,cartSkuSet,"forceCuratedForAll",cta)):knownUserEntry?(log("status: known user",{sessionId:knownUserEntry.sessionId,concernPrimary:knownUserEntry.concernPrimary,concernSecondary:knownUserEntry.concernSecondary,dateComplete:knownUserEntry.dateComplete,cartItemCount}),this.renderKnownUserTabs(rootEl,knownUserEntry,cartSkuSet,cta)):(log("status: unknown user",{hasCustomer:this.hasCustomer,cartItemCount,cartHasItems}),cartHasItems?this.renderCartBasedTabs(rootEl,cartData,cartSkuSet,cta):this.renderCuratedTab(rootEl,cartSkuSet,"unknown user, empty cart",cta))}getQuizCta(hasKnownUserEntry){if(!hasKnownUserEntry)return this.quizCtaTakeText?{text:this.quizCtaTakeText+" \u2197",href:"/pages/skin-quiz"}:void 0;if(this.hasCustomer)return this.quizCtaRetakeText?{text:this.quizCtaRetakeText+" \u2197",href:"/pages/skin-regimen-quiz?retake=1"}:void 0;if(this.quizCtaLoginText)return{text:this.quizCtaLoginText+" \u2197",href:"/account/login"}}maybePrependOverrideTab(tabs,cartSkuSet){if(this.overrideMode!=="prepend"||this.overridePristineSlides.length===0||!this.arrowsTemplate)return;const panel=buildOverrideTabPanel(this.overridePristineSlides,cartSkuSet,this.maxSlots,this.arrowsTemplate,this.carouselType,this.compactArrows);panel&&tabs.unshift({title:this.overrideTabTitle,panel})}async renderKnownUserTabs(rootEl,entry,cartSkuSet,cta){if(log(`source: known-user regimenList (metafield entry ${entry.sessionId})`),this.curatedContainer&&hideCuratedTab(this.curatedContainer),!this.tileTemplate||!this.quickAddTemplate||!this.arrowsTemplate)return;const tileTemplate=this.tileTemplate,quickAddTemplate=this.quickAddTemplate,arrowsTemplate=this.arrowsTemplate,[regimenPrimary,regimenSecondary]=entry.regimenList,flatPrimary=flattenRegimenMap(regimenPrimary),flatSecondary=flattenRegimenMap(regimenSecondary),allVariantIds=[...flatPrimary,...flatSecondary].map(product=>product.variantId),pricingByVariantId=await fetchVariantPricingByIds(allVariantIds),revalidate=products=>products.filter(product=>pricingByVariantId[product.variantId]).map(product=>({...product,...pricingByVariantId[product.variantId]})),rawTabs=[{title:CONCERN_LABELS[entry.concernPrimary]??entry.concernPrimary,rawCount:flatPrimary.length,products:revalidate(flatPrimary)},{title:CONCERN_LABELS[entry.concernSecondary]??entry.concernSecondary,rawCount:flatSecondary.length,products:revalidate(flatSecondary)}];log("known-user revalidation:",rawTabs.map(tab=>({title:tab.title,rawCount:tab.rawCount,afterRevalidateCount:tab.products.length})));const tabs=rawTabs.map(tab=>({...tab,products:dedupeProducts(tab.products,cartSkuSet).slice(0,this.maxSlots)})).filter(tab=>tab.products.length>0).map(tab=>({title:{prefix:this.knownUserTabPrefix,name:tab.title},panel:buildSimpleTilePanel(tileTemplate,quickAddTemplate,tab.products,arrowsTemplate,this.carouselType,this.compactArrows)}));this.maybePrependOverrideTab(tabs,cartSkuSet),log("known-user final tabs (after cart dedupe + maxSlots):",tabs.map(tab=>tab.title)),await renderTabs(rootEl,tabs,this.knownUserTitle,cta)}async renderCartBasedTabs(rootEl,cartData,cartSkuSet,cta){log("source: cart-based completeRegimen (probing up to 8 distinct cart SKUs)"),this.curatedContainer&&hideCuratedTab(this.curatedContainer);const cartItemsNonZeroCost=cartData.items.filter(item=>item.price>0)??[],probed=await probeCartItemRegimens(this.skinQuizDomain,cartItemsNonZeroCost);log("cart-based probe results:",probed.map(result=>({sku:result.cartItem.sku,title:result.cartItem.product_title,rawSuggestionCount:result.productList.length})));const maxTabs=Math.min(3,this.maxSlots),qualifying=[],rejected=[];for(const result of probed){const deduped=dedupeProducts(result.productList,cartSkuSet);if(deduped.length>=2?qualifying.push({anchorCartItem:result.cartItem,productList:deduped.slice(0,this.maxSlots),discounts:result.discounts}):rejected.push({sku:result.cartItem.sku,afterDedupeCount:deduped.length}),qualifying.length>=maxTabs)break}log("cart-based qualification:",{qualifying:qualifying.map(bundleData=>({anchorSku:bundleData.anchorCartItem.sku,anchorTitle:bundleData.anchorCartItem.product_title,finalProductCount:bundleData.productList.length})),rejected}),log("cart-based presentation mode:",this.showDiscountBanner?"bundle/discount UI":"plain carousel (no discount)");const titleFor=bundleData=>({prefix:this.cartBasedTabPrefix,name:bundleData.anchorCartItem.product_title,image:this.cartBasedTabShowImage?bundleData.anchorCartItem.image:void 0});let tabs;if(this.showDiscountBanner)tabs=qualifying.map(bundleData=>({title:titleFor(bundleData),panel:buildBundlePanel(bundleData,!0)}));else{const tileTemplate=this.tileTemplate,quickAddTemplate=this.quickAddTemplate,arrowsTemplate=this.arrowsTemplate;if(!tileTemplate||!quickAddTemplate||!arrowsTemplate)return;tabs=qualifying.map(bundleData=>({title:titleFor(bundleData),panel:buildSimpleTilePanel(tileTemplate,quickAddTemplate,bundleData.productList,arrowsTemplate,this.carouselType,this.compactArrows)}))}this.maybePrependOverrideTab(tabs,cartSkuSet),await renderTabs(rootEl,tabs,this.cartBasedTitle,cta)}async renderCuratedTab(rootEl,cartSkuSet,reason,cta){if(log(`source: curated collection, real new-product-card markup (reason: ${reason})`),await renderTabs(rootEl,[]),!this.curatedContainer){console.error("quiz-recommendations: missing curated container");return}await revealCuratedTab(this.curatedContainer,this.curatedPristineSlides,cartSkuSet,this.maxSlots,cta,this.carouselType,this.compactArrows),log("curated dedupe:",{rawCount:this.curatedPristineSlides.length,containerHidden:this.curatedContainer.classList.contains("hidden")})}};customElements.define("quiz-recommendations",QuizRecommendations);var QuizRecommendationBundle=class extends HTMLElement{constructor(){super(),this.cartUpdateUnsubscriber=null}
8readDatasetConfig(){this.products=JSON.parse(this.dataset.products||"[]"),this.discounts=JSON.parse(this.dataset.discounts||"[]"),this.showDiscountBanner=this.dataset.showDiscountBanner==="true",this.anchorSku=this.dataset.anchorSku||"",this.anchorName=this.dataset.anchorName||"",this.productsByVariantId=this.products.reduce((acc,product)=>(acc[product.variantId]=product,acc),{})}buildRegimenWithQuantities(cartData){const qtyMap={};return(cartData?.items??[]).forEach(item=>{qtyMap[item.variant_id]=(qtyMap[item.variant_id]||0)+item.quantity}),this.products.map(product=>({...product,quantityInCart:qtyMap[product.variantId]||0}))}computeDiscount(effectiveCount){return computeApplicableDiscountForCount(this.discounts,effectiveCount)}updateProductTilesDisplay(){updateProductTiles(Array.from(this.productTiles),this.regimen,this.anchorSku,!1)}updateATC(){const selectedCheckboxes=getSelectedProducts(this.checkboxList);updateAddToCartButtonState(this.addToCartButton,selectedCheckboxes,this.regimen,"Select items to add",this.anchorSku,!1);const addingPrice=calculateSelectedProductsPrice(selectedCheckboxes),inCartPrice=calculateInCartPrice(this.regimen),discountInfo={computeDiscount:count=>this.computeDiscount(count),formatPrice:formatPrice2};if(updateTotalPrice(this.priceElements,addingPrice,inCartPrice,selectedCheckboxes,this.regimen,this.regimen.length,discountInfo),this.showDiscountBanner&&this.discountBannerEl){const effectiveCount=this.regimen.filter(product=>product.quantityInCart>0).length+selectedCheckboxes.length;updateDiscountBanner(this.discountBannerEl,this.discounts,effectiveCount,discountInfo)}}async handleAddToCart(){showLoadingUI(this.addToCartButton,this.atcLoadingSpinner);try{const selectedCheckboxes=getSelectedProducts(this.checkboxList),variantArray=createAddProductPayload(selectedCheckboxes,this.productsByVariantId,this.anchorSku,`Pair with ${this.anchorName}`,"",this.discounts);addItemsToCart(variantArray)}catch(err){hideLoadingUI(this.addToCartButton,this.atcLoadingSpinner),console.error("quiz-recommendation-bundle: failed to add items to cart",err)}}addEventListeners(){this.checkboxList.forEach(checkbox=>checkbox.addEventListener("change",this.updateATC.bind(this))),this.addToCartButton?.addEventListener("click",this.handleAddToCart.bind(this))}async connectedCallback(){this.readDatasetConfig();const panelTemplate=document.querySelector("template[data-quiz-recommendations-bundle-panel]"),tileTemplate=document.querySelector("template[data-quiz-recommendations-bundle-tile]");if(!panelTemplate||!tileTemplate){console.error("quiz-recommendation-bundle: missing bundle-panel/tile template"),this.style.display="none";return}this.appendChild(panelTemplate.content.cloneNode(!0));const tileList=this.querySelector("[data-tile-list]");this.products.forEach(()=>{tileList.appendChild(tileTemplate.content.cloneNode(!0))}),this.productTiles=this.querySelectorAll(".complementary_regimen__product_tile"),this.checkboxList=this.querySelectorAll("input[type='checkbox']"),this.addToCartButton=this.querySelector("[data-complementary-regimen-atc-button]"),this.atcLoadingSpinner=this.querySelector(".loading__spinner_spinner"),this.discountBannerEl=this.querySelector("[data-discount-banner]"),this.priceElements={elPriceLabel:this.querySelector("[data-total-price-label]"),elPriceValue:this.querySelector("[data-total-price-value]"),elPriceOriginal:this.querySelector("[data-total-price-original]"),elPriceDiscounted:this.querySelector("[data-total-price-discounted]"),elPriceSavings:this.querySelector("[data-total-price-savings]"),elBundle:this.querySelector("[data-total-price-bundle]"),elBundleLabel:this.querySelector("[data-total-price-bundle-label]"),elBundleValue:this.querySelector("[data-total-price-bundle-value]"),elBundleOriginal:this.querySelector("[data-total-price-bundle-original]"),elBundleDiscounted:this.querySelector("[data-total-price-bundle-discounted]"),elBundleSavings:this.querySelector("[data-total-price-bundle-savings]")},this.showDiscountBanner||this.discountBannerEl?.classList.add("hidden");try{const cartData=await getCartData();this.regimen=this.buildRegimenWithQuantities(cartData),this.updateProductTilesDisplay(),this.updateATC(),this.addEventListeners(),this.cartUpdateUnsubscriber=subscribe(PUB_SUB_EVENTS.cartMutationComplete,async payload=>
8{hideLoadingUI(this.addToCartButton,this.atcLoadingSpinner),this.regimen=this.buildRegimenWithQuantities(payload.cartData),this.updateProductTilesDisplay(),this.updateATC()},"quiz-recommendation-bundle")}catch(err){this.style.display="none",console.error("quiz-recommendation-bundle: failed to initialize",err)}}disconnectedCallback(){this.checkboxList?.forEach(checkbox=>checkbox.removeEventListener("change",this.updateATC.bind(this))),this.addToCartButton?.removeEventListener("click",this.handleAddToCart.bind(this)),this.cartUpdateUnsubscriber&&this.cartUpdateUnsubscriber()}};customElements.define("quiz-recommendation-bundle",QuizRecommendationBundle);var API_URL_PATH_BADGE_DISCOUNTS="/api/discounts/badges",LOCAL_STORAGE_KEY_BADGE_DISCOUNTS="muradBadgeDiscounts",BADGE_DISCOUNTS_STALE_AFTER=1e3*60*60;function getCachedBadgeDiscounts(skinQuizDomain){let cached;try{cached=getLocalStorage(LOCAL_STORAGE_KEY_BADGE_DISCOUNTS)}catch{return null}if(!cached||cached.skinQuizDomain!==skinQuizDomain)return null;const{discounts,lastModified}=cached,timestamp=Date.parse(lastModified);return!Number.isFinite(timestamp)||timestamp>Date.now()||hasTimeElapsed(lastModified,BADGE_DISCOUNTS_STALE_AFTER)?null:Array.isArray(discounts)?discounts:null}function cacheBadgeDiscounts(discounts=[],skinQuizDomain){try{setLocalStorage(LOCAL_STORAGE_KEY_BADGE_DISCOUNTS,{discounts,skinQuizDomain,lastModified:new Date().toISOString()})}catch{}}var loadedBadgeDiscounts=null;function getLoadedBadgeDiscounts(){return loadedBadgeDiscounts}function setLoadedBadgeDiscounts(discounts=[]){loadedBadgeDiscounts=Array.isArray(discounts)?discounts:[]}var pageRequests=new Map;function loadBadgeDiscounts(skinQuizDomain){const domain=skinQuizDomain.replace(/\/$/,"");if(!pageRequests.has(domain)){const request=(async()=>{const cached=getCachedBadgeDiscounts(domain);if(cached)return cached;const res=await fetchBadgeDiscounts(domain);if(res.success!==!0||!Array.isArray(res.data?.discounts))throw new Error("Invalid badge discounts response");return cacheBadgeDiscounts(res.data.discounts,domain),res.data.discounts})();pageRequests.set(domain,request.finally(()=>pageRequests.delete(domain)))}return pageRequests.get(domain)}async function fetchBadgeDiscounts(skinQuizDomain){if(!skinQuizDomain)throw new Error("No skin quiz domain provided");try{const res=await fetch(`${skinQuizDomain}${API_URL_PATH_BADGE_DISCOUNTS}`,{cache:"no-store",signal:AbortSignal.timeout(1e4)}),json=await res.json();if(res.ok)return json;throw json.message?new Error(json.message):new Error(`Error retrieving badge discounts: ${res.status} - ${res.statusText}`)}catch(err){throw err}}var BadgeDiscounts=class extends HTMLElement{constructor(){super(),this.skinQuizDomain=this.dataset.skinQuizDomain,this.discounts=[]}connectedCallback(){this.onResume=()=>{document.visibilityState!=="hidden"&&this.refresh()},window.addEventListener("pageshow",this.onResume),this.refresh()}disconnectedCallback(){clearTimeout(this.refreshTimer),window.removeEventListener("pageshow",this.onResume)}async refresh(){if(!this.refreshing){this.refreshing=!0,clearTimeout(this.refreshTimer),this.skinQuizDomain||setLoadedBadgeDiscounts([]);try{this.skinQuizDomain&&(this.discounts=await loadBadgeDiscounts(this.skinQuizDomain))}catch(err){console.error("Failed to load badge discounts:",err),this.discounts=[]}this.refreshing=!1,this.isConnected&&(setLoadedBadgeDiscounts(this.discounts),this.dispatchEvent(new CustomEvent("badge-discounts:loaded",{bubbles:!0,detail:{discounts:this.discounts}})),this.skinQuizDomain&&(this.refreshTimer=setTimeout(()=>this.onResume(),BADGE_DISCOUNTS_STALE_AFTER)))}}};customElements.define("badge-discounts",BadgeDiscounts);function isProductEligibleForDiscount(discount,product){const eligibility=discount?.eligibility;if(!eligibility||!product)return!1;switch(eligibility.scope){case"all":return!0;case"products":return Array.isArray(eligibility.productIds)&&eligibility.productIds.includes(product.id);case"collections":return Array.isArray(eligibility.collectionIds)&&(product.collectionIds||[]).some(id=>eligibility.collectionIds.includes(id));default:return!1}}function getEligibleDiscountsForProduct(discounts=[],product){return Array.isArray(discounts)?discounts.filter(discount=>isProductEligibleForDiscount(discount,product)):[]}function isPercentageDiscount(discount){return discount?.valueType==="percentage"&&typeof discount.value=="number"&&Number.isFinite(discount.value)&&discount.value>0&&discount.value<=100}function discountedPrice(price,discount){return!Number.isInteger(price)||price<0||!isPercentageDiscount(discount)?null:Math.round(price*(100-discount.value)/100)}function formatPromoMoney(cents,currency,locale,compact=!1){const options={style:"currency",currency};return compact&&(options.minimumFractionDigits=0),new Intl.NumberFormat(locale||"en-US",options).format(cents/100)}function getPromoPurchasePrice(variant,purchaseType,sellingPlanId){return purchaseType!=="subscription"?variant?.price:variant?.allocations?.find(plan=>String(plan.id)===String(sellingPlanId))?.price}var DiscountBadge=class extends HTMLElement{connectedCallback(){const productId=Number(this.dataset.productId);if(!productId)return;let collectionIds=[];try{collectionIds=JSON.parse(this.dataset.collectionIds||"[]")}catch{collectionIds=[]}this.product={id:productId,collectionIds},this.onPurchaseChange=event=>{event?.target?.closest&&!event.target.closest("subscription-widget")||this.render(getLoadedBadgeDiscounts()||[])},this.onVariantChange=({detail})=>{this.pdpData?.variants.some(variant=>variant.id===Number(detail?.variantId))&&(this.dataset.variantId=String(detail.variantId),this.onPurchaseChange())},this.dataset.pageType==="pdp"&&(document.addEventListener("murad:variant:change",this.onVariantChange),document.addEventListener("change",this.onPurchaseChange),document.addEventListener("input",this.onPurchaseChange)),this.onDiscountsLoaded=event=>this.render(event.detail?.discounts||[]),document.addEventListener("badge-discounts:loaded",this.onDiscountsLoaded);const loaded=getLoadedBadgeDiscounts();loaded&&this.render(loaded)}disconnectedCallback(){this.onDiscountsLoaded&&document.removeEventListener("badge-discounts:loaded",this.onDiscountsLoaded),document.removeEventListener("murad:variant:change",this.onVariantChange),document.removeEventListener("change",this.onPurchaseChange),document.removeEventListener("input",this.onPurchaseChange)}get pdpData(){if(this.dataset.pageType!=="pdp")return null;
8try{return JSON.parse(document.querySelector(`[data-promo-product="${this.product.id}"]`)?.textContent||"null")}catch{return null}}get purchase(){const data=this.pdpData;if(!data)return null;const widget=document.querySelector(`subscription-widget[data-product-form-id="${data.formId}"]`),formVariant=document.querySelector("input[data-main-cta]")?.value,variantId=Number(formVariant||this.dataset.variantId),variant=data.variants.find(item=>item.id===variantId),planId=widget?.querySelector("select")?.value||variant?.allocations[0]?.id,subscription=widget?!!widget.querySelector('input[value="subscription"]:checked'):data.defaultPurchaseType==="subscription";return{variant,planId,subscription}}eligibleDiscount(discounts){if(!Array.isArray(discounts)||discounts.length!==1)return null;const purchase=this.purchase;if(purchase&&!purchase.variant)return null;const variant=purchase?.variant;if(variant?variant.compareAtPrice>variant.price:Number(this.dataset.compareAtPrice)>Number(this.dataset.variantPrice))return null;const[discount]=getEligibleDiscountsForProduct(discounts,this.product);return discount?.type!=="code"||typeof discount.code!="string"||!discount.code.trim()||typeof discount.description!="string"||!discount.description.trim()||discount.valueType==="percentage"&&!isPercentageDiscount(discount)?null:discount}render(discounts){this.classList.add("hidden"),this.removeAttribute("data-discount-badge-active"),this.textContent="";const discount=this.eligibleDiscount(discounts);if(!discount)return;const useShortDescription="shortDescription"in this.dataset;this.textContent=this.dataset.style==="strikethrough"&&isPercentageDiscount(discount)&&useShortDescription?discount.description_with_strikethrough_price:useShortDescription&&discount.description_short?discount.description_short:discount.description,this.setAttribute("data-discount-badge-active",""),this.classList.remove("hidden")}};customElements.define("discount-badge",DiscountBadge);var PromoPrice=class extends DiscountBadge{render(discounts){const fallback=this.querySelector("[data-promo-price-fallback]"),output=this.querySelector("[data-promo-price-output]");if(!fallback||!output)return;this.originalFallback??=fallback.innerHTML;const purchase=this.purchase,purchaseType=this.dataset.purchaseType==="selected"?purchase?.subscription?"subscription":"one-time":this.dataset.purchaseType,price=purchase?getPromoPurchasePrice(purchase.variant,purchaseType,purchase.planId):Number(this.dataset.basePrice),format=cents=>formatPromoMoney(cents,this.dataset.currency,document.documentElement.lang,this.dataset.pageType!=="pdp");if(purchase&&Number.isInteger(price)&&(this.dataset.purchaseType==="selected"||purchase.variant?.id!==Number(this.dataset.initialVariantId)||price!==Number(this.dataset.basePrice))){const comparePrice=purchaseType==="subscription"?purchase.variant.price:purchase.variant.compareAtPrice;if(fallback.replaceChildren(),this.dataset.mode==="price"&&comparePrice>price){const compare=document.createElement("s");compare.textContent=format(comparePrice),fallback.append(compare," ")}fallback.append(format(price)),this.fallbackUpdated=!0}else this.fallbackUpdated&&(fallback.innerHTML=this.originalFallback,this.fallbackUpdated=!1);const discount=this.eligibleDiscount(discounts),discounted=this.dataset.style==="strikethrough"?discountedPrice(price,discount):null,active=discounted!==null;if(fallback.classList.toggle("hidden",active),output.classList.toggle("hidden",!active),output.replaceChildren(),!active)return;if(this.dataset.mode==="price"){const compare=document.createElement("s");compare.textContent=format(price),output.append(compare," ")}const finalPrice=document.createElement("span");finalPrice.textContent=format(discounted),output.append(finalPrice)}};customElements.define("promo-price",PromoPrice);var CART_RULES_CONFIG={RULE_1_ENABLED:!0,RULE_1_CAP:window.cartItemMaxQuantity??CART_LINE_ITEM_QUANTITY_MAX_DEFAULT,RULE_2_ENABLED:!0,RULE_2_CAP:1,RULE_3_ENABLED:!0,RULE_4_ENABLED:!0,RULE_4_CAP:10,RULE_5_ENABLED:!0,RULE_6_ENABLED:!0,RULE_7A_ENABLED:!1,RULE_7B_ENABLED:!1};function isCompleteRegimenItem(item){return!!item.properties?._complete_regimen}function getCompleteRegimenValue(item){return item.properties?._complete_regimen??null}function parseCompleteRegimenCode(code){if(!code||!code.startsWith(COMPLETE_REGIMEN_DISCOUNT_CODE_PREFIX))return null;const parts=code.split("_");if(parts.length<5)return null;const minQuantity=parseInt(parts[3],10);return isNaN(minQuantity)?null:{regimenValue:`${parts[1]}_${parts[2]}`,minQuantity}}function getStorefrontConfig(){const endpoint="/api/2026-04/graphql.json",gwpEl=document.querySelector("[data-gwp]");if(gwpEl)try{const props=JSON.parse(gwpEl.getAttribute("data-gwp"));if(props?.graphql_storefront_access_token)return{endpoint,storefrontToken:props.graphql_storefront_access_token}}catch{}const crEl=document.querySelector("complementary-regimen[data-storefront-access-token]");if(crEl){const token=crEl.getAttribute("data-storefront-access-token");if(token)return{endpoint,storefrontToken:token}}return{endpoint,storefrontToken:null}}function isRuleEnabled(configDefault,lsKey){return localStorage.getItem("muradCartRules")==="0"||localStorage.getItem(lsKey)==="0"?!1:configDefault}function isZeroDollarItem(item){return item.original_price===0}function enforceCartRules(cartData){const items=cartData?.cartRaw?.items??[];if(items.length===0)return{messages:[],shouldClear:!1,updates:{},changes:[]};cartDebug("enforceCartRules started with cart data:",cartData);const messages=[];if(isRuleEnabled(CART_RULES_CONFIG.RULE_5_ENABLED,"muradCartRulesRule5")&&
8cartData.cartTotalPrice===0)return cartDebug("enforceCartRules rule 5: clearing zero-dollar-only cart"),messages.push("Your cart contained only free items and has been cleared."),{messages,shouldClear:!0,updates:{},changes:[]};const updates={},changes=[],zeroDollarVariantsSeen=new Set;let zeroDollarRunningTotal=0;for(const item of items){const variantId=item.variant_id;if(isZeroDollarItem(item)){if(isRuleEnabled(CART_RULES_CONFIG.RULE_3_ENABLED,"muradCartRulesRule3")&&zeroDollarVariantsSeen.has(variantId)){const keyToRemove=item.key;cartDebug(`enforceCartRules rule 3: duplicate zero-dollar variant ${variantId} ("${item.title}") \u2014 queuing removal of line item key ${keyToRemove}`),messages.push(`A duplicate free item ("${item.title}") was removed from your cart.`),changes.push({id:keyToRemove,quantity:0});continue}zeroDollarVariantsSeen.add(variantId);let correctedQty=isRuleEnabled(CART_RULES_CONFIG.RULE_2_ENABLED,"muradCartRulesRule2")?Math.min(item.quantity,CART_RULES_CONFIG.RULE_2_CAP):item.quantity;if(isRuleEnabled(CART_RULES_CONFIG.RULE_2_ENABLED,"muradCartRulesRule2")&&correctedQty<item.quantity&&(cartDebug(`enforceCartRules rule 2: capping zero-dollar item ${variantId} ("${item.title}") from ${item.quantity} to ${correctedQty}`),messages.push(`Free item quantity for "${item.title}" was reduced to ${correctedQty} (maximum ${CART_RULES_CONFIG.RULE_2_CAP} per free item).`)),isRuleEnabled(CART_RULES_CONFIG.RULE_4_ENABLED,"muradCartRulesRule4")){const capacityRemaining=CART_RULES_CONFIG.RULE_4_CAP-zeroDollarRunningTotal;correctedQty>capacityRemaining&&(cartDebug(`enforceCartRules rule 4: total zero-dollar qty limit reached; reducing "${item.title}" from ${correctedQty} to ${capacityRemaining}`),messages.push(`Your cart has reached the maximum of ${CART_RULES_CONFIG.RULE_4_CAP} free items. "${item.title}" quantity was adjusted.`),correctedQty=capacityRemaining)}zeroDollarRunningTotal+=correctedQty,correctedQty!==item.quantity&&(updates[variantId]=correctedQty)}else isRuleEnabled(CART_RULES_CONFIG.RULE_1_ENABLED,"muradCartRulesRule1")&&item.quantity>CART_RULES_CONFIG.RULE_1_CAP&&(cartDebug(`enforceCartRules rule 1: capping paid item ${variantId} ("${item.title}") from ${item.quantity} to ${CART_RULES_CONFIG.RULE_1_CAP}`),messages.push(`"${item.title}" quantity was reduced to ${CART_RULES_CONFIG.RULE_1_CAP} (maximum per item).`),updates[variantId]=CART_RULES_CONFIG.RULE_1_CAP),CART_RULES_CONFIG.RULE_7B_ENABLED&&isCompleteRegimenItem(item)&&item.quantity>1&&(cartDebug(`enforceCartRules rule 7: capping complete_regimen item ${variantId} ("${item.title}") from ${item.quantity} to 1`),messages.push(`"${item.title}" is part of a skin-care regimen and has been limited to a quantity of 1.`),updates[variantId]=1)}if(cartDebug("enforceCartRules rule 6: rule enabled =",isRuleEnabled(CART_RULES_CONFIG.RULE_6_ENABLED,"muradCartRulesRule6"),"| window.cartLowerLimits =",window.cartLowerLimits),isRuleEnabled(CART_RULES_CONFIG.RULE_6_ENABLED,"muradCartRulesRule6")){const rawLimits=Array.isArray(window.cartLowerLimits)?window.cartLowerLimits:[];cartDebug(`enforceCartRules rule 6: ${rawLimits.length} limit entries found`);for(const[entryIdx,entry]of rawLimits.entries()){const entryLimit=Number(entry.limit);if(cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] raw limit = ${entry.limit}, parsed = ${entryLimit}, valid = ${Number.isInteger(entryLimit)&&entryLimit>0}`),!Number.isInteger(entryLimit)||entryLimit<=0)continue;const groupVariantIds=new Set((entry.variantIds??[]).map(Number).filter(Boolean));if(cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] groupVariantIds (${groupVariantIds.size}):`,[...groupVariantIds]),groupVariantIds.size===0)continue;const groupItems=items.filter(item=>!isZeroDollarItem(item)&&groupVariantIds.has(item.variant_id));if(cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] groupItems (${groupItems.length}):`,groupItems.map(i=>({key:i.key,variant_id:i.variant_id,title:i.title,qty:i.quantity,zeroDollar:isZeroDollarItem(i)}))),cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] all cart items for reference:`,items.map(i=>({key:i.key,variant_id:i.variant_id,title:i.title,qty:i.quantity,zeroDollar:isZeroDollarItem(i),inGroup:groupVariantIds.has(i.variant_id)}))),groupItems.length===0)continue;const groupTotal=groupItems.reduce((sum,item)=>sum+item.quantity,0);cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] groupTotal = ${groupTotal}, entryLimit = ${entryLimit}, violation = ${groupTotal>entryLimit}`);const allowedQtyByVariantId=new Map;if(groupTotal>entryLimit){cartDebug(`enforceCartRules rule 6: product group cart
8-wide total ${groupTotal} exceeds limit ${entryLimit}; applying corrections`);let remaining=entryLimit;for(const item of groupItems){const allowedQty=Math.min(item.quantity,remaining);remaining-=allowedQty,allowedQtyByVariantId.set(item.variant_id,(allowedQtyByVariantId.get(item.variant_id)??0)+allowedQty),cartDebug(`enforceCartRules rule 6: greedy \u2014 item key=${item.key} variant=${item.variant_id} ("${item.title}") qty=${item.quantity} allowedQty=${allowedQty} remainingAfter=${remaining} needsCorrection=${allowedQty<item.quantity}`),allowedQty<item.quantity&&(cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] variant ${item.variant_id} ("${item.title}") needs reduction from ${item.quantity} to ${allowedQty} (group limit ${entryLimit})`),messages.push(`Limited special offer - "${item.title}" quantity was reduced to ${allowedQty} (maximum ${entryLimit} for this special offer).`))}cartDebug("enforceCartRules rule 6: allowedQtyByVariantId after greedy:",Object.fromEntries(allowedQtyByVariantId));for(const[variantId,allowedQty]of allowedQtyByVariantId){const variantGroupItems=groupItems.filter(i=>i.variant_id===variantId),currentVariantTotal=variantGroupItems.reduce((sum,i)=>sum+i.quantity,0);if(!(allowedQty>=currentVariantTotal))if(variantGroupItems.length===1)updates[variantId]=Math.min(updates[variantId]??currentVariantTotal,allowedQty),cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] updates[${variantId}] = ${updates[variantId]} (single-line, allowedQty=${allowedQty} vs currentVariantTotal=${currentVariantTotal})`);else{cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] variant ${variantId} spans ${variantGroupItems.length} lines (total=${currentVariantTotal} allowed=${allowedQty}) \u2014 deferred per-key corrections`);let variantAllowedRemaining=allowedQty;for(const item of variantGroupItems){const itemAllowedQty=Math.min(item.quantity,variantAllowedRemaining);if(variantAllowedRemaining-=itemAllowedQty,itemAllowedQty<item.quantity){const keyToUpdate=item.key,newQty=itemAllowedQty;cartDebug(`enforceCartRules rule 6: entry[${entryIdx}] multi-line correction \u2014 key ${keyToUpdate} ("${item.title}") from ${item.quantity} to ${newQty}`),changes.push({id:keyToUpdate,quantity:newQty})}}}}}for(const parentVariantId of groupVariantIds){const parentVariantIdStr=String(parentVariantId),linkedExtras=items.filter(item=>item.properties?.[PRODUCT_PROPERTY_KEYS.parentVariantId]===parentVariantIdStr);if(cartDebug(`enforceCartRules rule 6: extras scan for parentVariantId=${parentVariantId} (str="${parentVariantIdStr}") \u2014 linkedExtras found: ${linkedExtras.length}`,linkedExtras.map(i=>({key:i.key,variant_id:i.variant_id,title:i.title,qty:i.quantity,_parent_variant_id:i.properties?.[PRODUCT_PROPERTY_KEYS.parentVariantId]}))),cartDebug("enforceCartRules rule 6: all cart items _parent_variant_id values:",items.map(i=>({key:i.key,variant_id:i.variant_id,_parent_variant_id:i.properties?.[PRODUCT_PROPERTY_KEYS.parentVariantId]??"(none)"}))),linkedExtras.length===0)continue;const extraTotal=linkedExtras.reduce((sum,item)=>sum+item.quantity,0),targetParentQty=allowedQtyByVariantId.has(parentVariantId)?allowedQtyByVariantId.get(parentVariantId):groupItems.filter(i=>i.variant_id===parentVariantId).reduce((sum,i)=>sum+i.quantity,0);if(cartDebug(`enforceCartRules rule 6: extraTotal=${extraTotal} targetParentQty=${targetParentQty} needsCleanup=${extraTotal>targetParentQty}`),extraTotal<=targetParentQty)continue;cartDebug(`enforceCartRules rule 6: extra items for parent variant ${parentVariantId} total ${extraTotal}, capping to ${targetParentQty}`);let extraRemaining=targetParentQty;for(const item of linkedExtras){const allowedExtraQty=Math.min(item.quantity,extraRemaining);if(extraRemaining-=allowedExtraQty,cartDebug(`enforceCartRules rule 6: extra item key=${item.key} variant=${item.variant_id} ("${item.title}") qty=${item.quantity} allowedExtraQty=${allowedExtraQty} extraRemainingAfter=${extraRemaining} needsCorrection=${allowedExtraQty<item.quantity}`),allowedExtraQty<item.quantity){const newQty=allowedExtraQty;if(messages.push(newQty===0?`Limited special offer - "${item.title}" was removed with its paired product.`:`Limited special offer - "${item.title}" quantity was reduced to ${newQty} with its paired product.`),linkedExtras.filter(i=>i.variant_id===item.variant_id).length===1)updates[item.variant_id]=Math.min(updates[item.variant_id]??item.quantity,newQty),cartDebug(`enforceCartRules rule 6: extra item updates[${item.variant_id}] = ${updates[item.variant_id]} (single-line, paired with parent ${parentVariantId})`);
8else{const keyToUpdate=item.key;cartDebug(`enforceCartRules rule 6: extra item key=${keyToUpdate} ("${item.title}") multi-line correction from ${item.quantity} to ${newQty} (paired with parent ${parentVariantId})`),changes.push({id:keyToUpdate,quantity:newQty})}}}}}}if(CART_RULES_CONFIG.RULE_7A_ENABLED){const rawDiscountCodes=cartData?.cartRaw?.discount_codes??[],completeCodes=rawDiscountCodes.map(d=>d.code).filter(code=>code&&code.startsWith(COMPLETE_REGIMEN_DISCOUNT_CODE_PREFIX));for(const code of completeCodes){const parsed=parseCompleteRegimenCode(code);if(!parsed)continue;const{regimenValue,minQuantity}=parsed,matchingCount=items.filter(item=>!isZeroDollarItem(item)&&getCompleteRegimenValue(item)===regimenValue).length;matchingCount<minQuantity&&cartDebug(`enforceCartRules rule 7: discount code "${code}" requires ${minQuantity} items with _complete_regimen="${regimenValue}", found ${matchingCount}; removing code`),messages.push(`The discount code "${code}" has been removed because the required regimen items are no longer in your cart.`);const cartToken=cartData?.cartRaw?.token;if(cartToken){const remainingCodes=rawDiscountCodes.map(d=>d.code).filter(c=>c!==code),{endpoint,storefrontToken}=getStorefrontConfig();storefrontToken?updateCartDiscountCodes(cartToken,remainingCodes,{endpoint,storefrontToken}).catch(err=>{cartDebug("enforceCartRules rule 7: failed to remove discount code",err)}):cartDebug("enforceCartRules rule 7: no storefront token found; cannot remove discount code")}else cartDebug("enforceCartRules rule 7: no cart token found; cannot remove discount code")}}return cartDebug("enforceCartRules result:",{updates,changes:changes.length,messages:messages.length}),{messages,shouldClear:!1,updates,changes}}function fetchConfig(type="json"){return{method:"POST",headers:{"Content-Type":"application/json",Accept:`application/${type}`}}}function getIsCartPage(){return window.location.pathname.includes("/cart")}function getSectionsToRender(isCartPage){const cartDrawerComponents=[{section:"header",id:"cart-drawer-wrapper",selector:".cart-items-ajax"},{section:"header",id:"cart-drawer-wrapper",selector:"#cart-drawer-toggle-ajax"},{section:"header",id:"cart-drawer-wrapper",selector:".cart-checkout-cta-ajax"},{section:"header",id:"cart-drawer-wrapper",selector:"#cart-drawer-title"},{section:"header",id:"cart-drawer-wrapper",selector:"#cart-drawer-checkout-cta"},{section:"header",id:"cart-drawer-wrapper",selector:"#cart-free-ship-drawer [data-remaining]"}],cartPageComponents=[{section:"cart-page",id:"cart-page",selector:".cart-items-ajax"},{section:"cart-page",id:"cart-page",selector:"#cart-title-mobile"},{section:"cart-page",id:"cart-page",selector:"#cart-title-desktop"},{section:"cart-page",id:"cart-page-footer",selector:".cart-checkout-cta-ajax"},{section:"cart-page",id:"cart-page",selector:"#cart-page-yotpo-rewards-ajax .yotpo-points-anon"},{section:"cart-page",id:"cart-page",selector:"#cart-page-additional-checkout-buttons-ajax"},{section:"cart-page",id:"cart-page",selector:"#cart-free-ship-mobile [data-remaining]"},{section:"cart-page",id:"cart-page",selector:"#cart-free-ship-desktop [data-remaining]"}];return[...cartDrawerComponents,...isCartPage?cartPageComponents:[]]}function getSectionInnerHTML(html,selector){return new DOMParser().parseFromString(html,"text/html").querySelector(selector)?.innerHTML}function replaceSections(sectionsToRender,resSections){sectionsToRender.forEach(section=>{const elementToReplace=document.getElementById(section.id)?.querySelector(section.selector);if(elementToReplace===null){cartDebug(`Cannot find element to replace for section: ${section.section}; id: ${section.id}; selector: ${section.selector}.  This may be fine b/c some elements shouldn't be rendered (e.g. alternate rewards display if user is logged-in or anonymous)`);return}const updatedSectionHTML=resSections[section.section];elementToReplace&&updatedSectionHTML?elementToReplace.innerHTML=getSectionInnerHTML(updatedSectionHTML,section.selector):cartDebug(`Updated section HTML not found; cannot update ${section.section}; id: ${section.id}; selector: ${section.selector}`)})}var fetchURLs={add:"/cart/add",change:"/cart/change",update:"/cart/update",clear:"/cart/clear"};function openCartDrawer(){return function(payload){if(payload?.openDrawer===!1)return;if(!getIsCartPage()){const cartDrawerToggle=document.querySelector("#cart-drawer-toggle");cartDrawerToggle&&(cartDrawerToggle.checked=!0)}}}subscribe(PUB_SUB_EVENTS.cartMutationComplete,openCartDrawer(),"openCartDrawer");function showCartRulesNotification(messages){const NOTIFICATION_ID="cart-rules-notification",PARENT_ID="cart-drawer-content";let el=document.getElementById(NOTIFICATION_ID);el||(el=document.createElement("div"),el.id=NOTIFICATION_ID,el.setAttribute("role","status"),el.style.cssText=["position:absolute","top:4.5rem","left:50%","transform:translateX(-50%)","max-width:28rem","width:calc(100% - 2rem)","min-height:5rem","background:#fef3c7","border:1px solid #f59e0b","color:#92400e","font-size:0.875rem","border-radius:0.375rem","padding:0.75rem 1rem","box-shadow:0 4px 12px rgba(0,0,0,0.12)"].join(";"),document.getElementById(PARENT_ID)?.appendChild(el)),el.innerHTML=`<button onclick="this.closest('#${NOTIFICATION_ID}').hidden=true" aria-label="Dismiss" style="position:absolute;top:0;right:0;background:none;border:none;cursor:pointer;font-size:1.5rem;line-height:0.6;color:#92400e;padding:0.5rem">&times;</button>`+messages.map(msg=>`<p style="margin:0 0 0.25rem;padding-right:1.25rem">${msg}</p>
8`).join(""),el.hidden=!1,clearTimeout(el._dismissTimer),el._dismissTimer=setTimeout(()=>{el.hidden=!0},1e4)}async function mutateCartAndPublish({onSuccess,action,payload,line=void 0,id=void 0,openDrawer=!0,redirectToCheckout=!1,redirectUrl=`${window.Shopify.routes.root}checkout`}){const isCartPage=getIsCartPage();try{publish(PUB_SUB_EVENTS.cartInFlight,PUB_SUB_PAYLOADS[PUB_SUB_EVENTS.cartInFlight]({isInFlight:!0,id,line,action}));const sectionsToRender=getSectionsToRender(isCartPage);getCartDebugState()===!0&&debugOutlineElements(sectionsToRender.map(section=>document.getElementById(section.id)?.querySelector(section.selector)),"red");const uniqueSectionArray=sectionsToRender.reduce((prev,curr)=>(prev.includes(curr.section)||prev.push(curr.section),prev),[]);cartDebug("cart fetch",action);const body=JSON.stringify({...payload,sections:uniqueSectionArray}),res=await fetch(`${fetchURLs[action]}`,{...fetchConfig(),body});if(res.status===200){const resJson=await res.json();if(resJson.errors)throw new Error(resJson.errors);if(action==="add"&&onSuccess)try{Promise.resolve(onSuccess(resJson.items||[])).catch(console.error)}catch(error){console.error(error)}let cartData;action==="add"?cartData=await getCartData(!0):cartData=shapeCartData(resJson);const{cartRaw,cartTotalPrice,cartItemVariantIds}=cartData;setCartDataLocalStorage(cartData);const{doAddGifts,doRemoveGifts}=addRemoveGwpItems(cartData),MAX_CORRECTION_CYCLES=5,allViolationMessages=[];let lastCorrectionSections=null;for(let correctionCycle=0;correctionCycle<MAX_CORRECTION_CYCLES;correctionCycle++){const{messages:ruleMessages,shouldClear,updates,changes}=enforceCartRules(cartData);allViolationMessages.push(...ruleMessages);const hasCorrections=shouldClear||Object.keys(updates).length>0||changes.length>0;if(cartDebug(`enforceCartRules correction cycle ${correctionCycle+1}: shouldClear=${shouldClear} updates=${JSON.stringify(updates)} changes=${changes.length} hasCorrections=${hasCorrections}`),!hasCorrections)break;if(shouldClear){const clearRes=await fetch(fetchURLs.clear,{...fetchConfig(),body:JSON.stringify({sections:uniqueSectionArray})});if(clearRes.status===200){const clearJson=await clearRes.json();cartData=shapeCartData(clearJson),setCartDataLocalStorage(cartData),lastCorrectionSections=clearJson.sections??null}break}if(Object.keys(updates).length>0){const updateRes=await fetch(fetchURLs.update,{...fetchConfig(),body:JSON.stringify({updates,sections:uniqueSectionArray})});if(updateRes.status===200){const updateJson=await updateRes.json();cartData=shapeCartData(updateJson),setCartDataLocalStorage(cartData),lastCorrectionSections=updateJson.sections??null}}for(const{id:changeId,quantity:changeQty}of changes){const changeRes=await fetch(fetchURLs.change,{...fetchConfig(),body:JSON.stringify({id:changeId,quantity:changeQty,sections:uniqueSectionArray})});if(changeRes.status===200){const changeJson=await changeRes.json();cartData=shapeCartData(changeJson),setCartDataLocalStorage(cartData),lastCorrectionSections=changeJson.sections??null}}correctionCycle===MAX_CORRECTION_CYCLES-1&&console.error(`[cartRules] Max correction cycles (${MAX_CORRECTION_CYCLES}) reached \u2014 suppressing further enforcement to prevent an infinite loop.`)}allViolationMessages.length>0&&showCartRulesNotification(allViolationMessages),publish(PUB_SUB_EVENTS.cartMutationComplete,PUB_SUB_PAYLOADS[PUB_SUB_EVENTS.cartMutationComplete]({cartData,openDrawer,redirectToCheckout,redirectUrl})),publish(PUB_SUB_EVENTS.cartInFlight,PUB_SUB_PAYLOADS[PUB_SUB_EVENTS.cartInFlight]({isInFlight:!1,id,line})),isCartPage&&cartData.cartRaw.item_count===0?window.location.reload():replaceSections(sectionsToRender,lastCorrectionSections??resJson.sections),redirectToCheckout&&window.location.assign(redirectUrl)}else throw res.status===422?new Error(res.statusText):new Error(res.statusText)}catch(err){console.error(err),publish(PUB_SUB_EVENTS.cartInFlight,PUB_SUB_PAYLOADS[PUB_SUB_EVENTS.cartInFlight]({isInFlight:!1,id,line})),publish(PUB_SUB_EVENTS.cartMutationError,PUB_SUB_PAYLOADS[PUB_SUB_EVENTS.cartMutationError]({message:err?.message??"Cart update failed. Please try again."}))}}var mutationInFlight=!1,queuedMutation=null;async function runMutationQueued(args){if(mutationInFlight){queuedMutation=args;return}mutationInFlight=!0,queuedMutation=null;try{await mutateCartAndPublish(args)}finally{if(mutationInFlight=!1,queuedMutation){const next=queuedMutation;queuedMutation=null,runMutationQueued(next)}}}var mutateCartDebounce=debounce(({action,payload,line,id,onSuccess})=>{runMutationQueued({onSuccess,action,payload,line,id,openDrawer:payload?.openDrawer??!0,redirectToCheckout:payload?.redirectToCheckout??!1,redirectUrl:payload?.redirectUrl??`${window.Shopify.routes.root}checkout`})},ON_CHANGE_DEBOUNCE_TIMER);async function cartAdd({onSuccess,openDrawer=!0,redirectToCheckout=!1,redirectUrl=`${window.Shopify.routes.root}checkout`,variantArray=[{id:0,quantity:0,selling_plan:null,properties:{[PRODUCT_PROPERTY_KEYS.size]:"",[PRODUCT_PROPERTY_KEYS.orderInitiatedBy]:"user"}}]}){const payload={items:variantArray.map(lineItem=>({...lineItem,properties:{...lineItem.properties,[PRODUCT_PROPERTY_KEYS.orderInitiatedBy]:lineItem.properties?.[PRODUCT_PROPERTY_KEYS.orderInitiatedBy]??"user"}})),openDrawer,redirectToCheckout,redirectUrl};mutateCartDebounce({action:"add",payload,onSuccess})}async function cartChange2({id,line,quantity,sellingPlanId,properties}){let currentProperties={};properties&&(currentProperties=await cartDataFncs.getItemPropertiesByItemKey(id));const payload={id,line,quantity,selling_plan:sellingPlanId,...properties&&{properties:{...currentProperties,...properties}}};mutateCartDebounce({action:"change",payload,line,id})}async function cartUpdate({variantQuantityMap}){mutateCartDebounce({action:"update",payload:{updates:variantQuantityMap}})}async function cartClear(){mutateCartDebounce({action:"clear",payload:null})}var cartHub={cartAdd,cartChange:cartChange2,cartUpdate,cartClear};subscribe(PUB_SUB_EVENTS.cartAddRequest,cartHub.cartAdd,"cartHub"),subscribe(PUB_SUB_EVENTS.cartChangeRequest,cartHub.cartChange,"cartHub"),subscribe(PUB_SUB_EVENTS.cartUpdateRequest,cartHub.cartUpdate,"cartHub"),subscribe(PUB_SUB_EVENTS.cartClearRequest,cartHub.cartClear,"cartHub");var MIN_AFTERPAY_CART_TOTAL=3500,MAX_AFTERPAY_CART_TOTAL=1e5,afterpayCheckTimeout=null;function checkForAfterPayTotalPrice(cartIncludesSubscription=!1){const showAfterpay=window.afterpay_cart_total_price>=MIN_AFTERPAY_CART_TOTAL&&window.afterpay_cart_total_price<=MAX_AFTERPAY_CART_TOTAL&&!cartIncludesSubscription,afterpayParentEls=document.querySelectorAll("div.afterpay-parent");
8if(afterpayParentEls.length>0){const classNameHideAfterpay="hide-afterpay";afterpayParentEls.forEach(parent=>{showAfterpay?parent.classList.remove(classNameHideAfterpay):parent.classList.add(classNameHideAfterpay)})}}function doesCartIncludeSubscription(cartRaw={items:[]}){return cartRaw.items?.some(item=>item.selling_plan_allocation!==void 0)}function debouncedCheckForAfterPayTotalPrice({cartData}){const{cartRaw}=cartData;afterpayCheckTimeout&&(clearTimeout(afterpayCheckTimeout),afterpayCheckTimeout=null),afterpayCheckTimeout=setTimeout(()=>{checkForAfterPayTotalPrice(doesCartIncludeSubscription(cartRaw))},1e3)}async function handlePageLoad(){const cartData=await getCartData();if(!cartData){cartDebug("afterpay.js: no cart data on page load");return}checkForAfterPayTotalPrice(doesCartIncludeSubscription(cartData.cartRaw))}document.addEventListener("DOMContentLoaded",()=>{handlePageLoad()}),subscribe(PUB_SUB_EVENTS.cartMutationComplete,debouncedCheckForAfterPayTotalPrice,"afterpay"),(function(){if(localStorage.getItem("muradCartDebug")!=="2"&&localStorage.getItem("muradCartDebug")!=="3")return;const CONFIG={PAID_VARIANT_ID:null,FREE_VARIANT_ID_1:null,FREE_VARIANT_ID_2:null,RULE_1_ENABLED:!0,RULE_1_SETUP_QTY:8,RULE_1_CAP:6,RULE_2_ENABLED:!0,RULE_2_SETUP_QTY:3,RULE_2_CAP:1,RULE_3_ENABLED:!0,RULE_4_ENABLED:!0,RULE_4_SETUP_QTY:6,RULE_4_CAP:10,RULE_5_ENABLED:!0,USE_INTERACTIVE_VARIANT_SELECTION:!0},LS_VARIANTS_KEY="muradCartRulesTestVariants";function loadCachedVariants(){try{const cached=JSON.parse(localStorage.getItem(LS_VARIANTS_KEY));cached&&cached.PAID_VARIANT_ID&&cached.FREE_VARIANT_ID_1&&cached.FREE_VARIANT_ID_2&&(CONFIG.PAID_VARIANT_ID=cached.PAID_VARIANT_ID,CONFIG.FREE_VARIANT_ID_1=cached.FREE_VARIANT_ID_1,CONFIG.FREE_VARIANT_ID_2=cached.FREE_VARIANT_ID_2,console.log("\u2139\uFE0F  Loaded cached variant IDs from localStorage:",{PAID_VARIANT_ID:CONFIG.PAID_VARIANT_ID,FREE_VARIANT_ID_1:CONFIG.FREE_VARIANT_ID_1,FREE_VARIANT_ID_2:CONFIG.FREE_VARIANT_ID_2}))}catch{}}function saveCachedVariants(){localStorage.setItem(LS_VARIANTS_KEY,JSON.stringify({PAID_VARIANT_ID:CONFIG.PAID_VARIANT_ID,FREE_VARIANT_ID_1:CONFIG.FREE_VARIANT_ID_1,FREE_VARIANT_ID_2:CONFIG.FREE_VARIANT_ID_2}))}function clearCachedVariants(){localStorage.removeItem(LS_VARIANTS_KEY),CONFIG.PAID_VARIANT_ID=null,CONFIG.FREE_VARIANT_ID_1=null,CONFIG.FREE_VARIANT_ID_2=null,console.log("\u{1F5D1}\uFE0F  Cached variant IDs cleared. Run selectVariantsInteractively() or set them manually.")}loadCachedVariants();const wait=ms=>new Promise(r=>setTimeout(r,ms));async function waitForCart(predicate,maxMs=5e3,intervalMs=200){const deadline=Date.now()+maxMs;let cart;do await wait(intervalMs),cart=await getCart2();while(!predicate(cart)&&Date.now()<deadline);return cart}async function getCart2(){return(await fetch("/cart.js")).json()}async function directAdd(items){return(await fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items})})).json()}async function directUpdate(updates){return(await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates})})).json()}async function clearCart(){await fetch("/cart/clear.js",{method:"POST"}),console.log("\u{1F9F9} Cart cleared.")}function logCart(cart){console.table(cart.items.map(i=>({title:i.title,variant_id:i.variant_id,key:i.key,quantity:i.quantity,original_price:i.original_price}))),console.log(`  item_count: ${cart.item_count} | total_price: ${cart.total_price} (cents)`)}function validateConfig(){const VARIANT_ID_KEYS=["PAID_VARIANT_ID","FREE_VARIANT_ID_1","FREE_VARIANT_ID_2"],missing=(CONFIG.USE_INTERACTIVE_VARIANT_SELECTION?Object.keys(CONFIG).filter(k=>!VARIANT_ID_KEYS.includes(k)):Object.keys(CONFIG)).filter(k=>CONFIG[k]===0).map(k=>k);return missing.length?(console.log("\u274C Fill in CONFIG values before running tests:",missing),!1):window.muradCartActions?.cartRefresh?!0:(console.log("\u274C window.muradCartActions not found \u2014 is this the right page/store?"),!1)}async function testRule1(){if(!CONFIG.RULE_1_ENABLED)return console.log("Rule 1 \u2014 skipped (RULE_1_ENABLED is false)"),{name:"Rule 1",skipped:!0};console.group(`Rule 1 \u2014 paid item qty capped at ${CONFIG.RULE_1_CAP}`),await clearCart(),await directAdd([{id:CONFIG.PAID_VARIANT_ID,quantity:1}]),await directUpdate({[CONFIG.PAID_VARIANT_ID]:CONFIG.RULE_1_SETUP_QTY});const before=await getCart2();console.log(`BEFORE enforcement (expect qty ${CONFIG.RULE_1_SETUP_QTY}):`),logCart(before);const beforeItem=before.items.find(i=>i.variant_id==CONFIG.PAID_VARIANT_ID);if(!beforeItem||beforeItem.quantity!==CONFIG.RULE_1_SETUP_QTY){const got=beforeItem?`qt
8y ${beforeItem.quantity}`:"item not found";return console.log(`\u23ED\uFE0F SKIP: pre-condition not met \u2014 expected paid item at qty ${CONFIG.RULE_1_SETUP_QTY}, got ${got}`),console.groupEnd(),{name:"Rule 1",skipped:!0,reason:`pre-condition: ${got}`}}window.muradCartActions.cartRefresh(),console.log("Polling for enforcement result\u2026");const after=await waitForCart(cart=>{const item2=cart.items.find(i=>i.variant_id==CONFIG.PAID_VARIANT_ID);return item2&&item2.quantity<=CONFIG.RULE_1_CAP});console.log(`AFTER enforcement (expect qty ${CONFIG.RULE_1_CAP}):`),logCart(after);const item=after.items.find(i=>i.variant_id==CONFIG.PAID_VARIANT_ID),passed=item?.quantity===CONFIG.RULE_1_CAP;return passed?console.log("\u2705 PASS"):(console.log(`\u274C FAIL: expected qty ${CONFIG.RULE_1_CAP}, got ${item?.quantity}`),console.log("BEFORE (full):",before),console.log("AFTER (full):",after)),console.assert(passed,`FAIL: expected qty ${CONFIG.RULE_1_CAP}, got ${item?.quantity}`),console.groupEnd(),{name:"Rule 1",passed}}async function testRule2(){if(!CONFIG.RULE_2_ENABLED)return console.log("Rule 2 \u2014 skipped (RULE_2_ENABLED is false)"),{name:"Rule 2",skipped:!0};console.group(`Rule 2 \u2014 zero-dollar item qty capped at ${CONFIG.RULE_2_CAP}`),await clearCart(),await directAdd([{id:CONFIG.PAID_VARIANT_ID,quantity:1},{id:CONFIG.FREE_VARIANT_ID_1,quantity:1}]),await directUpdate({[CONFIG.FREE_VARIANT_ID_1]:CONFIG.RULE_2_SETUP_QTY});const before=await getCart2();console.log(`BEFORE enforcement (expect free item qty ${CONFIG.RULE_2_SETUP_QTY}):`),logCart(before);const beforeItem=before.items.find(i=>i.variant_id==CONFIG.FREE_VARIANT_ID_1);if(!beforeItem||beforeItem.quantity!==CONFIG.RULE_2_SETUP_QTY){const got=beforeItem?`qty ${beforeItem.quantity}`:"item not found";return console.log(`\u23ED\uFE0F SKIP: pre-condition not met \u2014 expected free item at qty ${CONFIG.RULE_2_SETUP_QTY}, got ${got}`),console.groupEnd(),{name:"Rule 2",skipped:!0,reason:`pre-condition: ${got}`}}window.muradCartActions.cartRefresh(),console.log("Polling for enforcement result\u2026");const after=await waitForCart(cart=>{const item2=cart.items.find(i=>i.variant_id==CONFIG.FREE_VARIANT_ID_1);return item2&&item2.quantity<=CONFIG.RULE_2_CAP});console.log(`AFTER enforcement (expect free item qty ${CONFIG.RULE_2_CAP}):`),logCart(after);const item=after.items.find(i=>i.variant_id==CONFIG.FREE_VARIANT_ID_1),passed=item?.quantity===CONFIG.RULE_2_CAP;return passed?console.log("\u2705 PASS"):(console.log(`\u274C FAIL: expected qty ${CONFIG.RULE_2_CAP}, got ${item?.quantity}`),console.log("BEFORE (full):",before),console.log("AFTER (full):",after)),console.assert(passed,`FAIL: expected qty ${CONFIG.RULE_2_CAP}, got ${item?.quantity}`),console.groupEnd(),{name:"Rule 2",passed}}async function testRule3(){if(!CONFIG.RULE_3_ENABLED)return console.log("Rule 3 \u2014 skipped (RULE_3_ENABLED is false)"),{name:"Rule 3",skipped:!0};console.group("Rule 3 \u2014 duplicate zero-dollar variant removed"),await clearCart(),await directAdd([{id:CONFIG.PAID_VARIANT_ID,quantity:1}]),await directAdd([{id:CONFIG.FREE_VARIANT_ID_1,quantity:1,properties:{_test:"a"}}]),await directAdd([{id:CONFIG.FREE_VARIANT_ID_1,quantity:1,properties:{_test:"b"}}]);const before=await getCart2(),dupCount=before.items.filter(i=>i.variant_id==CONFIG.FREE_VARIANT_ID_1).length;if(console.log(`BEFORE enforcement (${dupCount} line item(s) for free variant \u2014 need 2 to test Rule 3):`),logCart(before),dupCount<2)return console.log("\u23ED\uFE0F SKIP: pre-condition not met \u2014 Shopify merged the two adds into one line item. This variant does not support differing properties; try a different free variant or test against a real Yotpo/Swell redemption."),console.groupEnd(),{name:"Rule 3",skipped:!0,reason:"pre-condition: Shopify merged duplicate adds into one line item"};window.muradCartActions.cartRefresh(),console.log("Polling for enforcement result\u2026");const after=await waitForCart(cart=>cart.items.filter(i=>i.variant_id==CONFIG.FREE_VARIANT_ID_1).length===1),afterCount=after.items.filter(i=>i.variant_id==CONFIG.FREE_VARIANT_ID_1).length;console.log(`AFTER enforcement (expect 1 line item for free variant, got ${afterCount}):`),logCart(after);const passed=afterCount===1;return passed?console.log("\u2705 PASS"):(console.log(`\u274C FAIL: expected 1 line item, got ${afterCount}`),console.log("BEFORE (full):",before),console.log("AFTER (full):",after)),console.assert(passed,`FAIL: expected 1 line item, got ${afterCount}`),console.groupEnd(),{name:"Rule 3",passed}}async function testRule4(){if(!CONFIG.RULE_4_ENABLED)return console.log("Rule 4 \u2014 skipped (RULE_4_ENABLED is false)"),{name:"Rule 4",skipped:!0};console.group(`Rule 4 \u2014 total zero-dollar qty capped at ${CONFIG.RULE_4_CAP}`),await clearCart(),await directAdd([{id:CONFIG.PAID_VARIANT_ID,quantity:1}]),await directAdd([{id:CONFIG.FREE_VARIANT_ID_1,quantity:1},{id:CONFIG.FREE_VARIANT_ID_2,quantity:1}]),await directUpdate({[CONFIG.FREE_VARIANT_ID_1]:CONFIG.RULE_4_SETUP_QTY,[CONFIG.FREE_VARIANT_ID_2]:CONFIG.RULE_4_SETUP_QTY});const before=await getCart2(),totalFreeBefore=before.items.filter(i=>i.original_price===0).reduce((sum,i)=>sum+i.quantity,0),expectedSetupTotal=CONFIG.RULE_4_SETUP_QTY*2;if(console.log(`BEFORE enforcement (total free qty: ${totalFreeBefore}, expect ${expectedSetupTotal}):`),logCart(before),totalFreeBefore!==expectedSetupTotal)return console.log(`\u23ED\uFE0F SKIP: pre-condition not met \u2014 expected total free qty ${expectedSetupTotal}, got ${totalFreeBefore}`),console.groupEnd(),{name:"Rule 4",skipped:!0,reason:`pre-condition: total free qty ${totalFreeBefore}`};window.muradCartActions.cartRefresh(),console.log("Polling for enforcement result\u2026");const after=await waitForCart(cart=>cart.items.filter(i=>i.original_price===0).reduce((sum,i)=>sum+i.quantity,0)<=CONFIG.RULE_4_CAP),totalFreeAfter=after.items.filter(i=>i.original_price===0).reduce((sum,i)=>sum+i.quantity,0);console.log(`AFTER enforcement (total free qty: ${totalFreeAfter}, expect <= ${CONFIG.RULE_4_CAP}):`),logCart(after);const passed=totalFreeAfter<=CONFIG.RULE_4_CAP;return passed?console.log("\u2705 PASS"):(console.log(`\u274C FAIL: total free qty ${totalFreeAfter} exceeds ${CONFIG.RULE_4_CAP}`),console.log("BEFORE (full):",before),console.log("AFTER (full):",after)),console.assert(passed,`FAIL: total free qty ${totalFreeAfter} exceeds ${CONFIG.RULE_4_CAP}`),console.groupEnd(),{name:"Rule 4",passed}}async function testRule5(){if(!CONFIG.RULE_5_ENABLED)return console.log("Rule 5 \u2014 skipped (RULE_5_ENABLED is false)"),{name:"Rule 5",skipped:!0};console.group("Rule 5 \u2014 zero-dollar-only cart is cleared"),await clearCart(),await directAdd([{id:CONFIG.FREE_VARIANT_ID_1,quantity:1}]);const before=await getCart2();if(console.log(`BEFORE enforcement (total_price: ${before.total_price}, expect 0; item_count: ${before.item_count}):`),logCart(before),before.total_price!==0||before.item_count===0){const reason=before.item_count===0?"cart is empty (free item failed to add)":`cart has non-zero total_price ${before.total_price} (item may not be zero-dollar)`;return console.log(`\u23ED\uFE0F SKIP: pre-condition not met \u2014 ${reason}`),console.groupEnd(),{name:"Rule 5",skipped:!0,reason}}window.muradCartActions.cartRefresh(),console.log("Polling for enforcement result\u2026");const after=await waitForCart(cart=>cart.item_count===0);console.log(`AFTER enforcement (item_count: ${after.item_count}, expect 0):`),logCart(after);const passed=after.item_count===0;return passed?console.log("\u2705 PASS"):(console.log(`\u274C FAIL: expected empty cart, got ${after.item_count} items`),console.log("BEFORE (full):",before),console.log("AFTER (full):",after)),console.assert(passed,`FAIL: expected empty cart, got ${after.item_count} items`),console.groupEnd(),{name:"Rule 5",passed}}async function selectVariantsInteractively(){const PROMPTS=[{key:"PAID_VARIANT_ID",instruction:"Add any PAID item (original_price > 0) to your cart now, then wait\u2026",validate:item=>item.original_price>0,errorHint:"The item added has original_price === 0. Please add a paid product."},{key:"FREE_VARIANT_ID_1",instruction:"Add a ZERO-DOLLAR item (free sample / GWP) to your cart now, then wait\u2026",validate:item=>item.original_price===0,errorHint:"The item added has original_price > 0. Please add a free/zero-dollar product."},{key:"FREE_VARIANT_ID_2",instruction:"Add a SECOND, DIFFERENT zero-dollar item to your cart now, then wait\u2026",validate:item=>item.original_price===0,errorHint:"The item added has original_price > 0. Please add a free/zero-dollar product."}];console.group("\u{1F527} Interactive variant selection"),console.log("Each step will wait up to "+9e4/1e3+` s for you to add an item.
9The cart will be cleared before the tests begin \u2014 your additions here are temporary.`);const capturedVariantIds=new Set;for(const prompt of PROMPTS){const snapshot=await getCart2(),knownIds=new Set([...snapshot.items.map(i=>String(i.variant_id)),...capturedVariantIds]);console.log(`
10\u{1F449} [${prompt.key}] ${prompt.instruction}`);const newItem=await(async()=>{const deadline=Date.now()+9e4;for(;Date.now()<deadline;){await wait(1500);const added=(await getCart2()).items.find(i=>!knownIds.has(String(i.variant_id)));if(added)return added}return null})();if(!newItem)return console.log(`\u274C Timed out waiting for ${prompt.key}. Aborting interactive selection.`),console.groupEnd(),!1;if(!prompt.validate(newItem))return console.log(`\u274C Unexpected item added for ${prompt.key}: "${newItem.title}" (original_price: ${newItem.original_price}).`,prompt.errorHint),console.groupEnd(),!1;CONFIG[prompt.key]=newItem.variant_id,capturedVariantIds.add(String(newItem.variant_id)),console.log(`  \u2705 ${prompt.key} set to ${newItem.variant_id} ("${newItem.title}")`)}return console.log(`
11All variant IDs captured:`,{PAID_VARIANT_ID:CONFIG.PAID_VARIANT_ID,FREE_VARIANT_ID_1:CONFIG.FREE_VARIANT_ID_1,FREE_VARIANT_ID_2:CONFIG.FREE_VARIANT_ID_2}),saveCachedVariants(),console.log("\u{1F4BE} Variant IDs saved to localStorage \u2014 won't need to re-select next run."),console.groupEnd(),!0}async function runAllTests(){const variantIdsDefined=CONFIG.PAID_VARIANT_ID!==null&&CONFIG.FREE_VARIANT_ID_1!==null&&CONFIG.FREE_VARIANT_ID_2!==null;if(CONFIG.USE_INTERACTIVE_VARIANT_SELECTION&&!variantIdsDefined){if(!await selectVariantsInteractively())return}else variantIdsDefined&&console.log("\u2139\uFE0F  Variant IDs already set \u2014 skipping interactive selection.");
11if(!validateConfig())return;console.group("\u{1F9EA} Cart Rules \u2014 Full Test Suite");const results=[await testRule1(),await testRule2(),await testRule3(),await testRule4(),await testRule5()].filter(Boolean);await clearCart(),console.log("Suite complete. Cart cleared.");const passed=results.filter(r=>r.passed===!0),failed=results.filter(r=>r.passed===!1),skipped=results.filter(r=>r.skipped);console.group(`\u{1F4CB} Results: ${passed.length} passed, ${failed.length} failed, ${skipped.length} skipped`),results.forEach(r=>{r.skipped?console.log(`  \u23ED\uFE0F  SKIP \u2014 ${r.name}`):r.passed?console.log(`  \u2705 PASS \u2014 ${r.name}`):console.log(`  \u274C FAIL \u2014 ${r.name}`)}),console.groupEnd(),console.groupEnd()}window._cartRulesTest={CONFIG,testRule1,testRule2,testRule3,testRule4,testRule5,runAllTests,selectVariantsInteractively,clearCachedVariants,clearCart,getCart:getCart2},console.log(["Cart rules test helpers loaded on window._cartRulesTest.","","  Option A \u2014 provide variant IDs manually:","    window._cartRulesTest.CONFIG.PAID_VARIANT_ID   = <id>","    window._cartRulesTest.CONFIG.FREE_VARIANT_ID_1 = <id>","    window._cartRulesTest.CONFIG.FREE_VARIANT_ID_2 = <id>","    window._cartRulesTest.runAllTests()","","  Option B \u2014 select variants interactively (add items to cart when prompted):","    window._cartRulesTest.CONFIG.USE_INTERACTIVE_VARIANT_SELECTION = true","    window._cartRulesTest.runAllTests()  // prompts before tests run","    // or run the selection step alone:","    window._cartRulesTest.selectVariantsInteractively()","    // IDs are cached in localStorage after selection \u2014 won't prompt again until cleared:","    window._cartRulesTest.clearCachedVariants()  // clears cache + resets CONFIG IDs","","  Run a single test: window._cartRulesTest.testRule1()","","  Tip \u2014 inspect variant IDs in the current cart:","    fetch('/cart.js').then(r=>r.json()).then(c=>console.table(c.items.map(i=>({title:i.title,variant_id:i.variant_id,original_price:i.original_price}))))"].join(`
12`))})(),window.logout=async function(){(await fetch("/account/logout/")).status===200&&(location="/account/login/?logged_out=true")},document.addEventListener("DOMContentLoaded",async function globalComponents(){const urlParams=new URLSearchParams(window.location.search);urlParams.has("disableSignup")&&urlParams.get("disableSignup")=="1"&&(document.cookie="disableSignup=1"),document.querySelectorAll("[data-login-modal]")&&document.querySelectorAll("[data-login-modal]").forEach(login=>login.addEventListener("click",()=>{window.innerWidth<1024?document.querySelector("#account-modal--mobile").checked=!0:document.querySelector("#account-modal--desktop").checked=!0,login.hasAttribute("data-create-account")?document.querySelector("#register--desktop").checked=!0:login.hasAttribute("data-sign-in")&&(document.querySelector("#register--desktop").checked=!1)})),window.location.href.includes("cart=open")&&(document.querySelector("#cart-drawer-toggle").checked=!0),handleScrollLock(),handleSwell(),handleYotpoStyles();const components={};if(document.querySelector("[data-countdown]")){const Countdown=await import("./chunk--Countdown-FJ7KFU2G.vbt.js");components.countdown=Countdown.default}if(document.querySelector("[data-gwp]")){const GWP=await import("./chunk--GWP-Y3XBQFKR.vbt.js");components.gwp=GWP.default}if(document.querySelector("[data-verify-password]")){const VerifyPassword=await import("./chunk--VerifyPassword-XPDFJKY7.vbt.js");components["verify-password"]=VerifyPassword.default}if(document.querySelector("[data-promo-bar]")){const PromoBar=await import("./chunk--PromoBar-WCNRDM6Y.vbt.js");components["promo-bar"]=PromoBar.default}if(document.querySelector("[data-ajaxinate]")){const AjaxinateComponent=await import("./chunk--Ajaxinate-5BEN7YRK.vbt.js");components.ajaxinate=AjaxinateComponent.default}ComponentConstructor(components),document.dispatchEvent(new CustomEvent("global components loaded")),this.removeEventListener("DOMContentLoaded",globalComponents)}),document.addEventListener("global components loaded",async function asyncComponents(){const components={};
12if(document.querySelector("[data-slider]")){const Slider=await import("./chunk--Slider-D6YNBQKI.vbt.js");components.slider=Slider.default}if(document.querySelector("[data-smooth-scroll]")){const SmoothScroll=await import("./chunk--SmoothScroll-A7TVKOK2.vbt.js");components["smooth-scroll"]=SmoothScroll.default}if(document.querySelector("[data-intersection-change]")){const ChangeOnIntersection=await import("./chunk--ChangeOnIntersection-LFYXFGY5.vbt.js");components["intersection-change"]=ChangeOnIntersection.default}if(document.querySelector("[data-accordion]")){const Accordion=await import("./chunk--Accordion-JHYKLMR6.vbt.js");components.accordion=Accordion.default}if(document.querySelector("[data-sticky-cta]")){const StickyCTA=await import("./chunk--StickyCTA-LYBDEVUY.vbt.js");components["sticky-cta"]=StickyCTA.default}if(document.querySelector("[data-verify-form]")){const VerifyForm=await import("./chunk--VerifyForm-V3JZYEFK.vbt.js");components["verify-form"]=VerifyForm.default}if(document.querySelector("[data-recharge-widget]")){const RechargeWidget=await import("./chunk--RechargeWidget-TZ42FF7F.vbt.js");components["recharge-widget"]=RechargeWidget.default}if(document.querySelector("[data-tabs]")){const Tabs=await import("./chunk--Tabs-XDGVW46J.vbt.js");components.tabs=Tabs.default}if(document.querySelector("[data-estimated-delivery-api]")){const EstimatedDelivery=await import("./chunk--EstimatedDelivery-KNC2XDTA.vbt.js");components["estimated-delivery-api"]=EstimatedDelivery.default}if(document.querySelector("[data-storemapper-id]")){const Storemapper=await import("./chunk--Storemapper-IN54Q57Z.vbt.js");new Storemapper.default().init()}if(document.querySelector("[data-scroll-to]")){const ScrollTo=await import("./chunk--ScrollTo-7GHXG22R.vbt.js");components["scroll-to"]=ScrollTo.default}if(document.querySelector("[data-variant]")){const Variant=await import("./chunk--Variant-JZT7VUB4.vbt.js");components.variant=Variant.default}ComponentConstructor(components),document.dispatchEvent(new CustomEvent("async components loaded")),this.removeEventListener("global components loaded",asyncComponents)}),document.addEventListener("async components loaded",async function deferredComponentListeners(){const components={};if(document.querySelector("[data-yotpo-rewards]")){const YotpoRewards=await import("./chunk--YotpoRewards-6JF6EURI.vbt.js");components["yotpo-rewards"]=[YotpoRewards.default,"url:/pages/rewards"]}if(document.querySelector("[data-searchspring]")){const Searchspring=await import("./chunk--Searchspring-FSTT2MBM.vbt.js");components.searchspring=[Searchspring.default,"mouseover","url:/collections/","url:/search"]}if(document.querySelector("[data-filters]")){const Filters=await import("./chunk--Filters-G26NZQIR.vbt.js");components.filters=Filters.default}if(document.querySelector("[data-iframe]")){const IFrame=await import("./chunk--IFrame-ULTPB7IU.vbt.js");components.iframe=[IFrame.default,"mouseover"]}if(document.querySelector("[data-range-reveal]")){const RangeReveal=await import("./chunk--RangeReveal-FNVXLKF2.vbt.js");components["range-reveal"]=RangeReveal.default}if(document.querySelector("[data-predictive-search]")){const PredictiveSearch=await import("./chunk--PredictiveSearch-25OVNKD6.vbt.js");components["predictive-search"]=[PredictiveSearch.default,"mouseover","click"]}if(document.querySelector("[data-product-form]")){const ProductForm=await import("./chunk--ProductForm-GBU44WOF.vbt.js");components["product-form"]=[ProductForm.default,"mouseover","url:/products/"]}ComponentConstructor(components),this.removeEventListener("async components loaded",deferredComponentListeners)}),document.addEventListener("deferred component listeners attached",async function asyncComponents2(){ComponentConstructor({}),document.removeEventListener("deferred component listeners attached",asyncComponents2),this.removeEventListener("async components loaded",asyncComponents2)});function handleScrollLock(){document.querySelectorAll("[data-scroll-lock]").forEach(el=>{el.addEventListener("change",function(){this.checked?document.body.setAttribute("style","overflow:hidden;"):document.body.removeAttribute("style"),el.id==="search-modal-toggle"&&document.querySelector("#search").focus(),el.id==="account-modal--mobile"&&(document.querySelector("#account-modal--mobile--content").style.height=window.innerHeight+"px")})})}function handleSwell(){const STORE_KEY="muradYotpoPoints",store=window[STORE_KEY]=window[STORE_KEY]||{balance:null,setBalance(value){typeof value!="number"||Number.isNaN(value)||(this.balance=value,updatePointNodes(value))},adjustBalance(delta){if(typeof this.balance!="number")return;const next=Math.max(this.balance+delta,0);this.setBalance(next)}},rewardTracker={active:new Map};function updatePointNodes(balance){document.querySelectorAll("[data-yotpo-points]").forEach(el=>
12{el.innerHTML=balance.toLocaleString();const wrapper=el.parentElement?.hasAttribute("data-hide-container")&&el.parentElement||el.closest("[data-hide-container]");wrapper&&(wrapper.style.removeProperty("display"),wrapper.style.removeProperty("opacity"))})}function getRewardCost(item){const costKeys=["_yotpo_redemption_points_cost","_swell_points_used","_yotpo_points_cost"];for(const key of costKeys){const raw=item?.properties?.[key];if(raw==null||raw==="")continue;const cost=parseInt(raw,10);if(!Number.isNaN(cost))return cost}return null}function getRewardIdentifier(item){return[item?.properties?._yotpo_redemption_option_id,item?.properties?._swell_reward_id,item?.key,item?.id,item?.variant_id].find(candidate=>candidate!=null)}function extractRewardMap(items=[]){const map=new Map;return items.forEach(item=>{const cost=getRewardCost(item),identifier=getRewardIdentifier(item);cost===null||identifier===void 0||map.set(String(identifier),cost)}),map}function syncRewards(nextMap,{skipAdjust=!1}={}){!skipAdjust&&typeof store.balance=="number"&&(nextMap.forEach((cost,optionId)=>{rewardTracker.active.has(optionId)||store.adjustBalance(-cost)}),rewardTracker.active.forEach((cost,optionId)=>{nextMap.has(optionId)||(store.adjustBalance(cost),typeof window.swellAPI?.removePointRedemptionIdFromCart=="function"&&window.swellAPI.removePointRedemptionIdFromCart(optionId,()=>{}))})),rewardTracker.active=nextMap}async function primeRewards(){try{const res=await fetch("/cart.js");if(!res.ok)return;const cartJson=await res.json();syncRewards(extractRewardMap(cartJson.items),{skipAdjust:!0})}catch(err){console.error(err)}}subscribe(PUB_SUB_EVENTS.cartMutationComplete,({cartData})=>{const items=cartData?.cartRaw?.items;items&&syncRewards(extractRewardMap(items))},"yotpo-reward-sync"),document.addEventListener("swell:setup",()=>{const{vipTier,pointsBalance}=window.Swell.Customer.getCustomerDetails();if(typeof pointsBalance=="number"&&store.setBalance(pointsBalance),vipTier){let tier=vipTier.name;tier||(tier="Bronze"),document.querySelectorAll("[data-yotpo-tier]").forEach(el=>{el.innerHTML=tier;const wrapper=el.closest("[data-hide-container]");wrapper&&(wrapper.style.removeProperty("display"),wrapper.style.removeProperty("opacity"))})}document.querySelector("#rewards-header")&&document.querySelector("#rewards-header").classList.remove("hidden"),primeRewards()})}function handleYotpoStyles(){new MutationObserver(function(){const yotpoTitle=document.querySelector(".yotpo-bottom-line .yotpo-bottom-line-left-panel.yotpo-bottom-line-score");yotpoTitle&&(yotpoTitle.style.fontFamily="MatterSemiMono",this.disconnect())}).observe(document.body,{childList:!0,subtree:!0})}
13//# sourceMappingURL=/cdn/shop/t/2/assets/global.vbt.js.map?v=100204466171077718831789581415

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.