!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 i;let e;const o=()=>(void 0===e&&(e="debug"===n()),e);let s;const r=async(t,n,i)=>{const e=`https://${t||"bundles.kachingappz.app"}/storefront_api/${n}`,o={...i,shop:window.Shopify.shop,version:q()};return await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})},a=async(n,i,e,o,s)=>{try{const r="kaching_visited_deal_blocks",a=t.getItem(r),c=a?JSON.parse(a):[];if(c.includes(i))return;c.push(i),t.setItem(r,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:i,productId:e,abTestVariantId:o,sessionId:s})})}catch(r){console.error(r)}},c=async(t,n,i={},e=1)=>{if(Math.random()>e)return;h("sendStorefrontEvent",{name:n,data:i});const o=window.location.href;return await r(t,"events",{event:{name:n,data:i,url:o}})},u=async(t,n,i,e)=>{if("Failed to fetch"===i)return;const o=window.location.href;return await r(t,"errors",{error:{filename:n,message:i,stack:e,url:o}})},d=t=>{const n=["kaching-bundles.js","kaching-bundles-block.js"];window.addEventListener("error",(async function(i){try{await(async i=>{const{filename:e,message:s,error:r}=i;for(const a of n)if(e.includes(a)){if(o())return void h("Error",i);await u(t,e,s,r.stack)}})(i)}catch(e){console.error(e)}})),window.addEventListener("unhandledrejection",(async function(i){try{await(async i=>{if("object"!=typeof i.reason)return;const{message:e,stack:s}=i.reason;if(s)for(const r of n)if(s.includes(r)){if(o())return void h("Unhandled rejection",i);await u(t,r,e,s)}})(i)}catch(e){console.error(e)}}))};function h(t,i=null){(o()||(void 0===s&&(s="dev"===n()),s))&&console.debug("[Kaching Bundles]",t,i)}const l=()=>{const t=t=>{window.dispatchEvent(new Event(t))},n=history.pushState;history.pushState=function(...i){const e=n.apply(this,i);return t("pushstate"),t("locationchange"),e};const i=history.replaceState;history.replaceState=function(...n){const e=i.apply(this,n);return t("replacestate"),t("locationchange"),e},y(window,"popstate",(()=>{t("locationchange")}))},p=(t,n,i,e=0)=>{const o=Object.getPrototypeOf(t);if(o.hasOwnProperty(n)){const s=Object.getOwnPropertyDescriptor(o,n);if(!s.configurable)return;Object.defineProperty(t,n,{configurable:!0,get:function(...t){return s.get.apply(this,t)},set:function(...t){const o=this[n];s.set.apply(this,t);const r=this[n];return"function"==typeof i&&setTimeout(i.bind(this,o,r),e),r}})}},f=(t,n=document.body)=>n.querySelector(t),m=(t,n=document.body)=>[...n.querySelectorAll(t)],y=(t,n,i)=>t.addEventListener(n,i),w=t=>document.createElement(t),_=(t,n,i)=>t.setAttribute(n,i),b=t=>t.dataset,g=t=>{const n=f(t);if(!n)return;const i=JSON.parse(n.textContent);return h("jsonFromElement",i),i},v=(t,n)=>{let i=0,e=t;for(;e!==n&&e!==document.body;)i++,e=e.parentNode;if(e!==n)throw new Error("The specified child node is not a descendant of the parent node.");return i},k=(t,n)=>{const i=new Range;return i.setStart(t,0),i.setEnd(n,0),i.collapsed&&(i.setStart(n,0),i.setEnd(t,0)),i.commonAncestorContainer},S=(t,n,i=1/0)=>{let e=null,o=1/0;for(const s of n){const n=k(t,s),r=v(t,n);r>i||r{const t=document.currentScript;if(!t)return null;const n=t.src.match(/\/([^/]+)\/assets\//);return n&&n[1]?n[1]:null},I=t=>{const n=window.Shopify.routes;return(n&&n.root||"/")+t},C=(t,n)=>{new MutationObserver(((i,e)=>{for(const o of i)"childList"===o.type&&o.removedNodes.forEach((i=>{i.contains(t)&&(e.disconnect(),n())}))})).observe(document.body,{childList:!0,subtree:!0})},T=[['[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"]];class N extends Error{constructor(t){super(t),this.name="CartFetchError"}}const P="kaching_session_id",$=()=>{const n=new URL(window.location.href),i=new URLSearchParams(n.search).get("preview_kaching_session_id");i&&t.setItem(P,i)},V=()=>t.getItem(P)||F(),F=()=>{const n=window.crypto&&window.crypto.randomUUID?window.crypto.randomUUID():O();return t.setItem(P,n),n},O=()=>"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(I("cart.js"));if(!t.ok)throw new N("Failed to fetch cart");return(await t.json()).attributes.__kaching_session_id},j=async t=>{const n=new FormData;n.append("attributes[__kaching_session_id]",t);const i=await fetch(I("cart/update.js"),{method:"POST",body:n});return await i.json()},Q=(t,n)=>{const i=t.slice(-1);return parseInt(i,16)%n+1};class B{constructor(t,n,i,e,o){if(h("AddToCartForm",[t]),this.t=t,this.i=n,this.o=i,this.u=e,o){this.h("properties[__kaching_session_id]").value=V()}}update(t){if(h("AddToCartForm#update",[this.t,t]),1===t.length||this.u){const n=t.find((t=>t.variantId==this.currentVariantId()))||t[0],{variantId:i,quantity:e}=n;this.l({variantId:i,quantity:e})}else t.length>1&&this.p(t)}legacyFormData(){const t=new FormData(this.t);return t.has("items[0][id]")&&(t.delete("id"),t.delete("quantity")),t}currentVariantId(){const t=this.m("id");if(t)return Number(t.value)}l(t){this._();const{variantId:n,quantity:i}=t,e=this.h("id");e.disabled=!1,e.value=String(n),h("AddToCartForm#_addSingleVariantToCartForm",{idInput:e,variantId:n}),this.v(i)}v(t){h("AddToCartForm#_updateQuantityInput",t);let n=null;n=this.o?this.h("quantity"):this.m("quantity"),n&&(n.disabled=!1,n.value=String(t))}p(t){this._();for(const[n,i]of t.entries()){const{variantId:t,quantity:e}=i;this.h(`items[${n}][id]`).value=String(t);this.h(`items[${n}][quantity]`).value=String(e)}this.k()}k(){const t=this.m("id");t&&(t.disabled=!0);const n=this.m("quantity");n&&(n.disabled=!0)}_(){const t=m('input[name^="items"]',this.t);for(const n of t)n.remove()}h(t){if("ef847e-2.myshopify.com"===window.Shopify.shop&&"id"===t){const n=this.m(t);if(n)return n;const i=f(`input[name="${t}"]`);return i||this.S(t)}return this.m(t)||this.S(t)}m(t){return f(`[name="${t}"]`,this.t)}S(t){const n=w("input");return n.type="hidden",n.name=t,this.t.prepend(n),n}}const x="2024-07",R=t=>{const n=t.variants.edges.map((t=>t.node)).map((t=>({id:Number(t.id.split("/").pop()),price:Math.round(100*Number(t.price.amount)),compareAtPrice:t.compareAtPrice?Math.round(100*Number(t.compareAtPrice.amount)):null,options:t.selectedOptions.map((t=>t.value)),imageId:t.image?Number(t.image.id.split("/").pop()):null}))),i=t.options.map(((t,i)=>{const e=t.optionValues.map((t=>{var n,i,e,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==(e=null==(i=t.swatch)?void 0:i.image)?void 0:e.previewImage)?void 0:o.url)||null}}}));return{defaultName:t.name,name:t.name,position:i+1,optionValues:J(e,i,n)}})),e={text:null,text2:null};t.metafield_text&&(e.text=t.metafield_text.value),t.metafield_text2&&(e.text2=t.metafield_text2.value);return{id:Number(t.id.split("/").pop()),title:t.title,collectionIds:t.collections.edges.map((t=>Number(t.node.id.split("/").pop()))),options:i,selectedVariantId:Number(t.variants.edges[0].node.id.split("/").pop()),variants:n,metafields:{kaching_bundles:e}}},J=(t,n,i)=>t.filter((t=>i.filter((i=>i.options[n]===t.name)).length>0)),E=async(t,n)=>{const i=`https://${t||"bundles.kachingappz.app"}/storefront_api/deal_blocks?shop=${n}`,e=await fetch(i);return(await e.json()).deal_blocks},M=async t=>{var n;const i=await fetch(`/api/${x}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:'\n {\n shop {\n metafield(namespace: "$app:kaching_bundles", key: "deal_blocks") {\n value\n }\n }\n }\n '})}),e=null==(n=(await i.json()).data.shop.metafield)?void 0:n.value;return e?JSON.parse(e):[]},D=async(t,n,i=100)=>{const e=await fetch(`/api/${x}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:"\n query mediaImages($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:i}})});return(await e.json()).data.nodes.filter(Boolean).map((t=>({gid:t.id,url:t.image.url})))},L=t=>{var n;const i=t.variants.nodes.map((t=>{var n;return{id:Number(t.id.split("/").pop()),image:(null==(n=t.image)?void 0:n.url)||null,options:t.selectedOptions.map((t=>t.value))}})),e=t.options.map(((t,n)=>{const e=t.optionValues.map((t=>{var n,i,e,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==(e=null==(i=t.swatch)?void 0:i.image)?void 0:e.previewImage)?void 0:o.url)||null}}}));return{defaultName:t.name,name:t.name,position:n+1,optionValues:J(e,n,i)}}));return{id:Number(t.id.split("/").pop()),url:t.onlineStoreUrl,availableForSale:t.availableForSale,image:(null==(n=t.featuredImage)?void 0:n.url)||null,options:e,variants:i}},U=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}},z=async(t,n)=>{const i=n.dealBars.map((t=>t.mediaImageGID)).filter((t=>null!=t));if(!i.length)return[];return await D(t,i,300)},G=async(t,n)=>{const i=n.dealBars.map((({freeGift:t})=>null==t?void 0:t.mediaImageGID)).filter((t=>null!=t));if(!i.length)return[];return await D(t,i,300)},H=async(t,n)=>{if(!n.swatchOptions)return[];const i=n.swatchOptions.reduce(((t,n)=>[...t,...n.images.map((t=>t.mediaImageGID)).filter((t=>null!=t))]),[]);if(!i.length)return[];return await D(t,i)},X=window;class W{constructor(t,n,i,e,o,s,r,a){this.q=null,this.I=null,h("DealBlock",{dealBlock:t,cartForm:n,addToCartButton:i,quantityInput:e,variantPicker:o,globalConfig:s,dealBlockSettings:r,product:a}),this.C=t,this.t=n,this.T=i,this.N=e,this.P=o,this.$=s,this.V=r,this.i=a,this.F=this.i.selectedVariantId||this.i.variants[0].id,this.O=n&&new B(n,a,!e,s.addDifferentVariantsToCartSeparately,!!r.abTestVariantNumber),this.A()}updateVariantPicker(t){this.P=t}updateAddToCartButton(t){this.T=t,this.j()}updateQuantityInput(t){this.N=t,this.B()}A(){_(this.C,"config",JSON.stringify(this.$)),_(this.C,"deal-block",JSON.stringify(this.V)),_(this.C,"product",JSON.stringify(this.i)),_(this.C,"current-variant-id",String(this.F)),this.R(),this.J(),this.t&&(this.T||"119a01-bf.myshopify.com"===window.Shopify.shop)&&this.M()}async R(){const t=await(async(t,n)=>{const[i,e,o]=await Promise.all([z(t,n),G(t,n),H(t,n)]);return[...i,...e,...o]})(this.$.storefrontAccessToken,this.V);_(this.C,"media-images",JSON.stringify(t))}async J(){const t=this.V.dealBars.map((({freeGift:t})=>null==t?void 0:t.productGID)).filter((t=>null!=t));if(!t.length)return;const n=await(async(t,n,i,e)=>{const o=e.map((t=>Number(t.split("/").pop()))).map((t=>`id:${t}`)).join(" OR "),s=await fetch(`/api/${x}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:`\n query($productsQuery: String!) @inContext(country: ${n}, language: ${i}) {\n products(query: $productsQuery, first: 100) {\n nodes {\n id\n onlineStoreUrl\n availableForSale\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: 100, maxHeight: 100 })\n }\n }\n }\n }\n }\n variants(first: 250) {\n nodes {\n id\n selectedOptions {\n name\n value\n }\n image {\n url\n }\n }\n }\n }\n }\n }\n `,variables:{productsQuery:o}})});return(await s.json()).data.products.nodes.map(L)})(this.$.storefrontAccessToken,window.Shopify.country,window.Shopify.locale.split("-")[0].toUpperCase(),t);_(this.C,"free-gift-products",JSON.stringify(n))}M(){this.D(),this.L(),this.U(),this.B(),this.G(),this.H(),window.kachingBundlesDisableAddToCartHandling||(this.$.addDifferentVariantsToCartSeparately?this.j():this.X())}D(){l(),y(X,"locationchange",(()=>{const t=new URLSearchParams(X.location.search).get("variant");t&&this.W(Number(t))}))}L(){const t=f('input[name="id"]',this.t);t&&p(t,"value",((t,n)=>{h("_listenForVariantIdInputChange",[t,n]),t!==n&&n&&this.W(Number(n))}))}U(){const t=f('select[name="id"]',this.t);if(!t)return;let n;window.setInterval((()=>{const i=t.value;n!==i&&i&&(h("_listenForVariantIdSelectChange",[n,i]),n=i,this.W(Number(i)))}),100)}W(t){t!=this.F&&(this.F=t,this.C.dataset.nativeVariantChangeInProgress||window.kachingBundlesVariantChangeInProgress||(h("handleNativeVariantChange",t),this.C.dataset.nativeVariantChangeInProgress="true",setTimeout((()=>{delete this.C.dataset.nativeVariantChangeInProgress}),500),this.i.variants.find((n=>n.id==t))&&_(this.C,"current-variant-id",String(t))))}B(){this.N&&(y(this.N,"change",(()=>{const t=Number(this.N.value);h("_listenForQuantityInputChange change",t),this.K(t)})),p(this.N,"value",((t,n)=>{t!==n&&(h("_listenForQuantityInputChange observe",[t,n]),this.K(Number(n)))})))}K(t){window.kachingBundlesQuantityChangeInProgress||(!this.$.keepQuantityInput||window.kachingBundlesVariantChangeInProgress||this.C.dataset.nativeVariantChangeInProgress?this.Z&&this.Z.length&&this.v(this.Z):this.$.keepQuantityInput&&_(this.C,"quantity",String(t)))}v(t){if(!this.N)return;window.kachingBundlesQuantityChangeInProgress=!0;let n=t.reduce(((t,n)=>t+n.quantity),0);if(this.$.addDifferentVariantsToCartSeparately){const i=this.O.currentVariantId();n=(t.find((({variantId:t})=>t==i))||t[0]).quantity}h("_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)}G(){this.P&&y(this.C,"variant-selected",(t=>{const{variantId:n}=t.detail,i=this.i.variants.find((t=>t.id==n));h("listenForBlockVariantSelect",[n,i]);if(["054d81.myshopify.com","28212b.myshopify.com","79ad13-4.myshopify.com","value-deal-offers.myshopify.com","countrydale.myshopify.com","cbbd15.myshopify.com"].includes(window.Shopify.shop)||i.imageId&&i.imageId!=this.I){this.I=i.imageId,this.F=n,this.Y();for(const[t,n]of i.options.entries()){const e=this.i.options[t],o=e.name,s=e.optionValues.find((t=>t.name===n)).id;this.P.select(t+1,s,o,n,this.i.id,i.id)}}}))}H(){y(this.C,"variants-changed",(t=>{var n;clearTimeout(this.tt);const{variantIdQuantities:i,freeGift:e,formattedPrice:o,preselected:s}=t.detail;h("listenForBlockVariantsChange",{variantIdQuantities:i,freeGift:e,formattedPrice:o,preselected:s}),this.Y(),this.O.update(i),this.Z=i,this.q=e,this.v(i),null==(n=this.T)||n.updatePrice(o),this.nt(),s&&(this.tt=setTimeout((()=>{this.v(i),delete this.tt}),1e3))}))}Y(){clearTimeout(window.kachingBundlesVariantChangeInProgress),window.kachingBundlesVariantChangeInProgress=setTimeout((()=>{delete window.kachingBundlesVariantChangeInProgress}),500)}j(){if(!this.T)return;this.T.onClickIfConditionMet((()=>!window.kachingBundlesDisableAddToCartHandling&&(!!this.V.skipCart||(!!this.q||(!!this.it()||!!this.Z&&!(this.Z.length<2))))),(async()=>this.V.skipCart?(await this.et(),void(window.location.href=I("checkout"))):this.it()?this.et():this.ot()),(()=>this.V.skipCart||this.it()))}it(){return!!f("#UpcartPopup")}async ot(){h("addVariantsExceptCurrentToCart",this.Z);const t=this.O.currentVariantId(),n=this.Z.filter((({variantId:n})=>n!=t))||this.Z[0];await this.st(n)}async et(){h("addAllVariantsToCart",this.Z);let t=this.Z;t||(t=[{variantId:this.O.currentVariantId(),quantity:1}]),await this.st(t)}rt(){const t=m('[name^="properties"]').map((t=>[t.name.match(/properties\[(.*)\]/)[1],t.value]));return Object.fromEntries(t)}async st(t){const n=this.rt(),i=t.map((({variantId:t,quantity:i})=>({id:t,quantity:i,properties:n})));this.q&&i.push({id:this.q.variantId,quantity:this.q.quantity,properties:{__kaching_free_gift:!0}}),h("makeAddToCartRequest",{items:i}),await fetch(I("cart/add.js"),{method:"POST",body:JSON.stringify({items:i}),headers:{"Content-Type":"application/json"}})}X(){this.T&&(y(this.T.element,"click",(t=>{h("Add to cart button click event (legacy)",t),this.ct(t)})),y(this.t,"submit",(t=>{h("Add to cart form submit event (legacy)",t),this.ct(t)})))}async ct(t){h("legacyHandleCartSubmit",this.Z),this.$.multivariantCartDrawer||this.Z&&(this.Z.length<2||(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),await this.ut(),X.location.href=I("cart")))}async ut(){const t=this.O.legacyFormData();if(this.$.useLineItemProperties)for(const[i,e]of this.dt())t.set(i,e);h("legacyMakeAddToCartRequest",t);const n=await fetch(I("cart/add.js"),{method:"POST",body:t});return await n.json()}dt(){if(!this.Z||this.Z.length<2)return[];const t=[],n=m('[name^="properties"]').map((t=>[t.name.match(/properties\[(.*)\]/)[1],t.value]));for(const[i]of this.Z.entries())for(const[e,o]of n)t.push([`items[${i}][properties][${e}]`,o]);return t}nt(){if(!this.Z)return;const t="kaching-bundles-form--different-variants-selected";this.Z.length>1||this.q?this.t.classList.add(t):this.t.classList.remove(t)}}class K{static find(t){let n=t.parentElement;for(;n;){const t=f('variant-selects, variant-radios, variant-picker, product-variants, gp-product-variants, .gf_variants-wrapper, [data-pf-type="ProductVariantSwatches"], .product-selectors',n);if(t)return new K([t]);let i=m(".selector-wrapper, .radio-wrapper, .variant-wrapper, div[data-product-option]",n);if(["28212b.myshopify.com","9bd9ad.myshopify.com"].includes(window.Shopify.shop)&&(i=m(".selector-wrapper, .radio-wrapper, .variant-wrapper, .select-wrapper, div[data-product-option]",n)),i.length){const t=i.filter((t=>!i.some((n=>n!==t&&n.contains(t)))));return new K(t)}n=n.parentElement}return null}constructor(t){this.ht=t}elements(){return this.ht}hide(){for(const t of this.ht)t.style.display="none",t.parentElement.classList.add("kaching-bundles--variant-selects-hidden")}select(t,n,i,e,o,s){h("VariantPicker#select",[t,n,i,e]),this.lt(t,n,i,e,o)||this.ft(t,i,e)||this.yt(s)}lt(t,n,i,e,o){const s=this.ht.map((t=>[...t.querySelectorAll("input")])).flat();let r=s.filter((n=>[i,`${i}-${t}`,`options[${i}]`,`option${t}`,`option-${o}-${t-1}`].includes(n.name.trim())));r.length||(r=s.filter((n=>!!n.dataset.optionPosition&&Number(n.dataset.optionPosition)===t)));const a=r.find((t=>t.value==e||t.value===String(n)));return!!a&&(h("VariantPicker#_clickRadioInput",a),a.click(),!0)}ft(t,n,i){const e=this.ht.map((t=>[...t.querySelectorAll("select")])).flat().find((i=>!![`options[${n}]`,`option${t}`].includes(i.name)||(i.dataset.index===`option${t}`||(i.dataset.optionName===n||(i.id==="SingleOptionSelector-product-"+(t-1)||i.id===`p-variant-dropdown-${t}`)))));if(!e)return!1;return!![...e.options].find((t=>t.value==i))&&(h("VariantPicker#_setSelectValue",{variantSelect:e,optionValue:i}),e.value=i,e.dispatchEvent(new Event("change",{bubbles:!0})),!0)}yt(t){const n=this.ht.map((t=>[...t.querySelectorAll("select")])).flat().find((n=>[...n.options].find((n=>Number(n.value)===t))));return!!n&&(h("VariantPicker#_setSelectVariantId",{variantSelect:n,variantId:t}),n.value=String(t),n.dispatchEvent(new Event("change",{bubbles:!0})),!0)}}class Z{constructor(t){this.wt=!1,this._t=!1,this.element=t}onClickIfConditionMet(t,n,i){this.element.addEventListener("click",(async e=>{const o=t(),s=i();h("AddToCartButton#interceptClick",{conditionMet:o,preventDefault:s,submitInProgress:this.wt,ignoreClick:this._t}),o&&(this.wt?this.wt=!1:this._t||(this.wt=!0,this._t=!0,this.element.disabled=!0,setTimeout((()=>{this._t=!1}),1e3),e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),await n(),this.element.disabled=!1,s?this.wt=!1:this.element.click()))}),!0)}updatePrice(t){const n=this.bt(this.element);n&&(n.innerHTML=t)}bt(t){if(!t.childNodes.length)return null;const n=t.childNodes[0].nodeValue;if(n&&n.match(/\d/)&&!n.match(/[a-zA-Z]{4}/))return t;for(const i of t.childNodes){const t=this.bt(i);if(t)return t}return null}}const Y=['[data-pf-type^="ProductATC"]',"button.gp-button-atc","gp-product-button button",'button[type="submit"]','input[type="submit"]'],tt=['form[action*="/cart/add"]',"form[data-instant-form-product-url]"],nt=()=>{"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 it{constructor(t,n,i,e){this.N=null,this.P=null,this.T=null,this.$=n,this.V=i,t.innerHTML='',b(t).initialized="true",this.C=f("kaching-bundles-block",t),this.t=this.gt(),this.vt(),this.kt(),this.St(),this.qt(),this.It(),this.Ct(),this.Tt(),this.Nt=new W(this.C,this.t,this.T,this.N,this.P,n,i,e)}St(){const t=this.Pt();t||nt();const n=t&&new Z(t);this.T=n}Pt(){if(!this.t)return null;const t=[];for(const i of Y){const n=m(i,this.t);t.push(...n)}const n=S(this.C,t);return n||this.t.querySelector("button")}qt(){this.T&&C(this.T.element,(()=>{var t;this.St(),h("observeAddToCartButtonRemoval found new add to cart button",this.T),c(this.$.customApiHost,"add_to_cart_button_removed",{recreated:!!this.T,theme:null==(t=window.Shopify.theme)?void 0:t.name},.01),this.Nt.updateAddToCartButton(this.T),this.qt()}))}It(){const t=K.find(this.C);t&&(this.V.hideVariantPicker&&t.hide(),this.P=t)}Ct(){this.P&&C(this.P.elements()[0],(()=>{var t;this.It(),h("observeVariantPickerRemoval found new variant picker",this.P),c(this.$.customApiHost,"variant_picker_removed",{recreated:!!this.P,theme:null==(t=window.Shopify.theme)?void 0:t.name},.01),this.Nt.updateVariantPicker(this.P),this.Ct()}))}gt(){let t=this.C.parentElement;for(;t;){for(const n of tt)for(const i of[...Y,"button"]){const e=f(`${n} ${i}`,t);if(e)return e.closest(n)}t=t.parentElement}if("119a01-bf.myshopify.com"===window.Shopify.shop)for(t=this.C.parentElement;t;){if(t.matches(tt[0]))return t;t=t.parentElement}return null}vt(){const t=this.$t(),n=S(this.C,t,6);if(!n)return;this.$.keepQuantityInput||(n.style.display="none");const i=n.matches("input")?n:n.querySelector("input");this.N=i}kt(){this.N&&C(this.N,(()=>{var t;this.vt(),h("observeQuantityInputRemoval found new quantity input",this.N),c(this.$.customApiHost,"quantity_input_removed",{recreated:!!this.N,theme:null==(t=window.Shopify.theme)?void 0:t.name},.01),this.Nt.updateQuantityInput(this.N),this.kt()}))}$t(){const t=this.$.customSelectors.quantity;if(t){const n=m(t);if(n.length)return n}for(const[n,i]of T){if(!i)continue;const t=m(i);if(t.length)return t}return m(".product-form__quantity")}Tt(){const t=setInterval((()=>{(void 0!==window.FastClick||void 0!==window.T4SThemeSP&&void 0!==window.T4SThemeSP.FastClick)&&(clearInterval(t),m("*",this.C).forEach((t=>{return i="needsclick",(n=t)&&n.classList.add(i);var n,i})))}),500)}}class et{constructor(t){this.$=t,setTimeout((()=>{var n;const i=document.querySelector('link[href*="kaching-bundles-block.css"]');i?C(i,(()=>{var n;c(t.customApiHost,"css_removed",{theme:null==(n=window.Shopify.theme)?void 0:n.name})})):c(t.customApiHost,"css_not_found",{theme:null==(n=window.Shopify.theme)?void 0:n.name})}),100)}init(){const t=m("kaching-bundle, kaching-bundle-deals");this.Vt(t),0===t.length&&this.Ft(),this.Ot(),this.$.abTestsRunning&&(async()=>{try{$();const t=V();await A()!==t&&await j(t)}catch(t){if(!(t instanceof N))throw t;console.error(t)}})()}Vt(t){const n=g("script.kaching-bundles-product");if(n)for(const i of t)i.getAttribute("product-id")||i.setAttribute("product-id",n.id)}Ft(){if(!f("script.kaching-bundles-deal-block-settings"))return;const t=this.At();if(!t.length)return void nt();const n=g("script.kaching-bundles-product"),i=n&&n.id||this.$.productId;for(const e of t){const t=w("kaching-bundle");t.setAttribute("product-id",i),e.parentElement.insertBefore(t,e)}}async Ot(){const t=[...m("kaching-bundle, kaching-bundle-deals")].filter((t=>t.getAttribute("product-id")));h("_initializePlaceholders",t);if(0===t.filter((t=>!b(t).initialized)).length)return;const n=await this.jt(t);h("placeholdersData",n);const i=await this.Qt(Array.from(n.keys()),Array.from(n.values()).map((({dealBlock:t})=>t)).filter((t=>null!=t))),e=V();for(const o of t){const t=Number(o.getAttribute("product-id")),{product:s,dealBlock:r}=n.get(t);if(!s||!r)continue;setTimeout((()=>{a(this.$.shopifyDomain,r.id,t,r.abTestVariantId,e)}),2e3);const u=i.find((n=>n.id===t));u&&(this.Bt(s,u),c(this.$.customApiHost,"swatches_different_language",{language:window.Shopify.locale.split("-")[0].toUpperCase()})),new it(o,this.$,r,s)}}async Qt(t,n){if(!this.$.storefrontAccessToken)return[];if(n.map((t=>t.swatchOptions||[])).reduce(((t,n)=>t.concat(n)),[]).filter((t=>null!=t)).filter((t=>"default"!==t.swatchType)).every((t=>t.defaultLanguage===window.Shopify.locale.split("-")[0].toUpperCase())))return[];const i=await(async(t,n)=>{if(!t)return[];const i=n.map((t=>`id:${t}`)).join(" OR "),e=await fetch(`/api/${x}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:"\n query($productsQuery: String!) {\n products(query: $productsQuery, first: 100) {\n edges {\n node {\n id\n options {\n name\n optionValues {\n id\n name\n }\n }\n }\n }\n }\n }\n ",variables:{productsQuery:i}})});return(await e.json()).data.products.edges.map((t=>t.node)).map(U)})(this.$.storefrontAccessToken,t);return i}Bt(t,n){for(const i of n.options){const n=t.options.find((t=>t.position===i.position));if(n){n.defaultName=i.defaultName;for(const t of i.optionValues){const i=n.optionValues.find((n=>n.id===t.id));i&&(i.defaultName=t.defaultName)}}}}async jt(t){var n;const i=t.map((t=>Number(t.getAttribute("product-id")))),e=this.$.locale===this.$.liquidLocale?[...m("script.kaching-bundles-product")]:[],o=new Map(e.map((t=>[Number(b(t).productId),JSON.parse(t.textContent)]))),s=i.filter((t=>!o.has(t))),r=[...m("script.kaching-bundles-deal-block-settings")],a=new Map;for(const m of i){const t=r.filter((t=>Number(b(t).productId)===m));t.length&&a.set(m,t.map((t=>JSON.parse(t.textContent))))}const c=i.filter((t=>!a.has(t)||0===a.get(t).length||!a.get(t)[0])),u=s.length>0&&this.$.storefrontAccessToken?(async(t,n,i,e)=>{const o=e.map((t=>`id:${t}`)).join(" OR "),s=await fetch(`/api/${x}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:`\n query($productsQuery: String!) @inContext(country: ${n}, language: ${i}) {\n products(query: $productsQuery, first: 100) {\n edges {\n node {\n id\n title\n options {\n name\n optionValues {\n id\n name\n swatch {\n color\n image {\n previewImage {\n url(transform: { maxWidth: 100, maxHeight: 100 })\n }\n }\n }\n }\n }\n variants(first: 250) {\n edges {\n node {\n id\n price {\n amount\n }\n compareAtPrice {\n amount\n }\n selectedOptions {\n name\n value\n }\n image {\n id\n }\n }\n }\n }\n collections(first: 50) {\n edges {\n node {\n id\n }\n }\n }\n metafield_text: metafield(namespace: "kaching_bundles", key: "text") {\n value\n }\n metafield_text2: metafield(namespace: "kaching_bundles", key: "text2") {\n value\n }\n }\n }\n }\n }\n `,variables:{productsQuery:o}})});return(await s.json()).data.products.edges.map((t=>t.node)).map(R)})(this.$.storefrontAccessToken,window.Shopify.country,window.Shopify.locale.split("-")[0].toUpperCase(),s):[],d=c.length>0?(async(t,n,i)=>n?M(n):E(t,i))(this.$.customApiHost,this.$.storefrontAccessToken,this.$.shopifyDomain):[],[h,l]=await Promise.all([u,d]),p=new Map(s.map((t=>[t,h.find((n=>n.id==t))]))),f=new Map([...o,...p]),y=V(),w=new Map;for(const m of i){const t=f.get(m),i=(null==(n=a.get(m))?void 0:n.filter((t=>t)))||l;let e=this.xt(i,t);e=e.filter((t=>{if(!t.abTestVariantId)return!0;const n=Q(y,t.abTestVariantsCount);return t.abTestVariantNumber===n})),e.length?w.set(m,{product:t,dealBlock:e[0]}):w.set(m,{product:t,dealBlock:null})}return w}xt(t,n){const i=[],e=t.filter((t=>"selected-products"===t.blockVisibility));for(const a of e)a.selectedProductIds.map(Number).includes(n.id)&&i.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)))&&i.push(a);const s=t.filter((t=>"excluded-products"===t.blockVisibility));for(const a of s)a.excludedProductIds.map(Number).includes(n.id)||i.push(a);const r=t.filter((t=>"all-products"===t.blockVisibility));for(const a of r)i.push(a);return i}At(){const t=this.Rt();if(t)return[t];const n=this.Jt();if(n)return[n];const i=this.Et();return i?[i]:[]}Rt(){const t=m("gp-product-button");for(const n of t)if(!n.closest("gp-sticky"))return n;return null}Jt(){for(const t of T){const n=f(t[0]);if(n){if(n.closest(".dbtfy-sticky-addtocart"))continue;return n}}return null}Et(){for(const t of tt)for(const n of[...Y,"button"]){const i=f(`${t} ${n}`);if(i)return i.parentElement}return null}}const ot=t=>{var n;801===(null==(n=window.Shopify.theme)?void 0:n.theme_store_id)?setTimeout((()=>new et(t).init()),100):new et(t).init()},st=()=>{if(void 0===i&&(i="off"===n()),i){const t=m("style#kaching-bundles-custom-css");for(const n of t)n.remove();return}o()&&(h("App version",q()),h("Shopify domain",window.Shopify.shop));const t=g("script#kaching-bundles-config");if(!t)return;d(t.customApiHost);const e=window.Shopify.currency;t.currencyRate=e?Number(e.rate):1,t.locale=window.Shopify.locale||t.liquidLocale,ot(t),window.Shopify.designMode&&y(window,"shopify:section:load",(()=>{ot(t)})),(t=>{var n;const i=document.querySelector('link[href*="kaching-bundles-block.css"]');if(!i)return;const e=i.closest('div[data-block-type="liquid"]');e&&(c(t,"impact_theme_fix",{theme:null==(n=window.Shopify.theme)?void 0:n.name}),e.dataset.blockType="liquid-kaching-fix")})(t.customApiHost)};window.kachingBundlesDisableAutoInitialize||st(),window.kachingBundlesInitialize=st}();