1(()=>{if(customElements.get("blissy-pillowcase-builder"))return;const escape=value=>String(value??"").replace(/[&<>"']/g,char=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[char]),normalizeSearch=value=>String(value??"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/&/g," and ").replace(/[^\p{L}\p{N}]+/gu," ").trim(),colorSearchAliases={emerald:"green",matcha:"green",olive:"green",aqua:"blue turquoise",lavender:"purple",orchid:"purple",plum:"purple",blush:"pink","rose gold":"pink",burgundy:"red maroon",chocolate:"brown",bronze:"brown",taupe:"brown beige",champagne:"beige cream",silver:"grey gray",grey:"gray silver",gray:"grey silver"},searchableProduct=item=>normalizeSearch(`${item.title} ${item.color} ${colorSearchAliases[normalizeSearch(item.color)]||""}`),colorKey=value=>normalizeSearch(value).replace(/\bgray\b/g,"grey"),similarShades={grey:["ash blue","taupe"],"ash blue":["grey","matcha","aqua"],taupe:["grey","champagne","chocolate"],champagne:["taupe","white","gold"],white:["champagne","grey"],black:["grey"],blue:["aqua","emerald"],aqua:["ash blue","matcha"],green:["aqua","ash blue"],emerald:["matcha","olive","aqua"],matcha:["olive","ash blue"],olive:["matcha","taupe"],pink:["blush","rose gold","lavender"],blush:["pink","rose gold","lavender"],"rose gold":["blush","pink","champagne"],purple:["pink","burgundy"],lavender:["orchid","blush","plum"],orchid:["lavender","royal purple","pink"],plum:["royal purple","burgundy"],"royal purple":["plum","orchid"],red:["burgundy","pink"],burgundy:["plum","red"],brown:["taupe","champagne"],chocolate:["bronze","taupe"],bronze:["chocolate","gold"],gold:["champagne","bronze"],beige:["champagne","taupe","white"],cream:["champagne","white"],ivory:["champagne","white"],sage:["matcha","olive"],"sage green":["matcha","olive"],mint:["matcha","aqua"],teal:["emerald","aqua"],turquoise:["aqua","emerald"],"light blue":["ash blue","aqua"],"sky blue":["ash blue","aqua"],"baby blue":["ash blue","aqua"],navy:["blue"],"navy blue":["blue"],yellow:["gold","champagne"],orange:["bronze","gold"],coral:["pink","rose gold"]},spellingDistance=(a,b)=>{const rows=Array.from({length:a.length+1},(_,i)=>[i]);for(let j=0;j<=b.length;j++)rows[0][j]=j;for(let i=1;i<=a.length;i++)for(let j=1;j<=b.length;j++)rows[i][j]=Math.min(rows[i-1][j]+1,rows[i][j-1]+1,rows[i-1][j-1]+ +(a[i-1]!==b[j-1])),i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1]&&(rows[i][j]=Math.min(rows[i][j],rows[i-2][j-2]+1));return rows[a.length][b.length]};customElements.define("blissy-pillowcase-builder",class extends HTMLElement{connectedCallback(){if(this.controller)return;this.controller=new AbortController,this.form=this.closest("form"),this.offer=this.closest("blissy-pillowcase-offer"),this.root=this.closest(".pdp-refresh"),this.action=this.offer.querySelector("[data-pillowcase-open]"),this.current=JSON.parse(this.querySelector("[data-pillowcase-current]").textContent),this.copy=JSON.parse(this.querySelector("[data-pillowcase-copy]").textContent),this.targetCount=2,this.drafts=new Map,this.selections=[this.current,null],this.activeSlot=1,this.catalog=[],this.cartReady=!1,this.cartInitialized=!1,this.dialog=this.querySelector("dialog"),document.body.appendChild(this.dialog);const options={signal:this.controller.signal},on=(el,event,callback)=>el.addEventListener(event,callback,options);on(this.action,"click",()=>{this.working||this.open()}),on(this.root,"blissy:purchase-pricing",()=>this.sync()),on(this.form,"change",()=>queueMicrotask(()=>this.sync())),on(document,"rebuy:cart.change",event=>{if(!this.dialog.open||this.busy||!this.isOffer)return;const items=event.detail?.cart?.cart?.items;if(Array.isArray(items)){const quantities=new Map;if(items.filter(item=>item.product_type==="Pillowcase").forEach(item=>quantities.set(item.id,(quantities.get(item.id)||0)+item.quantity)),JSON.stringify([...quantities].sort((a,b)=>a[0]-b[0]))===this.cartSignature)return}clearTimeout(this.cartTimer),this.cartTimer=setTimeout(()=>this.refreshCart(),150)}),on(document,"rebuy:smartcart.show",()=>{this.dialog.open&&window.Rebuy?.SmartCart?.hide()}),this.form.addEventListener("submit",event=>{this.busy&&(event.preventDefault(),event.stopImmediatePropagation())},{...options,capture:!0}),on(this.dialog,"click",event=>{if(event.target.closest("[data-pillowcase-close]")&&this.dialog.close(),event.target.closest("[data-pillowcase-view-cart]")){this.showCart();return}const correction=event.target.closest("[data-pillowcase-spelling-choice]");if(correction?.dataset.correction){const input=this.dialog.querySelector("[data-pillowcase-search]");input.value=correction.dataset.correction,this.renderProducts(),input.focus({preventScroll:!0});return}if(event.target.closest("[data-pillowcase-clear-filters]")){["search","style","size"].forEach(name=>
1{this.dialog.querySelector(`[data-pillowcase-${name}]`).value=""}),this.syncSizeFilter(),this.renderProducts(),this.dialog.querySelector("[data-pillowcase-search]").focus({preventScroll:!0});return}if(event.target.closest("[data-pillowcase-clear]")&&!this.working){this.selections=this.selections.map(item=>item?.inCart?item:null),this.activeSlot=this.cartCount,this.error(""),this.render(),this.dialog.querySelector(".pillowcase-builder-dialog__browse").scrollTop=0,this.dialog.querySelector(`[data-pillowcase-slot="${this.activeSlot}"]`)?.focus({preventScroll:!0});return}const remove=event.target.closest("[data-pillowcase-remove]");if(remove&&!this.working){const item=this.selections[Number(remove.dataset.pillowcaseRemove)];if(item?.inCart){this.removeCartItem(item);return}this.activeSlot=Number(remove.dataset.pillowcaseRemove),this.selections[this.activeSlot]=null,this.error(""),this.render(),this.dialog.querySelector(`[data-pillowcase-slot="${this.activeSlot}"]`)?.focus({preventScroll:!0});return}const slot=event.target.closest("[data-pillowcase-slot]");slot&&!this.working&&!this.selections[Number(slot.dataset.pillowcaseSlot)]?.inCart&&(this.activeSlot=Number(slot.dataset.pillowcaseSlot),this.render());const card=event.target.closest("[data-pillowcase-choice]");card&&!this.working&&this.select(this.catalog.find(item=>item.id===Number(card.dataset.pillowcaseChoice))),event.target.closest("[data-pillowcase-repeat]")&&!this.working&&this.select(this.selections[0]),event.target.closest("[data-pillowcase-bundle-add]")&&this.addBundle(),event.target.closest("[data-pillowcase-retry]")&&!this.working&&this.open()}),on(this.dialog.querySelector("[data-pillowcase-style]"),"change",()=>{this.syncSizeFilter(),this.renderProducts()}),on(this.dialog.querySelector("[data-pillowcase-size]"),"change",()=>this.renderProducts()),on(this.dialog.querySelector("[data-pillowcase-search]"),"input",()=>this.renderProducts()),on(this.dialog,"close",()=>{document.documentElement.style.overflow=this.previousOverflow,this.sync()}),this.sync()}t(key,values={}){return Object.entries(values).reduce((text,[name,value])=>text.replaceAll(`__${name.toUpperCase()}__`,String(value)),this.copy[key]||"")}get isOffer(){return this.targetCount===4&&this.dataset.bogoEnabled==="true"}get count(){return this.selections.filter(Boolean).length}get cartCount(){return this.selections.filter(item=>item?.inCart).length}get newPicks(){return this.selections.filter(item=>item&&!item.inCart)}get working(){return this.busy||this.cartLoading||this.loading}get addLabel(){return this.cartCount===this.targetCount?this.copy.view_cart:this.cartCount?this.copy.complete:this.targetCount===2?this.copy.add_two:this.copy.add_bundle}sync(){const quantity=Number(this.form.querySelector("[data-quantity-input]")?.value)||1,target=quantity>=4&&this.dataset.bogoEnabled==="true"?4:2;this.offer.hidden=quantity<2,this.targetCount!==target&&!this.working&&(this.drafts.set(this.targetCount,this.newPicks),this.targetCount=target,this.initialDraft=this.drafts.get(target),this.selections=Array.from({length:target},(_,index)=>this.initialDraft?.[index]||(index===0&&!this.initialDraft?this.current:null)),this.activeSlot=this.selections.findIndex(item=>!item),this.cartInitialized=!1,this.cartReady=!1),this.dialog.style.setProperty("--pillowcase-slots",this.targetCount),this.offer.querySelector("[data-pillowcase-offer-title]").textContent=this.isOffer?this.copy.title:this.copy.title_two;const offerNote=this.offer.querySelector(".pillowcase-offer__note");offerNote.textContent=this.isOffer?this.copy.offer_gift:this.copy.offer_note,offerNote.classList.toggle("is-gift",this.isOffer),this.dialog.querySelector("[data-pillowcase-title]").textContent=this.isOffer?this.copy.title:this.copy.choose_two,this.dialog.querySelector("#pillowcase-builder-discount-note").textContent=this.isOffer?this.copy.footnote:this.copy.footnote_two;const pricing=this.root.blissyPurchasePricing,savings=this.isOffer?pricing?.bundleSavingsPercent:pricing?.basePriceInCents>0?Math.round((1-pricing.unitPriceInCents/pricing.basePriceInCents)*100):0;[this.offer,this.dialog].forEach(root=>root.querySelectorAll("[data-pillowcase-savings]").forEach(label=>
1{label.textContent=Number.isFinite(savings)?savings+"%":"",label.parentElement.hidden=!(savings>0)})),this.action.disabled=!!this.working||!!this.form.querySelector("[data-add-to-cart]")?.disabled,this.updateCtaSavings()}async open(){clearTimeout(this.cartTimer),this.catalog.length&&(this.dialog.querySelector("[data-pillowcase-size]").value=this.current.size,this.syncSizeFilter()),this.dialog.open||(window.Rebuy?.SmartCart?.visible&&Rebuy.SmartCart.hide(),this.previousOverflow=document.documentElement.style.overflow,this.dialog.showModal(),document.documentElement.style.overflow="hidden"),await Promise.all([this.catalog.length?Promise.resolve():this.loadCatalog(),this.refreshCart()])}async refreshCart(){return this.cartPromise?this.cartPromise:(this.cartLoading=!0,this.cartReady=!1,this.render(),this.cartPromise=(async()=>{try{const response=await fetch(this.dataset.cartUrl,{cache:"no-store",credentials:"same-origin",signal:this.controller.signal});if(!response.ok)throw new Error("Cart unavailable");const document2=new DOMParser().parseFromString(await response.text(),"text/html"),data=JSON.parse(document2.querySelector("[data-pillowcase-cart]").textContent);if(!Array.isArray(data.items))throw new Error("Invalid cart");const cartItems=[],quantities=new Map;this.cartLines=data.items,(this.isOffer?data.items:[]).forEach(({item,quantity,key})=>{quantities.set(item.id,(quantities.get(item.id)||0)+quantity);for(let i=0;i<quantity&&cartItems.length<this.targetCount;i++)cartItems.push({...item,inCart:!0,lineKey:key})});const pending=this.cartInitialized?this.newPicks:this.initialDraft||(cartItems.length?[]:[this.current]);for(this.selections=[...cartItems,...pending.slice(0,this.targetCount-cartItems.length)];this.selections.length<this.targetCount;)this.selections.push(null);const empty=this.selections.findIndex(item=>!item),signature=JSON.stringify([...quantities].sort((a,b)=>a[0]-b[0]));return this.activeSlot=empty!==-1?empty:signature===this.cartSignature&&this.activeSlot>=0&&!this.selections[this.activeSlot]?.inCart?this.activeSlot:-1,this.cartSignature=signature,this.cartInitialized=!0,this.cartReady=!0,this.error(""),!0}catch(error){return error.name!=="AbortError"&&(this.error(this.copy.cart_error),this.dialog.querySelector("[data-pillowcase-retry]").hidden=!1),!1}finally{this.cartLoading=!1,this.cartPromise=null,this.isConnected&&this.render()}})(),this.cartPromise)}showCart(){this.dialog.close(),setTimeout(()=>{window.Rebuy?.SmartCart?.status==="ready"?(Rebuy.SmartCart.show(),Rebuy.Cart?.fetchShopifyCart?.()):location.assign((window.Shopify?.routes?.root||"/")+"cart")},0)}async removeCartItem(item){if(!this.working){this.busy=!0,this.removing=!0,this.error(""),this.renderSummary(),this.sync();try{if(!await this.refreshCart())return;const line=this.cartLines.find(line2=>line2.key===item.lineKey)||this.cartLines.find(line2=>line2.item.id===item.id);if(!line)return;const update={id:line.key,quantity:Math.max(0,line.quantity-1)};if(window.Rebuy?.Cart?.changeItem)await new Promise((resolve,reject)=>Rebuy.Cart.changeItem(update,{success:resolve,error:reject}));else if(!(await fetch((window.Shopify?.routes?.root||"/")+"cart/change.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(update)})).ok)throw new Error(this.copy.remove_error);await this.refreshCart()}catch(error){this.error(typeof error?.message=="string"?error.message:this.copy.remove_error)}finally{this.busy=!1,this.removing=!1,this.render()}}}async loadCatalog(){if(!this.loading){this.loading=!0,this.dialog.querySelector("[data-pillowcase-status]").textContent=this.copy.loading,this.dialog.querySelector("[data-pillowcase-retry]").hidden=!0;try{let next=this.dataset.catalogUrl;const items=[],visited=new Set;for(;next&&!visited.has(next);){visited.add(next);const url=new URL(next,location.origin);if(url.origin!==location.origin)throw new Error("Invalid catalog URL");url.searchParams.set("section_id","pillowcase-bundle-catalog");const response=await fetch(url,{signal:this.controller.signal});if(!response.ok)throw new Error("Catalog unavailable");const document2=new DOMParser().parseFromString(await response.text(),"text/html"),data=JSON.parse(document2.querySelector("[data-pillowcase-catalog]").textContent);items.push(...data.items),next=data.next}if(this.catalog=[...new Map(items.filter(item=>item.available).map(item=>[item.id,item])).values()],!this.catalog.length)throw new Error("No eligible pillowcases");this.selections=this.selections.map(item=>item?.inCart?item:item&&this.catalog.find(choice=>choice.id===item.id)||null),this.current=this.catalog.find(item=>item.id===this.current.id)||this.current,["style","size"].forEach(name=>
1{const select=this.dialog.querySelector(`[data-pillowcase-${name}]`),previous=select.value;select.innerHTML=`<option value="">${this.copy[name]}</option>`+[...new Set(this.catalog.map(item=>item[name]))].sort().map(value=>`<option value="${escape(value)}">${escape(value)}</option>`).join(""),[...select.options].some(option=>option.value===previous)&&(select.value=previous)}),this.filtersInitialized||(this.dialog.querySelector("[data-pillowcase-size]").value=this.current.size,this.filtersInitialized=!0),this.syncSizeFilter(),this.render()}catch(error){if(error.name==="AbortError")return;this.dialog.querySelector("[data-pillowcase-status]").textContent=this.copy.catalog_error,this.dialog.querySelector("[data-pillowcase-retry]").hidden=!1}finally{this.loading=!1,this.isConnected&&this.render()}}}select(item){if(!this.cartReady||this.activeSlot<0||this.selections[this.activeSlot]?.inCart)return;const choice=item&&this.catalog.find(choice2=>choice2.id===item.id);if(!choice)return;this.selections[this.activeSlot]=choice;const nextEmpty=this.selections.findIndex(selection=>!selection);this.activeSlot=nextEmpty,this.error(""),this.render()}render(){const slots=this.dialog.querySelector("[data-pillowcase-slots]"),selectedSizes=new Set(this.selections.map(item=>item?.size).filter(Boolean)),showSizes=selectedSizes.size>1;slots.classList.toggle("has-shared-size",selectedSizes.size===1);const gift=this.dialog.querySelector("[data-pillowcase-gift]");gift.hidden=!this.isOffer,gift.classList.toggle("is-unlocked",this.count===this.targetCount),this.dialog.querySelector("[data-pillowcase-gift-status]").textContent=this.count===this.targetCount?this.copy.gift_unlocked:this.copy.gift_locked,slots.parentElement.classList.toggle("has-gift",this.isOffer),slots.innerHTML=this.selections.map((item,index)=>`<div class="pillowcase-builder-dialog__slot${item?" is-filled":""}${item?.inCart?" is-in-cart":""}${index===this.activeSlot?" is-active":""}"> 2 ${this.isOffer&&index===3?`<span class="pillowcase-builder-dialog__free">${escape(this.copy.free)}</span>`:""} 3 <button type="button" data-pillowcase-slot="${index}" class="pillowcase-builder-dialog__slot-select" aria-pressed="${index===this.activeSlot}"${this.isOffer&&index===3?' aria-describedby="pillowcase-builder-discount-note"':""} aria-label="${escape(this.t("slot_label",{count:index+1,detail:item?`${item.color}, ${item.size}. ${item.inCart?this.copy.in_cart:this.copy.change}`:this.copy.choose}))}"> 4 ${!this.isOffer||index<3?`<span class="pillowcase-builder-dialog__slot-number">${index+1}</span>`:""} 5 ${item?`<img src="${escape(item.image)}" width="46" height="46" alt=""><span>${escape(item.color)}</span>${showSizes?`<small data-pillowcase-picked-size>${escape(item.size)}</small>`:""}${item.inCart?`<small class="pillowcase-builder-dialog__in-cart-label">${escape(this.copy.in_cart)}</small>`:""}`:`<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg><span>${escape(this.copy.choose)}</span>`} 6 </button> 7 ${item?`<button type="button" class="pillowcase-builder-dialog__remove" data-pillowcase-remove="${index}" aria-label="${escape(this.t("remove_label",{color:item.color,count:index+1}))}"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="m4 4 8 8M4 12l8-8"/></svg>${escape(this.copy.remove)}</button>`:""} 8 </div>`).join("");const complete=this.count===this.targetCount&&this.activeSlot<0;this.dialog.querySelector("[data-pillowcase-step]").textContent=complete?this.copy.complete_title:this.t(this.selections[this.activeSlot]?"change_step":"choose_step",{count:this.activeSlot+1});const count=this.dialog.querySelector("[data-pillowcase-count]");count.textContent=this.cartLoading?"\u2026":`${this.count}/${this.targetCount}`,count.setAttribute("aria-label",this.cartLoading?this.copy.checking:this.t("progress",{count:this.count,total:this.targetCount}));const clear=this.dialog.querySelector("[data-pillowcase-clear]");clear.textContent=this.cartCount?this.copy.clear_picks:this.copy.clear,clear.title=this.cartCount?this.copy.clear_help:this.copy.clear,this.dialog.querySelector("[data-pillowcase-repeat]").hidden=!this.selections[0]||this.activeSlot<=0||!this.catalog.length||this.cartCount===this.targetCount,this.dialog.querySelector("[data-pillowcase-cart-note]").hidden=this.cartCount===0,this.dialog.querySelector("[data-pillowcase-complete]").hidden=!complete,this.dialog.querySelector("[data-pillowcase-complete-rewards]").hidden=!this.isOffer||!complete,this.dialog.querySelector("[data-pillowcase-complete-message]").textContent=this.cartCount===this.targetCount?this.copy.complete_cart:this.copy.complete_add,this.dialog.querySelector("[data-pillowcase-complete-help
8]").textContent=this.cartCount===this.targetCount?this.copy.complete_cart_help:this.copy.complete_help,this.dialog.querySelector("[data-pillowcase-browse-controls]").hidden=complete,this.renderProducts(),this.renderSummary(),this.sync()}syncSizeFilter(){const style=this.dialog.querySelector("[data-pillowcase-style]").value,select=this.dialog.querySelector("[data-pillowcase-size]"),previous=select.value,sizes=[...new Set(this.catalog.filter(item=>!style||item.style===style).map(item=>item.size).filter(Boolean))].sort(),visible=sizes.length>1;select.innerHTML=`<option value="">${escape(this.copy.size)}</option>`+sizes.map(size=>`<option value="${escape(size)}">${escape(size)}</option>`).join(""),select.value=visible&&sizes.includes(previous)?previous:"",select.disabled=!visible,select.closest("label").hidden=!visible,select.closest(".pillowcase-builder-dialog__filters").classList.toggle("is-size-hidden",!visible)}suggestSpelling(search,eligible){if(search.length<4||search.length>40||!eligible.length)return null;const candidates=new Map,add=value=>{const key=normalizeSearch(value);key&&!candidates.has(key)&&candidates.set(key,String(value).trim())};if(this.catalog.forEach(item=>{add(item.color),add(item.style)}),Object.keys(similarShades).forEach(add),Object.values(colorSearchAliases).forEach(aliases=>aliases.split(" ").forEach(add)),add("pillowcase"),candidates.has(search))return null;const limit=search.length>=8?2:1;let best=null,ambiguous=!1;for(const[key,label]of candidates){if(Math.abs(key.length-search.length)>limit)continue;const distance=spellingDistance(search,key);if(!distance||distance>limit||best&&distance>best.distance)continue;const terms=key.split(" "),related=Object.hasOwn(similarShades,colorKey(key))?similarShades[colorKey(key)]:[];if(!eligible.some(item=>terms.every(term=>searchableProduct(item).includes(term))||related.includes(colorKey(item.color))))continue;const score=distance*4+ +(key[0]!==search[0])+ +(key.at(-1)!==search.at(-1));!best||score<best.score?(best={key,label,distance,score},ambiguous=!1):score===best.score&&colorKey(key)!==colorKey(best.key)&&(ambiguous=!0)}return best&&!ambiguous?best.label:null}renderProducts(){if(!this.catalog.length)return;const style=this.dialog.querySelector("[data-pillowcase-style]").value,size=this.dialog.querySelector("[data-pillowcase-size]").value,search=normalizeSearch(this.dialog.querySelector("[data-pillowcase-search]").value),queryColor=colorKey(search),searchTerms=search.split(" ").filter(Boolean);this.dialog.querySelector("[data-pillowcase-clear-filters]").hidden=!style&&!size&&!search;const eligible=this.catalog.filter(item=>(!style||item.style===style)&&(!size||item.size===size)),matches=eligible.filter(item=>{if(!search)return!0;const text=searchableProduct(item);return searchTerms.every(term=>text.includes(term))});search&&matches.sort((a,b)=>+(colorKey(b.color)===queryColor)-+(colorKey(a.color)===queryColor));const matchedIds=new Set(matches.map(item=>item.id)),relatedColors=new Set(Object.hasOwn(similarShades,queryColor)?similarShades[queryColor]:[]),similar=eligible.filter(item=>!matchedIds.has(item.id)&&relatedColors.has(colorKey(item.color))),correction=matches.length||similar.length?null:this.suggestSpelling(search,eligible),spellingChoice=this.dialog.querySelector("[data-pillowcase-spelling-choice]");this.dialog.querySelector("[data-pillowcase-spelling]").hidden=!correction,spellingChoice.textContent=correction||"",spellingChoice.dataset.correction=correction||"",spellingChoice.setAttribute("aria-label",this.copy.search_for.replace("__TERM__",correction||"")),this.dialog.querySelector("[data-pillowcase-status]").textContent=matches.length?search?this.copy.search_results.replace("__MATCHES__",matches.length).replace("__SIMILAR__",similar.length):this.t("available",{count:matches.length}):similar.length?this.copy.search_related_empty:correction?this.copy.search_spelling_status.replace("__TERM__",correction):this.copy.no_matches,this.dialog.querySelector("[data-pillowcase-status]").classList.toggle("is-visually-hidden",matches.length>0||!!correction),this.dialog.querySelector("[data-pillowcase-matches-heading]").hidden=!matches.length||!similar.length,this.dialog.querySelector("[data-pillowcase-grid]").innerHTML=this.renderProductCards(matches),this.dialog.querySelector("[data-pillowcase-similar]").hidden=!similar.length,this.dialog.querySelector("[data-pillowcase-similar-grid]").innerHTML=this.renderProductCards(similar)}renderProductCards(items){return items.map(item=>{const picked=this.newPicks.filter(selection=>selection.id===item.id).length,inCart=this.selections.filter(selection=>selection?.inCart&&selection.id===item.id).length,selected=picked+inCart,detail=item.size,pickedLabel=[inCart?this.t("in_cart_count",{count:inCart}):"",picked?`${this.copy.picked}${picked>1?` \xD7${picked}`:""}
8`:""].filter(Boolean).join(" \xB7 ");return`<button type="button" class="pillowcase-builder-dialog__product${selected?" is-picked":""}" data-pillowcase-choice="${item.id}" aria-label="${escape(this.t("choose_label",{color:item.color,size:item.size,count:this.activeSlot+1}))}${selected?`. ${escape(pickedLabel)}`:""}"> 9 ${selected?`<span class="pillowcase-builder-dialog__picked" title="${escape(pickedLabel)}"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="m3 8 3 3 7-7"/></svg>${selected>1?`\xD7${selected}`:escape(this.copy.picked)}</span>`:""} 10 <img src="${escape(item.image)}" width="180" height="180" loading="lazy" alt=""><span class="pillowcase-builder-dialog__product-info"><strong>${escape(item.color)}</strong><small>${escape(detail)}</small></span></button>`}).join("")}renderSummary(){const full=this.count===this.targetCount;this.dialog.querySelectorAll("[data-pillowcase-slot], [data-pillowcase-remove], [data-pillowcase-clear], [data-pillowcase-repeat]").forEach(control=>{const index=control.dataset.pillowcaseSlot;control.disabled=!!this.working||!this.cartReady||index!==void 0&&!!this.selections[Number(index)]?.inCart||control.hasAttribute("data-pillowcase-clear")&&this.newPicks.length===0});const button=this.dialog.querySelector("[data-pillowcase-bundle-add]");button.disabled=!full||!this.catalog.length||!!this.working||!this.cartReady,button.querySelector("[data-pillowcase-add-label]").textContent=this.cartLoading?this.copy.checking:this.removing?this.copy.updating:this.busy?this.copy.adding:full?this.addLabel:this.t(this.targetCount-this.count===1?"remaining_one":"remaining_many",{count:this.targetCount-this.count}),this.updateCtaSavings();const additionNote=this.dialog.querySelector("[data-pillowcase-addition-note]");additionNote.hidden=!full||!this.cartCount||this.cartCount===this.targetCount,additionNote.textContent=this.newPicks.length===1?this.copy.adds_one:this.copy.adds_many.replace("__COUNT__",this.newPicks.length)}updateCtaSavings(){const button=this.dialog.querySelector("[data-pillowcase-bundle-add]"),label=button.querySelector("[data-pillowcase-add-savings]"),pricing=this.root.blissyPurchasePricing;let percent=0;if(this.count===this.targetCount&&this.cartCount<this.targetCount&&!this.working&&pricing?.basePriceInCents>0){const ratio=pricing.unitPriceInCents/pricing.basePriceInCents;if(this.selections.every(item=>Number.isFinite(item.price)&&item.price>0)&&Number.isFinite(ratio)&&ratio>=0&&ratio<=1){const reference=this.selections.reduce((sum,item)=>sum+Math.max(item.price,Number(item.compareAtPrice)||0),0),prices=this.selections.map(item=>Math.round(item.price*ratio)),total=prices.reduce((sum,price)=>sum+price,0)-(this.isOffer?Math.min(...prices):0);percent=Math.round((1-total/reference)*100)}}label.hidden=!percent;const text=percent?`${this.copy.save} ${percent}%`:"";label.textContent!==text&&(label.textContent=text),button.classList.toggle("has-cta-savings",!!percent)}error(message){[this.querySelector("[data-pillowcase-inline-error]"),this.dialog.querySelector("[data-pillowcase-error]")].forEach(el=>{el.textContent=message,el.hidden=!message})}async addBundle(){if(!(this.working||this.count!==this.targetCount||!this.catalog.length||!this.cartReady)){this.busy=!0,this.error(""),this.dialog.querySelector(".pillowcase-builder-dialog__browse").setAttribute("aria-busy","true"),this.renderSummary(),this.sync();try{const previousCart=this.cartSignature;if(!await this.refreshCart())return;if(this.cartCount===this.targetCount){this.showCart();return}if(this.cartSignature!==previousCart||this.count!==this.targetCount){this.error(this.copy.cart_changed),this.dialog.open||await this.open();return}const grouped=new Map;this.newPicks.forEach(item=>grouped.set(item.id,(grouped.get(item.id)||0)+1));const items=[...grouped].map(([id,quantity])=>({id,quantity})),crossSell=document.getElementById("blissy-cross-sell");if(crossSell?.dataset.selected==="true"&&Number(crossSell.dataset.variantId)&&items.push({id:Number(crossSell.dataset.variantId),quantity:Number(crossSell.dataset.qty)||1}),window.Rebuy?.Cart?.addItem)await new Promise((resolve,reject)=>
10Rebuy.Cart.addItem({items},{success:resolve,error:reject}));else{const response=await fetch((window.Shopify?.routes?.root||"/")+"cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items})}),result=await response.json();if(!response.ok)throw new Error(result.description||this.copy.add_error)}typeof window.resetCrossSellWidget=="function"&&window.resetCrossSellWidget(),this.selections=this.selections.map(item=>item?.inCart?item:null),this.cartReady=!1,this.drafts.delete(this.targetCount),this.initialDraft=null,this.showCart()}catch(error){this.error(typeof error?.message=="string"?error.message:this.copy.add_error)}finally{this.busy=!1,this.dialog.querySelector(".pillowcase-builder-dialog__browse").removeAttribute("aria-busy"),typeof window.hideAddToCartLoader=="function"&&window.hideAddToCartLoader(),this.renderSummary(),this.sync()}}}disconnectedCallback(){this.dialog?.open&&this.dialog.close(),this.dialog?.remove(),clearTimeout(this.cartTimer),this.controller?.abort(),this.controller=null}})})(); 11//# sourceMappingURL=/cdn/shop/t/593/assets/pillowcase-bundle-builder.js.map?v=175142700156435586861790135950
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.