!function(){"use strict";const t=(()=>{try{const t="kaching_local_storage_test";return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch(t){return!1}})()?window.localStorage:window.sessionStorage,n=()=>new URLSearchParams(window.location.search).get("kaching");let e;let i;const o=()=>(void 0===i&&(i="debug"===n()),i);let r;const s=async(n,e,i,o,r)=>{try{const s="kaching_visited_deal_blocks",a=t.getItem(s),c=a?JSON.parse(a):[];if(c.includes(e))return;c.push(e),t.setItem(s,JSON.stringify(c));const u=`${"https://kaching-bundles-stats-50cc8a504c1c.herokuapp.com"}/impressions`;await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shopDomain:n,dealBlockId:e,productId:i,abTestVariantId:o,sessionId:r})})}catch(s){console.error(s)}},a=async(t,n={},e=1)=>{if(Math.random()>e)return;l("sendStorefrontEvent",{name:t,data:n});const i=window.location.href;return await fetch("https://storefront-events-25baffeb7686.herokuapp.com/popup/events",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:{name:t,data:n,url:i,shop:window.Shopify.shop}})})},c=async(t,n,e,i=.1)=>{if(Math.random()>i)return;if("Failed to fetch"===n)return;if(n&&(n.includes("Cannot define multiple custom elements with the same tag name")||n.includes("Failed to execute 'define' on 'CustomElementRegistry'")||n.includes("CustomElementRegistry.define")))return;const o=window.location.href,r=window.Shopify.shop;return await fetch("https://storefront-events-25baffeb7686.herokuapp.com/bundles/errors",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({error:{filename:t,message:n,stack:e,url:o,shop:r}})})},u=()=>{const t=["kaching-bundles.js","kaching-bundles-block.js"];window.addEventListener("error",(async function(n){try{await(async n=>{const{filename:e,message:i,error:r}=n;for(const s of t)if(e.includes(s)){if(o()||I())return void l("Error",n);await c(e,i,r.stack)}})(n)}catch(e){console.error(e)}})),window.addEventListener("unhandledrejection",(async function(n){try{await(async n=>{if("object"!=typeof n.reason)return;const{message:e,stack:i}=n.reason;if(i)for(const r of t)if(i.includes(r)){if(o()||I())return void l("Unhandled rejection",n);await c(r,e,i)}})(n)}catch(e){console.error(e)}}))};function l(t,e=null){(o()||(void 0===r&&(r="dev"===n()),r))&&console.debug("[Kaching Bundles]",t,e)}const d=()=>{const t=t=>{window.dispatchEvent(new Event(t))},n=history.pushState;history.pushState=function(...e){const i=n.apply(this,e);return t("pushstate"),t("locationchange"),i};const e=history.replaceState;history.replaceState=function(...n){const i=e.apply(this,n);return t("replacestate"),t("locationchange"),i},m(window,"popstate",(()=>{t("locationchange")}))},h=(t,n,e,i=0)=>{const o=Object.getPrototypeOf(t);if(o.hasOwnProperty(n)){const r=Object.getOwnPropertyDescriptor(o,n);if(!r.configurable)return;Object.defineProperty(t,n,{configurable:!0,get:function(...t){return r.get.apply(this,t)},set:function(...t){const o=this[n];r.set.apply(this,t);const s=this[n];return"function"==typeof e&&setTimeout(e.bind(this,o,s),i),s}})}},p=(t,n=document.body)=>{try{return n.querySelector(t)}catch(e){return null}},f=(t,n=document.body)=>{try{return[...n.querySelectorAll(t)]}catch(e){return[]}},m=(t,n,e)=>t.addEventListener(n,e),w=t=>document.createElement(t),y=(t,n,e)=>t.setAttribute(n,e),_=t=>t.dataset,b=t=>{const n=p(t);if(!n)return;const e=JSON.parse(n.textContent);return l("jsonFromElement",e),e},g=(t,n)=>{let e=0,i=t;for(;i!==n&&i!==document.body;)e++,i=i.parentNode;if(i!==n)throw new Error("The specified child node is not a descendant of the parent node.");return e},v=(t,n)=>{const e=new Range;return e.setStart(t,0),e.setEnd(n,0),e.collapsed&&(e.setStart(n,0),e.setEnd(t,0)),e.commonAncestorContainer},k=(t,n,e=1/0)=>{let i=null,o=1/0;for(const r of n){const n=v(t,r),s=g(t,n);s>e||s{const t=document.currentScript;if(!t)return!1;return t.src.includes("kaching-bundles-dev")},P=(t,n={})=>{const e=window.Shopify.routes,i=(e&&e.root||"/")+t,o=new URLSearchParams;for(const[s,a]of Object.entries(n))o.append(s,a);const r=o.toString();return r?`${i}?${r}`:i},S=(t,n)=>{new MutationObserver(((e,i)=>{for(const o of e)"childList"===o.type&&o.removedNodes.forEach((e=>{e.contains(t)&&(i.disconnect(),n())}))})).observe(document.body,{childList:!0,subtree:!0})},C=[['[data-icon="gpicon-product-cartbutton"]','[data-icon="gpicon-product-quantity"]'],["gp-product-button","gp-product-quantity"],["product-form",".product-form__quantity"],['[data-pf-type="ProductATC"]','[data-pf-type="ProductQuantity"]'],[".product-form__item--submit",'label[for="Quantity-product-template"]'],[".product-single__add-to-cart",".product-single__quantity"],[".product-info__buy-buttons",".product-info__quantity-selector"],[".ProductForm__BuyButtons, .ProductForm__AddToCart",".ProductForm__QuantitySelector"],['[data-block-type="buy-buttons"]','[data-block-type="quantity-selector"]'],[".product-page--submit-action",".quantity-controls__outer"],[".product-form__payment-container",".product-form__info-item--quantity"],["[data-product-submit]",".product-quantity-input"],[".product-form--atc",".product-form--atc-qty"],[".purchase-details",".purchase-details__quantity"],[".product-single__form .payment-buttons",".product__quantity"],[".product-form--wide",".product-single__quantity"],[".product-single__add-to-cart",".product-single__quantity"],[".product-form--button-container",null],[".product-form__item--submit",".product-form__item--quantity"],[".product-detail__form__action",null],[".product__submit__buttons",null],[".buy-buttons-row",".quantity-wrapper"],[".t4s-product-form__buttons","[data-quantity-wrapper]"],[".qty-wrapper--with-payment-button",".product-qty"],[".shopify-product-form",".product-quantity-block"],[".shopify-product-form",".product-block-quantity-selector"],[".type_buy_buttons",".type_quantity_selector"],[".product-single__form .add-to-cart",".product__quantity"],[".purchase-section",".quantity.form"],[".product-form__buttons",".quantity_selector"],[".product__atc",".quantity--input"],[".product-form__payment-container",".quantity-selector"],[".ecom-product-single__add-to-cart",".ecom-product-single__quantity"],[".product-form__submit",".product__quantity"],[".product-info__add-to-cart","quantity-input"],[".yv-checkout-btn",".yv-product-quantity"],[".product-add-to-cart-container","quantity-selector"],[".product__block__buttons",".product__block__quantity"],["x-buy-button","x-quantity-input"],['[data-instant-action-type="redirect-to-cart"]','[data-instant-type="container"]:has(> .instant-quantity-input)']];class N extends Error{constructor(t){super(t),this.name="CartFetchError"}}const q="kaching_session_id",$=()=>{const n=new URL(window.location.href),e=new URLSearchParams(n.search).get("preview_kaching_session_id");e&&t.setItem(q,e)},T=()=>t.getItem(q)||V(),V=()=>{const n=x();return t.setItem(q,n),n},x=()=>"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():F(),F=()=>"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+t/4).toString(16))),A=async()=>{const t=await fetch(P("cart.js"));if(!t.ok)throw new N("Failed to fetch cart");return(await t.json()).attributes._kaching_session_id},D=async t=>{const n=new FormData;n.append("attributes[_kaching_session_id]",t);const e=await fetch(P("cart/update.js"),{method:"POST",body:n});return await e.json()},O=(t,n)=>{const e=t.slice(-1);return parseInt(e,16)%n+1};class B{constructor(t,n,e,i,o){if(l("AddToCartForm",[t]),this.t=t,this.i=n,this.o=e,this.u=i,o){this.l("properties[__kaching_session_id]").value=T()}}update(t){l("AddToCartForm#update",[this.t,t]),this.h(t.id),this.p(t.quantity),this.m(t.properties),this._(t.selling_plan)}currentVariantId(){const t=this.v("id");if(t)return Number(t.value)}h(t){const n=this.l("id");n.disabled=!1,n.value=String(t)}p(t){l("AddToCartForm#_updateQuantityInput",t);let n=null;n=this.o?this.l("quantity"):this.v("quantity"),n&&(n.disabled=!1,n.value=String(t))}m(t){var n,e;if(t.__kaching_bundles){const i=this.l("properties[__kaching_bundles]");let o=t.__kaching_bundles;const r=null==(e=null==(n=window.Shopify.theme)?void 0:n.schema_name)?void 0:e.toLowerCase();(null==r?void 0:r.startsWith("shrine pro"))&&(o=btoa(o)),i.value=o}else{const t=this.v("properties[__kaching_bundles]");null==t||t.remove()}}_(t){if(this.u)if(t){this.l("selling_plan").value=String(t)}else{const t=this.v("selling_plan");null==t||t.remove()}}l(t){return this.v(t)||this.k(t)}v(t){return p(`[name="${t}"]`,this.t)}k(t){const n=w("input");return n.type="hidden",n.name=t,this.t.prepend(n),n}}class j{constructor(t){this.storefrontApiVersion="2025-04",this.storefrontAccessToken=t}async query(t,{variables:n}={variables:{}}){var e;let i=`https://${window.Shopify.shop}/api/${this.storefrontApiVersion}/graphql.json`;const o=null==(e=t.match(/query\s+(\w+)/))?void 0:e[1];o&&(i+=`?operation_name=${o}`);const r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:t,variables:n})});let s=null;try{if(s=await r.text(),!s)throw new Error("Empty graphql response");return JSON.parse(s).data}catch(c){throw a("storefront_graphql_error",{status:r.status,body:s}),c}}}const G="$app:kaching_bundles",E="\n id\n availableForSale\n price {\n amount\n }\n compareAtPrice {\n amount\n }\n selectedOptions {\n name\n value\n }\n image {\n id\n url(transform: { maxWidth: 200, maxHeight: 200 })\n }\n unitPriceMeasurement {\n quantityUnit\n quantityValue\n referenceUnit\n referenceValue\n }\n sellingPlanAllocations(first: 100) @include(if: $includeSellingPlans) {\n nodes {\n sellingPlan {\n id\n }\n priceAdjustments {\n price {\n amount\n }\n }\n }\n }\n",M=async(t,{country:n,language:e,productIds:i,removeUnavailableVariants:o,includeSellingPlans:r})=>{const s=i.map((t=>`gid://shopify/Product/${t}`));let a=(await t.query(`\n query FetchProducts($productGIDs: [ID!]!, $includeSellingPlans: Boolean!) @inContext(country: ${n}, language: ${e}) {\n nodes(ids: $productGIDs) {\n ... on Product {\n id\n handle\n onlineStoreUrl\n availableForSale\n title\n featuredImage {\n url\n }\n options {\n name\n optionValues {\n id\n name\n swatch {\n color\n image {\n previewImage {\n url(transform: { maxWidth: 200, maxHeight: 200 })\n }\n }\n }\n }\n }\n variants(first: 250) {\n nodes {\n ${E}\n }\n }\n collections(first: 50) {\n nodes {\n id\n }\n }\n metafield: metafield(namespace: "${G}", key: "text") {\n value\n }\n metafield2: metafield(namespace: "${G}", key: "text2") {\n value\n }\n metafield3: metafield(namespace: "${G}", key: "text3") {\n value\n }\n metafield4: metafield(namespace: "${G}", key: "text4") {\n value\n }\n legacy_metafield_text: metafield(namespace: "kaching_bundles", key: "text") {\n value\n }\n legacy_metafield_text2: metafield(namespace: "kaching_bundles", key: "text2") {\n value\n }\n sellingPlanGroups(first: 100) @include(if: $includeSellingPlans) {\n nodes {\n sellingPlans(first: 100) {\n nodes {\n id\n name\n priceAdjustments {\n adjustmentValue {\n __typename\n ... on SellingPlanPercentagePriceAdjustment {\n adjustmentPercentage\n }\n ... on SellingPlanFixedAmountPriceAdjustment {\n adjustmentAmount {\n amount\n }\n }\n ... on SellingPlanFixedPriceAdjustment {\n price {\n amount\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n `,{variables:{productGIDs:s,includeSellingPlans:r}})).nodes.filter((t=>null!=t));return a=await Promise.all(a.map((n=>U(t,n)))),a.map((t=>J(t,o)))},U=async(t,n)=>{if(n.variants.nodes.length<250)return n;const e=new Set,i=[],o=[],r=async r=>{let s=!0,a=null;for(;s;){const c=await t.query(`\n query($productGID: ID!, $cursor: String, $reverse: Boolean) {\n product(id: $productGID) {\n variants(first: 250, after: $cursor, reverse: $reverse) {\n nodes {\n ${E}\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n }\n }\n `,{variables:{productGID:n.id,cursor:a,reverse:r}}),{nodes:u,pageInfo:l}=c.product.variants;for(const t of u){if(e.has(t.id)){s=!1;break}e.add(t.id),r?o.push(t):i.push(t)}l.hasNextPage||(s=!1),a=l.endCursor}};return await Promise.all([r(!1),r(!0)]),n.variants.nodes=[...i,...o.reverse()],l("fetchAllVariantsForProduct",{productId:n.id,variants:n.variants.nodes.length}),a("2048_variants",{variants:n.variants.nodes.length}),n},J=(t,n)=>{var e,i,o,r,s,a,c,u;let l=t.variants.nodes.map((({unitPriceMeasurement:t,...n})=>{var e,i,o,r;return{id:Number(n.id.split("/").pop()),availableForSale:n.availableForSale,price:Math.round(100*Number(n.price.amount)),compareAtPrice:n.compareAtPrice?Math.round(100*Number(n.compareAtPrice.amount)):null,options:n.selectedOptions.map((t=>t.value)),imageId:n.image?Number(n.image.id.split("/").pop()):null,image:(null==(e=n.image)?void 0:e.url)||null,unitPriceQuantityValue:(null==t?void 0:t.quantityValue)||null,unitPriceQuantityUnit:(null==(i=null==t?void 0:t.quantityUnit)?void 0:i.toLowerCase())||null,unitPriceReferenceValue:(null==t?void 0:t.referenceValue)||null,unitPriceReferenceUnit:(null==(o=null==t?void 0:t.referenceUnit)?void 0:o.toLowerCase())||null,sellingPlans:(null==(r=n.sellingPlanAllocations)?void 0:r.nodes.map((t=>({id:Number(t.sellingPlan.id.split("/").pop()),price:t.priceAdjustments.length>0?Math.round(100*Number(t.priceAdjustments[0].price.amount)):Math.round(100*Number(n.price.amount))}))))||[]}}));if(n){const t=l.filter((t=>t.availableForSale));t.length>0&&(l=t)}const d=t.options.map(((t,n)=>{const e=t.optionValues.map((t=>{var n,e,i,o;return{id:Number(t.id.split("/").pop()),defaultName:t.name,name:t.name,swatch:{color:(null==(n=t.swatch)?void 0:n.color)||null,image:(null==(o=null==(i=null==(e=t.swatch)?void 0:e.image)?void 0:i.previewImage)?void 0:o.url)||null}}}));return{defaultName:t.name,name:t.name,position:n+1,optionValues:R(e,n,l)}})),h=t=>{const n=t.priceAdjustments[0];if(!n)return null;const e=n.adjustmentValue;switch(e.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:e.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"fixed_amount",value:100*Number(e.adjustmentAmount.amount)};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:100*Number(e.price.amount)};default:throw new Error(`Unknown price adjustment type: ${e.__typename}`)}},p=(null==(e=t.sellingPlanGroups)?void 0:e.nodes.flatMap((t=>t.sellingPlans.nodes.map((t=>({id:Number(t.id.split("/").pop()),name:t.name,priceAdjustment:h(t)}))))))||[];return{id:Number(t.id.split("/").pop()),url:t.onlineStoreUrl,availableForSale:t.availableForSale,title:t.title,image:(null==(i=t.featuredImage)?void 0:i.url)||null,collectionIds:t.collections.nodes.map((t=>Number(t.id.split("/").pop()))),options:d,selectedVariantId:Number(t.variants.nodes[0].id.split("/").pop()),variants:l,sellingPlans:p,metafields:{text:(null==(o=t.metafield)?void 0:o.value)||null,text2:(null==(r=t.metafield2)?void 0:r.value)||null,text3:(null==(s=t.metafield3)?void 0:s.value)||null,text4:(null==(a=t.metafield4)?void 0:a.value)||null},legacyMetafields:{kaching_bundles:{text:(null==(c=t.legacy_metafield_text)?void 0:c.value)||null,text2:(null==(u=t.legacy_metafield_text2)?void 0:u.value)||null}}}},R=(t,n,e)=>t.filter((t=>e.filter((e=>e.options[n]===t.name)).length>0)),Q=t=>{const n=t.options.map(((t,n)=>({defaultName:t.name,position:n+1,optionValues:t.optionValues.map((t=>({id:Number(t.id.split("/").pop()),defaultName:t.name})))})));return{id:Number(t.id.split("/").pop()),options:n}},L=async(t,n,e=200)=>(await t.query("\n query FetchMediaImages($mediaImageIds: [ID!]!, $size: Int!) {\n nodes(ids: $mediaImageIds) {\n ... on MediaImage {\n id\n image {\n url(transform: { maxWidth: $size, maxHeight: $size })\n }\n }\n }\n }\n ",{variables:{mediaImageIds:n,size:e}})).nodes.filter(Boolean).map((t=>({gid:t.id,url:t.image.url}))),z=async t=>{var n;const e=null==(n=(await t.query(`\n query FetchDealBlocks {\n shop {\n metafield(namespace: "${G}", key: "deal_blocks") {\n value\n }\n }\n }\n `)).shop.metafield)?void 0:n.value;return e?JSON.parse(e):[]},K=async(t,n)=>{const e=n.dealBars.map((t=>t.mediaImageGID)).filter((t=>null!=t)).filter((t=>!t.includes("placeholder")));if(!e.length)return[];let i=300;"d1b96b-5.myshopify.com"===window.Shopify.shop&&(i=1200);return await L(t,e,i)},H=async(t,n)=>{const e=n.dealBars.map((({freeGifts:t})=>(t||[]).map((t=>t.mediaImageGID)))).reduce(((t,n)=>t.concat(n)),[]).filter((t=>null!=t)).filter((t=>!t.includes("placeholder")));if(!e.length)return[];return await L(t,e,300)},W=async(t,n)=>{const e=n.dealBars.map((({upsells:t})=>(t||[]).map((t=>t.mediaImageGID)))).reduce(((t,n)=>t.concat(n)),[]).filter((t=>null!=t));if(!e.length)return[];return await L(t,e,300)},X=async(t,n)=>{if(!n.swatchOptions)return[];const e=n.swatchOptions.reduce(((t,n)=>[...t,...n.images.map((t=>t.mediaImageGID)).filter((t=>null!=t))]),[]);if(!e.length)return[];return await L(t,e,300)},Z=async(t,n)=>{if(!n.collectionBreaksEnabled||!n.collectionBreaks)return[];const e=n.collectionBreaks.mediaImageGID;if(!e)return[];return await L(t,[e],300)},Y=async(t,n,e)=>{var i;if(!t)return;if(0===n.length)return;const o=tt(e);if(0===o.length)return;const r=n.map((t=>t.id)),s=null==(i=o.find((t=>t.localization)))?void 0:i.localization,a=new j(t);try{const t=await(async(t,n,e)=>{const i=n.map((t=>`gid://shopify/Product/${t}`));let o="";return e&&(o=`@inContext(country: ${e.country}, language: ${e.language})`),(await t.query(`\n query FetchProductsInDefaultLanguage($productGIDs: [ID!]!) ${o} {\n nodes(ids: $productGIDs) {\n ... on Product {\n id\n options {\n name\n optionValues {\n id\n name\n }\n }\n }\n }\n localization {\n country {\n isoCode\n }\n language {\n isoCode\n }\n }\n }\n `,{variables:{productGIDs:i}})).nodes.filter((t=>null!=t)).map(Q)})(a,r,s);for(const e of n){const n=t.find((t=>t.id===e.id));n&&nt(e,n)}}catch(c){console.error("[Kaching Bundles] Failed to fetch swatches",c),setTimeout((()=>{throw c}),0)}},tt=t=>t.map((t=>t.swatchOptions||[])).reduce(((t,n)=>t.concat(n)),[]).filter((t=>null!=t)).filter((t=>"default"!==t.swatchType)),nt=(t,n)=>{for(const e of n.options){const n=t.options.find((t=>t.position===e.position));if(n){n.defaultName=e.defaultName;for(const t of e.optionValues){const e=n.optionValues.find((n=>n.id===t.id));e&&(e.defaultName=t.defaultName)}}}},et=window;class it{constructor(t,n,e,i,o,r,s,a,c){this.I=[],this.P=!1,l("DealBlock",{dealBlockElement:t,cartForm:n,addToCartButton:e,quantityInput:i,variantPicker:o,globalConfig:r,translations:s,dealBlockSettings:a,product:c}),this.S=t,this.t=n,this.C=e,this.N=i,this.q=o,this.$=r,this.T=s,this.V=a,this.i=c,this.F=this.i.selectedVariantId||this.i.variants[0].id,this.A=n&&new B(n,c,!i,!!a.subscriptionsEnabled||a.dealBars.some((t=>"subscription"===t.dealBarType)),!!a.abTestVariantNumber),this.D()}replaceVariantPicker(t){this.q=t}replaceAddToCartButton(t){this.C=t,this.O()}replaceQuantityInput(t){this.N=t,this.B()}D(){y(this.S,"config",JSON.stringify(this.$)),y(this.S,"translations",JSON.stringify(this.T)),y(this.S,"deal-block",JSON.stringify(this.V)),y(this.S,"product",JSON.stringify(this.i)),y(this.S,"current-variant-id",String(this.F)),this.j(),this.G(),this.M(),this.t&&this.U()}async j(){if(!this.$.storefrontAccessToken)return;const t=new j(this.$.storefrontAccessToken),n=await(async(t,n)=>{const[e,i,o,r,s]=await Promise.all([K(t,n),H(t,n),W(t,n),X(t,n),Z(t,n)]);return[...e,...i,...o,...r,...s]})(t,this.V);y(this.S,"media-images",JSON.stringify(n))}async G(){if(!this.$.storefrontAccessToken)return;const t=this.V.dealBars.flatMap((({freeGifts:t})=>t?t.map((t=>t.productGID)):[])).filter((t=>null!=t)),n=this.V.dealBars.flatMap((({upsells:t})=>t?t.map((t=>t.productGID)):[])).filter((t=>null!=t)),e=this.V.dealBars.flatMap((({bundleProducts:t})=>t?t.map((t=>t.productGID)):[])).filter((t=>null!=t)).filter((t=>"default"!==t)),i=Array.from(new Set([...t,...n,...e]));if(!i.length)return;const o=new j(this.$.storefrontAccessToken),r=await M(o,{country:window.Shopify.country,language:window.Shopify.locale.split("-")[0].toUpperCase(),productIds:i.map((t=>Number(t.split("/").pop()))),removeUnavailableVariants:!0,includeSellingPlans:this.$.accessScopes.includes("unauthenticated_read_selling_plans")});if(await Y(this.$.storefrontAccessToken,r,[this.V]),!this.$.featureFlags.discount_function_v4)for(const s of r)for(const t of s.sellingPlans)t.priceAdjustment=null;y(this.S,"other-products",JSON.stringify(r))}async M(){if(!this.$.storefrontAccessToken)return;const{collectionBreaksEnabled:t,collectionBreaks:n}=this.V;if(!t||!n)return;const e=(n.excludedProducts||[]).map((({id:t})=>t)),i=(n.selectedProducts||[]).map((({id:t})=>t)),o=(n.selectedCollections||[]).map((({id:t})=>t)),r=new j(this.$.storefrontAccessToken);let s=await(async(t,{country:n,language:e,blockVisibility:i,excludedProductGIDs:o,selectedProductGIDs:r,selectedCollectionGIDs:s})=>{const a=250;switch(i){case"selected-products":return r.slice(0,a);case"all-products":case"excluded-products":{let r=(await t.query(`\n query FetchProductGIDs($limit: Int!) @inContext(country: ${n}, language: ${e}) {\n products(first: $limit) {\n nodes {\n id\n }\n }\n }\n `,{variables:{limit:a}})).products.nodes.map((t=>t.id));return"excluded-products"===i&&(r=r.filter((t=>!o.includes(t)))),r}case"selected-collections":return(await t.query("\n query FetchCollectionProductGIDs($collectionGIDs: [ID!]!, $limit: Int!) {\n nodes(ids: $collectionGIDs) {\n ... on Collection {\n products(first: $limit) {\n nodes {\n id\n }\n }\n }\n }\n }\n ",{variables:{collectionGIDs:s,limit:a}})).nodes.flatMap((t=>t.products.nodes.map((t=>t.id)))).splice(0,a)}})(r,{country:window.Shopify.country,language:window.Shopify.locale.split("-")[0].toUpperCase(),blockVisibility:n.visibility,excludedProductGIDs:e,selectedProductGIDs:i,selectedCollectionGIDs:o});s=s.slice(0,250);const a=(c=50,s.reduce(((t,n,e)=>{const i=Math.floor(e/c);return t[i]||(t[i]=[]),t[i].push(n),t}),[]));var c;let u=(await Promise.all(a.map((t=>M(r,{country:window.Shopify.country,language:window.Shopify.locale.split("-")[0].toUpperCase(),productIds:t.map((t=>Number(t.split("/").pop()))),removeUnavailableVariants:!1,includeSellingPlans:this.$.accessScopes.includes("unauthenticated_read_selling_plans")}))))).flat();if(u=u.filter((t=>t.availableForSale)),await Y(this.$.storefrontAccessToken,u,[this.V]),!this.$.featureFlags.discount_function_v4)for(const l of u)for(const t of l.sellingPlans)t.priceAdjustment=null;y(this.S,"collection-breaks-products",JSON.stringify(u)),setTimeout((()=>{this.J(u)}),1e3)}J(t){for(const n of t){const t=n.variants[0].image||n.image;if(t){(new Image).src=t}}}U(){if(this.R(),this.L(),this.K(),this.B(),this.H(),this.W(),!window.kachingBundlesDisableAddToCartHandling){this.O();try{this.X()}catch(t){console.error(t)}}}X(){m(document.body,"kaching-unavailable-option-value-selected",(t=>{const{swatch:n}=t.detail;a("unavailable-option-value-selected-3",{swatch:n})}))}R(){d(),m(et,"locationchange",(()=>{const t=new URLSearchParams(et.location.search).get("variant");t&&this.Z(Number(t))}))}L(){const t=p('input[name="id"]',this.t);t&&h(t,"value",((t,n)=>{l("_listenForVariantIdInputChange",[t,n]),t!==n&&n&&this.Z(Number(n))}))}K(){const t=p('select[name="id"]',this.t);if(!t)return;let n;window.setInterval((()=>{const e=t.value;n!==e&&e&&(l("_listenForVariantIdSelectChange",[n,e]),n=e,this.Z(Number(e)))}),100)}Z(t){if(l("handleNativeVariantChange",{variantId:t,currentVariantId:this.F}),t!=this.F&&this.i.variants.find((n=>n.id==t))){if(this.$.featureFlags.remove_variant_change_delay&&window.kachingBundlesCurrentVariantChangeInProgress||(this.F=t),this.$.featureFlags.remove_variant_change_delay){if(window.kachingBundlesCurrentVariantChangeInProgress)return void l("handleNativeVariantChange","skipping")}else if(this.S.dataset.nativeVariantChangeInProgress||window.kachingBundlesCurrentVariantChangeInProgress)return void l("handleNativeVariantChange","skipping");this.S.dataset.nativeVariantChangeInProgress="true",setTimeout((()=>{delete this.S.dataset.nativeVariantChangeInProgress}),this.$.featureFlags.remove_variant_change_delay?1e3:500),y(this.S,"current-variant-id",String(t))}}B(){this.N&&(m(this.N,"change",(()=>{const t=Number(this.N.value);l("_listenForQuantityInputChange change",t),this.Y(t)})),h(this.N,"value",((t,n)=>{t!==n&&(l("_listenForQuantityInputChange observe",[t,n]),this.Y(Number(n)))})))}Y(t){window.kachingBundlesQuantityChangeInProgress||(!this.$.keepQuantityInput||window.kachingBundlesCurrentVariantChangeInProgress||this.S.dataset.nativeVariantChangeInProgress?this.tt():this.$.keepQuantityInput&&y(this.S,"quantity",String(t)))}tt(){if(!this.N||0===this.I.length)return;if(window.kachingBundlesDisableAddToCartHandling&&!this.$.keepQuantityInput)return;window.kachingBundlesQuantityChangeInProgress=!0;const t=this.I.filter((t=>this.nt(t))),n=(t.find((({id:t})=>t==this.F))||t[0]).quantity;l("_updateQuantityInput",n),this.N.value=String(n),"119a01-bf.myshopify.com"===window.Shopify.shop&&this.N.dispatchEvent(new Event("input",{bubbles:!0})),this.N.dispatchEvent(new Event("change",{bubbles:!0})),setTimeout((()=>{delete window.kachingBundlesQuantityChangeInProgress}),100)}H(){this.q&&m(this.S,"variant-selected",(t=>{const{variantId:n}=t.detail;l("listenForBlockVariantSelect",n),this.et(n)}))}W(){m(this.S,"variants-changed",(t=>{var n;clearTimeout(this.it);const{discountedPrice:e,fullPrice:i,preselected:o}=t.detail;this.I=this.S.items(),l("listenForBlockVariantsChange",{items:this.I,discountedPrice:e,preselected:o});const r=this.I.filter((t=>this.nt(t))),s=r.find((t=>t.id==this.F))||r[0];this.et(s.id),this.A.update(s),this.tt(),null==(n=this.C)||n.updatePrice(e),o&&setTimeout((()=>{var t;return null==(t=this.C)?void 0:t.updatePrice(e)}),300),this.ot(),o&&(this.it=setTimeout((()=>{this.tt(),delete this.it}),1e3)),setTimeout((()=>{for(const t of this.I)if(t.properties.__kaching_bundles){const n=JSON.parse(t.properties.__kaching_bundles);n.bxgy&&a("bxgy_item",{property:n})}})),this.rt(e,i),this.st()}))}rt(t,n){if(this.$.featureFlags.update_native_price){if(t.amount>0){const n=f(".price--large .price__regular .price-item--regular, .price--large .price__sale .price-item--sale");for(const e of n)e.innerHTML=t.formatted}if(n.amount>0){const t=p(".price--large .price__sale .price-item--regular");t&&(t.innerHTML=n.formatted)}if(t.amount>0&&n.amount>0){const e=p(".price--large .price__badge-sale");if(e){const i=Math.round((n.amount-t.amount)/n.amount*100);e.innerHTML=e.innerHTML.replace(/\d+%/,`${i}%`)}}}}st(){var t,n,e,i;l("reconvertPrices");try{(null==(t=window.bucksCC)?void 0:t.reConvert)&&window.bucksCC.reConvert(),(null==(n=window.baCurr)?void 0:n.refreshConversion)&&window.baCurr.refreshConversion(),(null==(e=window.DoublyGlobalCurrency)?void 0:e.convertAll)&&window.DoublyGlobalCurrency.convertAll(),(null==(i=window.conversionBearAutoCurrencyConverter)?void 0:i.convertPricesOnPage)&&window.conversionBearAutoCurrencyConverter.convertPricesOnPage(),window.mlvedaload&&window.mlvedaload()}catch(o){console.error(o)}}et(t){const n=this.i.variants.find((n=>n.id==t));if(l("_changeCurrentVariant",{variantId:t,currentVariantId:this.F}),this.F==t)return;if(this.F=t,!this.q)return;(!this.$.featureFlags.remove_variant_change_delay||!this.S.dataset.nativeVariantChangeInProgress)&&(clearTimeout(window.kachingBundlesCurrentVariantChangeInProgress),window.kachingBundlesCurrentVariantChangeInProgress=setTimeout((()=>{delete window.kachingBundlesCurrentVariantChangeInProgress}),1e3));for(const[e,i]of n.options.entries()){const t=this.i.options[e],o=t.name,r=t.optionValues.find((t=>t.name===i)).id;this.q.select(e+1,r,o,i,this.i.id,n.id)}}O(){if(!this.C)return;this.C.onClickIfConditionMet((()=>!window.kachingBundlesDisableAddToCartHandling&&(!!this.V.skipCart||(!!this.ct()||(!!this.ut()||this.I.length>1)))),(async()=>{if(this.V.skipCart)return await this.lt(),window.kachingCartApi&&(l("Kaching Cart update tiered promotions bar"),await window.kachingCartApi.updateTieredPromotionsBar()),void(window.location.href=P("checkout"));if(this.ct()){try{window.upcartOpenCart&&window.upcartOpenCart()}catch(t){console.error("upcartOpenCart error",t)}return await this.lt(),void(window.upcartRefreshCart&&window.upcartRefreshCart())}if(this.ut()){try{window.opusOpen&&window.opusOpen()}catch(t){console.error("opusOpen error",t)}return await this.lt(),void(window.opusRefreshCart&&window.opusRefreshCart())}return this.dt()}),(()=>this.V.skipCart||this.ct()||this.ut())),this.ht(),this.ft()}ht(){window.upcartShouldSkipAddToCartInterceptor=!0;const t=window.upcartShouldSkipAddToCart;window.upcartShouldSkipAddToCart=n=>{if("function"==typeof t){if(!0===t(n))return!0}return n.includes("kaching_bundles=true")}}ft(){["the-gloria-skincare.myshopify.com","xzxihx-8t.myshopify.com","e76602-61.myshopify.com"].includes(window.Shopify.shop)&&(window.OpusNoATC=!0)}ct(){return!!p("#UpcartPopup")||!!window.upcartDocumentOrShadowRoot}ut(){return window.opusActive&&a("opus_cart"),["the-gloria-skincare.myshopify.com","xzxihx-8t.myshopify.com","e76602-61.myshopify.com"].includes(window.Shopify.shop)&&window.opusActive||!1}async dt(){l("addItemsExceptCurrentToCart",this.I);const t=this.A.currentVariantId();setTimeout((()=>{t!=this.F&&a("different_current_variant_v3",{form:t,object:this.F})}));const n=this.I.findIndex((n=>this.nt(n)&&n.id==t)),e=this.I.filter(((t,e)=>e!==n));await this.wt({items:e,partial:!0})}async lt(){l("addAllItemsToCart",this.I);let t=this.I;0===t.length&&(t=[{id:this.A.currentVariantId(),quantity:1,properties:{}}]),await this.wt({items:t})}yt(){const t=f('[name^="properties"]').map((t=>[t.name.match(/properties\[(.*)\]/)[1],t.value])).filter((([t])=>"__kaching_bundles"!==t));return Object.fromEntries(t)}nt(t){const n=this._t(t);return!n||(n.main||!1)}_t(t){if(!t.properties.__kaching_bundles)return null;return JSON.parse(t.properties.__kaching_bundles)}async wt({items:t,partial:n=!1}){const e=this.yt(),i=t.map((t=>{var n;return this.nt(t)||(null==(n=this._t(t))?void 0:n.collectionBreaksProduct)?{...t,properties:{...e,...t.properties}}:t}));setTimeout((()=>this.bt(e)));const o={kaching_bundles:"true"};n&&(o.partial="true");const r={"Content-Type":"application/json"};n||(r["X-Kaching-Cart-Ignore"]="1"),await fetch(P("cart/add.js",o),{method:"POST",body:JSON.stringify({items:i}),headers:r})}bt(t){if(!this.V.collectionBreaksEnabled)return;const n=Object.fromEntries(Object.entries(t).filter((([t])=>!t.startsWith("__kaching_"))));0!==Object.keys(n).length&&a("collection_break_properties",{properties:n})}ot(){const t="kaching-bundles-form--different-variants-selected";this.I.length>1?this.t.classList.add(t):this.t.classList.remove(t)}}class ot{static find(t,n){let e=t.parentElement;for(;e;){if(n){const t=f(n,e);if(t.length>0)return new ot(t)}const t=p(["variant-selects","variant-radios","variant-picker","product-variants","gp-product-variants",".gf_variants-wrapper",'[data-pf-type="ProductVariantSwatches"]',".product-selectors",".product-block-variant-picker","dm-variant-selects"].join(", "),e);if(t)return new ot([t]);let i=f([".selector-wrapper",".radio-wrapper",".variant-wrapper","div[data-product-option]",".pp-variant-picker"].join(", "),e);if(["28212b.myshopify.com","9bd9ad.myshopify.com"].includes(window.Shopify.shop)&&(i=f(".selector-wrapper, .radio-wrapper, .variant-wrapper, .select-wrapper, div[data-product-option]",e)),i.length>0){const t=i.filter((t=>!i.some((n=>n!==t&&n.contains(t)))));return new ot(t)}e=e.parentElement}return null}constructor(t){this.gt=t}elements(){return this.gt}hide(){for(const t of this.gt)t.style.display="none",t.parentElement.classList.add("kaching-bundles--variant-selects-hidden")}select(t,n,e,i,o,r){l("VariantPicker#select",[t,n,e,i]),this.vt(t,n,e,i,o)||this.kt(t,e,i)||this.It(r)}vt(t,n,e,i,o){const r=this.gt.map((t=>[...t.querySelectorAll("input")])).flat();let s=r.filter((n=>[e,`${e}-${t}`,`options[${e}]`,`option${t}`,`option-${o}-${t-1}`].includes(n.name.trim())));s.length||(s=r.filter((n=>!!n.dataset.optionPosition&&Number(n.dataset.optionPosition)===t))),s.length||(s=r.filter((t=>"radio"===t.type)));const a=s.find((t=>t.value==i||t.value===String(n)));return!!a&&(l("VariantPicker#_clickRadioInput",a),a.click(),!0)}kt(t,n,e){const i=this.gt.map((t=>[...t.querySelectorAll("select")])).flat().find((e=>!![`options[${n}]`,`option${t}`].includes(e.name)||(e.dataset.index===`option${t}`||(e.dataset.optionName===n||(e.id==="SingleOptionSelector-product-"+(t-1)||e.id===`p-variant-dropdown-${t}`)))));if(!i)return!1;return!![...i.options].find((t=>t.value==e))&&(i.value===e?(l("VariantPicker#_setSelectValue - already set",{variantSelect:i,optionValue:e}),!0):(l("VariantPicker#_setSelectValue",{variantSelect:i,optionValue:e}),i.value=e,i.dispatchEvent(new Event("change",{bubbles:!0})),!0))}It(t){const n=this.gt.map((t=>[...t.querySelectorAll("select")])).flat().find((n=>[...n.options].find((n=>Number(n.value)===t))));return!!n&&(n.value===String(t)?(l("VariantPicker#_setSelectVariantId - already set",{variantSelect:n,variantId:t}),!0):(l("VariantPicker#_setSelectVariantId",{variantSelect:n,variantId:t}),n.value=String(t),n.dispatchEvent(new Event("change",{bubbles:!0})),!0))}}class rt{constructor(t){var n;this.Pt=!1,this.St=!1,this.element=t;try{if(!this.Ct(this.element))return;a("add-to-cart-button-price-4",{theme:null==(n=window.Shopify.theme)?void 0:n.schema_name})}catch(e){console.error(e)}}onClickIfConditionMet(t,n,e){this.element.addEventListener("click",(async i=>{const o=t(),r=e();l("AddToCartButton#interceptClick",{conditionMet:o,preventDefault:r,submitInProgress:this.Pt,ignoreClick:this.St}),o&&(this.Pt?this.Pt=!1:this.St||(this.Pt=!0,this.St=!0,this.element.disabled=!0,setTimeout((()=>{this.St=!1}),1e3),i.preventDefault(),i.stopPropagation(),i.stopImmediatePropagation(),await n(),this.element.disabled=!1,r?this.Pt=!1:(await new Promise((t=>setTimeout(t,200))),this.element.click())))}),!0)}updatePrice(t){const n=this.Ct(this.element);n&&(n.innerHTML=t.amount>0?t.formatted:"")}Ct(t){if(!t.childNodes.length)return null;const n=t.childNodes[0].nodeValue;if(n&&n.match(/\d/)&&!n.match(/[a-zA-Z]{4}/)&&!n.includes("%"))return t;for(const e of t.childNodes){const t=this.Ct(e);if(t)return t}return null}}let st,at,ct=null,ut=[];const lt=async()=>{if(ct)return ct;ct=(async()=>{if(!st.storefrontAccessToken)return;const t=new j(st.storefrontAccessToken);at=await z(t)})();try{await ct}catch(t){throw ct=null,t}},dt=async t=>{var n,e;await lt();const i=at.filter((n=>n.id===t||n.nanoId===t)).find((t=>{if(!t.abTestVariantId)return!0;const n=T(),e=O(n,t.abTestVariantsCount);return t.abTestVariantNumber===e}));if(!i)return null;const o=null==(n=ut.find((t=>t.locale===st.locale)))?void 0:n.translations,r=(null==o?void 0:o.dealBlocks[i.id])||{},s=t=>({id:t.id,title:r[t.title]||t.title,mediaImageGID:t.mediaImageGID,freeGifts:ht(t.freeGifts),upsells:pt(t.upsells),dealBarType:"quantity-break",quantity:Number(t.quantity)}),a=t=>({id:t.id,title:r[t.title]||t.title,mediaImageGID:t.mediaImageGID,freeGifts:ht(t.freeGifts),upsells:pt(t.upsells),dealBarType:"bxgy",buyQuantity:Number(t.buyQuantity),getQuantity:Number(t.getQuantity)}),c=t=>({id:t.id,title:r[t.title]||t.title,mediaImageGID:t.mediaImageGID,freeGifts:ht(t.freeGifts),upsells:pt(t.upsells),dealBarType:"bundle",bundleProducts:u(t.bundleProducts)}),u=t=>t.map((t=>({id:t.id,productGID:ft(t.productGID),variantGID:t.variantGID?ft(t.variantGID):null,quantity:Number(t.quantity)})));return{collectionBreaksEnabled:null!=(e=i.collectionBreaksEnabled)&&e,differentVariantsEnabled:i.differentVariantsEnabled,dealBars:i.dealBars.map((t=>{switch(t.dealBarType){case void 0:case"quantity-break":return s(t);case"bxgy":return a(t);case"bundle":return c(t);default:return null}})).filter((t=>null!==t))}},ht=t=>{if(!t)return[];return t.filter((t=>t.productGID)).map((t=>({id:t.id,productGID:ft(t.productGID),variantGID:t.variantGID?ft(t.variantGID):null,quantity:Number(t.quantity)})))},pt=t=>{if(!t)return[];return t.filter((t=>t.productGID)).map((t=>({id:t.id,productGID:ft(t.productGID),variantGID:t.variantGID?ft(t.variantGID):null,quantity:Number(t.quantity)})))},ft=t=>Number(t.split("/").pop()),mt=['[data-pf-type^="ProductATC"]',"button.gp-button-atc","gp-product-button button","x-buy-button",'button[type="submit"]','input[type="submit"]'],wt=['form[action*="/cart/add"]',"form[data-instant-form-product-url]"],yt=()=>{"visualPreviewInitialLoad"!==new URLSearchParams(window.location.search).get("source")&&console.log('%c❗ [Kaching Bundles] Please add "Add to cart" button to the page template',"color: white; font-weight: bold; background: linear-gradient(90deg, #8181d7, #93e9e5); padding: 5px 8px; border-radius: 3px;")};class _t{constructor(t,n,e,i,o){this.N=null,this.q=null,this.C=null;const r={...n};r.moneyFormat=this.Nt(n.moneyFormat,i.showPricesWithoutDecimals),r.currencyRate=this.qt(n.currencyRate,i.currency),this.$=r,this.T=e,this.V=i,t.innerHTML='',_(t).initialized="true",this.S=p("kaching-bundles-block",t),this.t=this.$t(),this.Tt(),this.Vt(),this.xt(),this.Ft(),this.At(),this.Dt(),this.Ot(),this.Bt=new it(this.S,this.t,this.C,this.N,this.q,this.$,e,i,o)}Nt(t,n){return n?t.includes("amount_no_decimals")?t:t.replace(/\{\{.+\}\}/g,"{{ amount_no_decimals }}"):t}qt(t,n){return n?window.Shopify.currency.active===n.currencyCode?1:1/n.currencyRate*t:t}xt(){const t=this.jt();t||yt();const n=t&&new rt(t);this.C=n}jt(){if(!this.t)return null;if(this.$.customSelectors.addToCartButton){const t=p(this.$.customSelectors.addToCartButton,this.t);if(t)return t}const t=[];for(const e of mt){const n=f(e,this.t);t.push(...n)}const n=k(this.S,t);return n||this.t.querySelector("button")}Ft(){this.C&&S(this.C.element,(()=>{var t;this.xt(),l("observeAddToCartButtonRemoval found new add to cart button",this.C),a("add_to_cart_button_removed",{recreated:!!this.C,theme:null==(t=window.Shopify.theme)?void 0:t.schema_name},.01),this.Bt.replaceAddToCartButton(this.C),this.Ft()}))}At(){const t=ot.find(this.S,this.$.customSelectors.variantPicker);t&&(this.V.hideVariantPicker&&t.hide(),this.q=t)}Dt(){this.q&&S(this.q.elements()[0],(()=>{var t;this.At(),l("observeVariantPickerRemoval found new variant picker",this.q),a("variant_picker_removed",{recreated:!!this.q,theme:null==(t=window.Shopify.theme)?void 0:t.schema_name},.01),this.Bt.replaceVariantPicker(this.q),this.Dt()}))}$t(){let t=this.S.parentElement;for(;t;){for(const n of wt)for(const e of[this.$.customSelectors.addToCartButton,...mt,"button"]){if(!e)continue;const i=p(`${n} ${e}`,t);if(i)return i.closest(n)}t=t.parentElement}return null}Tt(){const t=this.Gt(),n=k(this.S,t,6);if(!n)return;this.$.keepQuantityInput||(n.style.display="none");const e=n.matches("input")?n:n.querySelector("input");this.N=e}Vt(){this.N&&S(this.N,(()=>{var t;this.Tt(),l("observeQuantityInputRemoval found new quantity input",this.N),a("quantity_input_removed",{recreated:!!this.N,theme:null==(t=window.Shopify.theme)?void 0:t.schema_name},.01),this.Bt.replaceQuantityInput(this.N),this.Vt()}))}Gt(){const t=this.$.customSelectors.quantity;if(t){const n=f(t);if(n.length)return n}for(const[n,e]of C){if(!e)continue;const t=f(e);if(t.length)return t}return f(".product-form__quantity")}Ot(){const t=setInterval((()=>{(void 0!==window.FastClick||void 0!==window.T4SThemeSP&&void 0!==window.T4SThemeSP.FastClick||void 0!==window.BEEThemeSP&&void 0!==window.BEEThemeSP.FastClick)&&(clearInterval(t),f("*",this.S).forEach((t=>{return e="needsclick",(n=t)&&n.classList.add(e);var n,e})))}),500)}}class bt{constructor(t){this.$=t,setTimeout((()=>{const t=document.querySelector('link[href*="kaching-bundles-block.css"]');t&&S(t,(()=>{var t;a("css_removed",{theme:null==(t=window.Shopify.theme)?void 0:t.schema_name},.01)}))}),100)}init(){this.Et();const t=f("kaching-bundle, kaching-bundle-deals");this.Mt(t),0===t.length&&this.Ut(),this.Jt(),this.$.abTestsRunning&&(async()=>{try{$();const t=T();await A()!==t&&await D(t)}catch(t){if(!(t instanceof N))throw t;console.error(t)}})()}Et(){const t=b("script#kaching-bundles-translations")||[],n=t.find((t=>t.locale===this.$.locale));this.T=null==n?void 0:n.translations,(async t=>{ut=t})(t)}Mt(t){const n=b("script.kaching-bundles-product");if(n)for(const e of t)e.getAttribute("product-id")||e.setAttribute("product-id",n.id)}Ut(){if(!p("script.kaching-bundles-deal-block-settings"))return;const t=this.Rt();if(!t.length)return void yt();const n=b("script.kaching-bundles-product"),e=n&&n.id||this.$.productId;for(const i of t){const t=w("kaching-bundle");t.setAttribute("product-id",e),i.parentElement.insertBefore(t,i)}}async Jt(){var t,n;const e=[...f("kaching-bundle, kaching-bundle-deals")].filter((t=>t.getAttribute("product-id")));l("_initializePlaceholders",e);if(0===e.filter((t=>!_(t).initialized)).length)return;const i=await this.Qt(e);l("placeholdersData",i);const o=Array.from(i.values()).map((({dealBlock:t})=>t)).filter((t=>null!=t)),r=Array.from(i.values()).map((({product:t})=>t)).filter((t=>null!=t));if(await Y(this.$.storefrontAccessToken,r,o),!this.$.featureFlags.discount_function_v4)for(const s of r)for(const t of s.sellingPlans)t.priceAdjustment=null;const a=T();for(const c of e){const e=Number(c.getAttribute("product-id")),{product:o,dealBlock:r}=i.get(e);if(!o||!r)continue;this.$.webPixel?setTimeout((()=>{var t;null==(t=window.Shopify.analytics)||t.publish("kaching_bundle_viewed",{product_id:e,deal_block_id:r.id,ab_test_variant_id:r.abTestVariantId,session_id:a})})):setTimeout((()=>{s(this.$.shopifyDomain,r.id,e,r.abTestVariantId,a)}),2e3);const u={...{...this.$.defaultTranslations,...null==(t=this.T)?void 0:t.system},...null==(n=this.T)?void 0:n.dealBlocks[r.id]};new _t(c,this.$,u,r,o)}}async Qt(t){var n;const e=t.map((t=>Number(t.getAttribute("product-id")))),i=this.$.locale===this.$.liquidLocale?[...f("script.kaching-bundles-product")]:[],o=new Map(i.map((t=>{const n=Number(_(t).productId),e=JSON.parse(t.textContent);return 250===e.variants.length?null:[n,e]})).filter((t=>null!==t))),r=e.filter((t=>!o.has(t))),s=[...f("script.kaching-bundles-deal-block-settings")],a=new Map;for(const f of e){const t=s.filter((t=>Number(_(t).productId)===f));t.length&&a.set(f,t.map((t=>t.textContent?JSON.parse(t.textContent):null)))}const c=e.filter((t=>!a.has(t))),u=this.$.storefrontAccessToken?new j(this.$.storefrontAccessToken):null,l=r.length>0&&u?M(u,{country:window.Shopify.country,language:window.Shopify.locale.split("-")[0].toUpperCase(),productIds:r,removeUnavailableVariants:!1,includeSellingPlans:this.$.accessScopes.includes("unauthenticated_read_selling_plans")}):[],d=c.length>0&&u?z(u):[],[h,p]=await Promise.all([l,d]),m=new Map(r.map((t=>[t,h.find((n=>n.id==t))]))),w=new Map([...o,...m]),y=T(),b=new Map;for(const f of e){const t=w.get(f);if(!t)continue;const e=(null==(n=a.get(f))?void 0:n.filter((t=>t)))||p;let i=this.Lt(e,t);i=i.filter((t=>!t.marketId||t.marketId===this.$.marketId)),i=i.filter((t=>{if(!t.abTestVariantId)return!0;const n=O(y,t.abTestVariantsCount);return t.abTestVariantNumber===n})),this.$.b2bCustomer&&(i=i.filter((t=>!t.excludeB2bCustomers))),i.length?b.set(f,{product:t,dealBlock:i[0]}):b.set(f,{product:t,dealBlock:null})}return b}Lt(t,n){const e=[],i=t.filter((t=>"selected-products"===t.blockVisibility));for(const a of i)a.selectedProductIds.map(Number).includes(n.id)&&e.push(a);const o=t.filter((t=>"selected-collections"===t.blockVisibility));for(const a of o)n.collectionIds.some((t=>a.selectedCollectionIds.map(Number).includes(t)))&&e.push(a);const r=t.filter((t=>"excluded-products"===t.blockVisibility));for(const a of r)a.excludedProductIds.map(Number).includes(n.id)||(a.excludedCollectionIds||[]).some((t=>n.collectionIds.includes(t)))||e.push(a);const s=t.filter((t=>"all-products"===t.blockVisibility));for(const a of s)e.push(a);return e}Rt(){const t=this.zt();if(t)return[t];const n=this.Kt();if(n)return[n];const e=this.Ht();return e?[e]:[]}zt(){const t=f("gp-product-button");for(const n of t)if(!n.closest("gp-sticky"))return n;return null}Kt(){for(const t of C){const n=p(t[0]);if(n){if(n.closest(".dbtfy-sticky-addtocart, .cart-drawer"))continue;return setTimeout((()=>{var e;const i=n.closest('[class*="cart"], [class*="Cart"]');i&&"body"!==i.tagName.toLowerCase()&&(i.classList.toString().includes("add-to-cart")||i.classList.toString().includes("AddToCart")||i.classList.toString().includes("icartShopifyCartContent")||a("theme_position_in_cart_drawer_v8",{selector:t[0],classes:i.classList.toString(),theme:null==(e=window.Shopify.theme)?void 0:e.schema_name},.01))})),n}}return null}Ht(){for(const t of wt)for(const n of[this.$.customSelectors.addToCartButton,...mt,"button"]){if(!n)continue;const e=p(`${t} ${n}`);if(e)return e.parentElement}return null}}const gt=t=>{var n;801===(null==(n=window.Shopify.theme)?void 0:n.theme_store_id)?setTimeout((()=>new bt(t).init()),100):new bt(t).init()},vt=()=>{if(void 0===e&&(e="off"===n()),e){const t=f("style#kaching-bundles-custom-css");for(const n of t)n.remove();return}o()&&(l("App version",(()=>{const t=document.currentScript;if(!t)return null;const n=t.src.match(/\/([^/]+)\/assets\//);return n&&n[1]?n[1]:null})()),l("Shopify domain",window.Shopify.shop));const t=b("script#kaching-bundles-config");if(!t)return;u();const i=window.Shopify.currency;t.currencyRate=i?Number(i.rate):1,t.locale=window.Shopify.locale||t.liquidLocale,window.kachingBundlesKeepQuantityInput&&(t.keepQuantityInput=!0),gt(t),window.Shopify.designMode&&m(window,"shopify:section:load",(()=>{gt(t)})),(()=>{const t=/\b__kaching_/,n=["script","style"],e=e=>{const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:t=>{const e=t.parentElement;return!e||n.includes(e.tagName.toLowerCase())?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let o;for(;o=i.nextNode();){const n=o.textContent||"";if(t.test(n)){const t=o.parentElement;if(t.classList.contains("properties-key-value-key"))continue;if("dt"===t.tagName.toLowerCase()){const n=t.nextElementSibling;"dd"===(null==n?void 0:n.tagName.toLowerCase())&&(n.style.display="none")}t.style.display="none",a("kaching_property_hidden",{text:n,element:t.tagName},.01)}}};new MutationObserver((t=>{for(const n of t)for(const t of n.addedNodes)t.nodeType===Node.ELEMENT_NODE&&e(t)})).observe(document.body,{childList:!0,subtree:!0}),e(document.body)})(),(()=>{const t=document.querySelector('link[href*="kaching-bundles-block.css"]');if(!t)return;const n=t.closest('div[data-block-type="liquid"]');n&&(n.dataset.blockType="liquid-kaching-fix")})(),window.kachingBundlesApi=(st=t,{fetchDeal:dt}),setTimeout((()=>{lt()}),1e3)};window.kachingBundlesDisableAutoInitialize||vt(),window.kachingBundlesInitialize=vt}();