(()=>{var __webpack_modules__={384:(e,t,r)=>{r.d(t,{A:()=>n});const n={HOST:"https://discounts.logbase.io",API_VERSION:"2025-07",IS_LOG_REQUIRED:!1,LEGACY_USERS:["tilak-polypack.myshopify.com","creativatruffles.myshopify.com","44311b.myshopify.com"]}},413:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{A:()=>__WEBPACK_DEFAULT_EXPORT__});var _config_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(384);const utils={isNotPrivateTab:()=>{try{return"object"==typeof sessionStorage&&"object"==typeof localStorage}catch(e){return!1}},log:(e,t)=>(utils.isNotPrivateTab()&&("true"==sessionStorage.getItem("dealeasy-log")||_config_js__WEBPACK_IMPORTED_MODULE_0__.A.IS_LOG_REQUIRED)&&(t?console.log("%s",`${e} : `,t):console.log("%s",e)),!0),errorLog:(e,t)=>(console.error("%s",e),console.dir(t,{depth:null,colors:!0}),!0),importDayJs:()=>(eval('!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){"use strict";var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",c="month",f="quarter",h="year",d="date",l="Invalid Date",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(t){var e=["th","st","nd","rd"],n=t%100;return"["+t+(e[(n-20)%10]||e[n]||e[0])+"]"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0")},m:function t(e,n){if(e.date()1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t){const e=Array.from(document.querySelectorAll("script[src*='dealeasy']"));if(e.some((e=>e.src.includes("dealeasy-widgets.esm.js"))))return!0;{const t=e.find((e=>e.src.includes("lb-dealeasy.js")));if(t){const e=document.createElement("script");return e.src=t.src.replace("lb-dealeasy.js","dealeasy-widgets.esm.js"),e.type="module",e.defer=!0,document.head.appendChild(e),!0}}return!1},customWait:e=>new Promise((t=>setTimeout(t,e))),encryptData:e=>{const t=String.fromCharCode(...atob("RGVhbGVhc3lCdW5kbGVz").split("").map((e=>e.charCodeAt(0))));let r="";for(let n=0,o=0;n({countryCode:lbDealeasy.CountryCode||Shopify.country,currencyRate:Number(lbDealeasy.CurrencyRate||Shopify.currency.rate),currencyCode:lbDealeasy.CurrencyCode||Shopify.currency.active}),productRegExpressions:{products:/\/products\/([^/?]*)/,variant:/\/variant\/([^/?]*)/},getLocale:()=>{if("function"==typeof dealeasyGetLocale)return dealeasyGetLocale();const e=Shopify.locale.replace("-","_").toUpperCase();if(e){const[t,r]=e.split("_");return t===r?t:e}},getProductHandle:e=>{const t=e.match(utils.productRegExpressions.products),r=t?t[1]:void 0;return r?decodeURIComponent(r):void 0},getRootRoute:()=>Shopify&&Shopify.routes?Shopify.routes.root:void 0,getProductRequestURL:e=>{let t=utils.getRootRoute(),r=`https://${window.location.hostname}/products/${e}.js`;return t&&"/"!==t&&(r=`https://${window.location.hostname}${t}products/${e}.js`),r},getProductOnlineStoreURL:(e,t=void 0)=>{let r=utils.getProductRequestURL(e).replace(".js","");return t&&(r=`${r}?variant=${t}`),r},getCollectionRequestURL:e=>{let t=utils.getRootRoute(),r=`https://${window.location.hostname}/collections/${e}.js`;return t&&"/"!==t&&(r=`https://${window.location.hostname}${t}collections/${e}.js`),r},getCollectionOnlineStoreURL:e=>utils.getCollectionRequestURL(e).replace(".js",""),getURLParam:(e,t)=>{if(e&&"string"==typeof e&&t){const r=e.includes("http")?e:`https://${window.location.hostname}${e}`,n=new URL(r),o=new URLSearchParams(n.search);if(o.has(t))return o.get(t);const i=e.match(utils.productRegExpressions[t]);return i?i[1]:void 0}},getPageProductHandle:e=>{if(e&&e.includes("/products/"))return utils.getProductHandle(e);const t=["#lb-dealeasy-block","#lb-vd-cards","#lb-volume-discount","#lb-bundle"];for(const e of t){const t=document.querySelector(e);if(t){const e=t.getAttribute("productHandle");if(e&&!e.toLowerCase().includes("productid"))return e}}},getCurrentProduct:(e,t)=>{try{const r=utils.getURLParam(t,"variant");if(r){const t=e.variants.find((e=>e.id.includes(r)));return t?{...e,currentVariant:t}:void 0}return{...e,currentVariant:e.variants.find((e=>e.availableForSale))??e.variants[0]}}catch(e){return void console.error("fn.getCurrentProduct : ",e)}},previousVariantOnNetworkReq:void 0,isVariantChangeRequest:(e,t)=>{if(utils.getURLParam(e,"variant"))return!1;const r=utils.getURLParam(t,"variant");return!(!r||r===utils.previousVariantOnNetworkReq)&&(utils.previousVariantOnNetworkReq=r,!0)},isCartActionRequest:e=>{if(e&&"string"==typeof e){const t=["/cart/add","/cart/update","/cart/change","/cart/clear"],r=new URL(e.includes("https://")?e:`https://${window.location.hostname}${e}`).searchParams.get("src"),n="dealeasy"===r,o="selleasy"===r&&"undefined"==typeof lbupsellVersion;if(t.some((t=>e.includes(t)))&&!n&&!o)return!0}return!1},isCartForm:e=>{const t=e.getAttribute("action"),r=e.getAttribute("method");return!!(t&&r&&"post"===r.toLowerCase()&&/\/cart\/?(\?|$)/.test(t))},appendDiscountCodesOnCartFormURL:(e,t)=>{const r=new URL(e.includes("http")?e:`https://${window.location.hostname}${e}`);return t&&t.length?(r.searchParams.set("discount",encodeURIComponent(t.join(","))),r.pathname+r.search):r.pathname+r.search},setDiscountCodes:e=>{if(e&&e.length){const t=JSON.parse(sessionStorage.getItem("dealeasy-discount-code-sources")??"{}");let r=!1;return t.dealeasy&&t.dealeasy.length?(r=t.dealeasy.some((t=>!e.includes(t))),t.dealeasy=[...new Set([...t.dealeasy,...e])]):(t.dealeasy=e,r=!0),sessionStorage.setItem("dealeasy-discount-code-sources",JSON.stringify(t)),r}return!1},getCartGoalPrice:e=>{const[t,r,n]=e.split("-"),o=Shopify.currency.rate;return Number(t*o)},clearLocalStorage:()=>{if(utils.isNotPrivateTab()){const e=[];["dealeasy-gift-products","dealeasy-added-gift-goals","dealeasy-cart-products","dealeasy-discount-code-sources","dealeasy-discount-codes","dealeasy-recommendations","dealeasy-added-gwp-gifts"].forEach((e=>sessionStorage.removeItem(e))),e.forEach((e=>localStorage.removeItem(e)))}return!0},removeWidgetOnPage:e=>{const t={"volume-discount":["lb-volume-discount","lb-vd-cards","lb-vd-qty-selector"],"cart-progress-bar":["lb-cart-progress-bar"],bundles:["lb-bundle-builder","lb-related-bundles"],"vd-nudge":["lb-vd-nudge"],recommendations:["lb-recommendations"],bogo:["lb-bogo-banner"]};return!!t[e]&&(t[e].forEach((e=>document.querySelectorAll(e).forEach((e=>e.remove())))),!0)},getProductFormsOnPage:()=>document.querySelectorAll("form[method='post'][action*='/cart/add']"),getBuyButtonsOnProductForms:(e=void 0)=>{const t=utils.getProductFormsOnPage(),r=[],n=["input[name='id'][type='hidden']","input[name='product-id'][type='hidden']"];"object"==typeof dealeasyFormDefaultAttributes&&n.push(...dealeasyFormDefaultAttributes);const o=n.map((e=>`:not(${e})`)).join("");return t.forEach((t=>{const n=e?t.querySelectorAll(e):t.querySelectorAll(`button:not([data-src*='lb-dealeasy']),input:not([data-src*='lb-dealeasy'])${o},shopify-accelerated-checkout`);r.push(...n)})),r},getAddToCartButtonOnPage:(e=void 0)=>{const t=utils.getBuyButtonsOnProductForms(e);for(const r of t)if("submit"===r.type&&"add"===r.name||e&&r.matches(e))return r},hideElementsOnPage:e=>(e&&"string"==typeof e&&e.split(",").map((e=>e.trim())).forEach((e=>{const t=document.querySelector(e);t&&(t.style.display="none")})),!0),appendModalOnPage:()=>{try{let e=document.querySelector("lb-dealeasy-modal");return e||(e=document.createElement("lb-dealeasy-modal"),document.querySelector("body").insertAdjacentElement("beforeend",e)),e}catch(e){return void console.error("utils.appendModalOnPage : ",e)}},checkModalOnPage:async e=>{const t=document.querySelector("lb-dealeasy-modal");return!t||t.source===e||new Promise(((e,t)=>{window.addEventListener("lb-dealeasy-gpp-close",(t=>{e(!0)}))}))},positionWidget:(e,t,r)=>{try{if(document.querySelector(t))return!0;{const n=document.createElement(t);if(window.location.pathname.includes("/products/"))if("appBlock"==e.positionType){const e=document.querySelector(r);if(e)return e.insertAdjacentElement("beforeend",n),!0}else{const t=screen.width<=480?e.mobilePosition:e.desktopPosition,r=screen.width<=480?e.mobileCssSelector:e.desktopCssSelector,o=utils.getProductFormsOnPage(),i=utils.getAddToCartButtonOnPage()?.parentElement;switch(t){case"belowProductForm":if(o&&o.length)return o[0].insertAdjacentElement("afterend",n),!0;break;case"aboveProductForm":if(o&&o.length)return o[0].insertAdjacentElement("beforebegin",n),!0;break;case"aboveAtcButton":if(i)return i.insertAdjacentElement("beforebegin",n),!0;break;case"belowAtcButton":if(i)return i.insertAdjacentElement("afterend",n),!0;break;default:const e=document.querySelector(r);if(e)return e.insertAdjacentElement(t,n),!0;if(i)return i.insertAdjacentElement("beforebegin",n),!0}}else{const e=document.querySelector(r)??document.querySelector("#lb-dealeasy-block");if(e)return e.insertAdjacentElement("beforeend",n),!0}}return!1}catch(e){return console.error("utils.positionWidget : ",e),!1}},getProductAtcButton:()=>{const e=utils.getProductFormsOnPage();for(const t of e){const e=t.querySelector('button[type="submit"][name="add"], input[type="submit"][name="add"]');if(e)return e.parentElement}},getSetDifference:(e,t,r)=>e.filter((e=>!t.some((t=>t[r]===e[r])))),getSetUnion:(e,t,r)=>{const n=[...e,...t],o=new Map;return n.forEach((e=>{o.set(e[r],e)})),Array.from(o.values())},getSetIntersection:(e,t,r)=>e.filter((e=>t.some((t=>t[r]===e[r])))),disableOriginalFormAttributes:e=>{if(e&&e.length){const t=["input[name='id'][type='hidden']","input[name='product-id'][type='hidden']","input[name='quantity']"];return"object"==typeof dealeasyFormDefaultAttributes&&t.push(...dealeasyFormDefaultAttributes),e.forEach((e=>{t.forEach((t=>{e.querySelectorAll(t).forEach((e=>{e.setAttribute("disabled","true")}))}))})),!0}return!1},enableOriginalFormAttributes:e=>{if(e&&e.length){const t=["input[name='id'][type='hidden']","input[name='product-id'][type='hidden']","input[name='quantity']"];return"object"==typeof dealeasyFormDefaultAttributes&&t.push(...dealeasyFormDefaultAttributes),e.forEach((e=>{t.forEach((t=>{e.querySelectorAll(t).forEach((e=>{e.removeAttribute("disabled")}))}))})),!0}return!1},getFormAttributesAndProperties:e=>{try{const t=[],r=[];return[...utils.getProductFormProperties(e),...utils.getOtherDefaultFormInputs(e)].forEach((e=>{const n=e.name.match(/properties\[(.*?)\]/);n?t.push({name:n[1],value:e.value}):r.push({name:e.name,value:e.value})})),{productFormProperties:t,productFormAttributes:r}}catch(e){return console.error("utils.getFormAttributesAndProperties : ",e),!1}},getProductFormProperties:e=>{const t={},r=["input[name='id'][type='hidden']","input[name='product-id'][type='hidden']","input[name='quantity']","input[name='section-id'][type='hidden']","input[name='form_type'][type='hidden']","input[name='utf8'][type='hidden']","input[name=''][type='hidden']","input:not([name])[type='hidden']"];return e.forEach((e=>{e.querySelectorAll('input[type="hidden"]'+(r.length?`:not(${r.join(",")})`:"")).forEach((e=>{if(!e.disabled){const r=e.value;r&&(t[e.name.trim()]=r.trim())}}))})),Object.entries(t).map((([e,t])=>({name:e,value:t})))},getOtherDefaultFormInputs:e=>{if("object"==typeof dealeasyFormDefaultInputs&&dealeasyFormDefaultInputs.length){const t={};return e.forEach((e=>{dealeasyFormDefaultInputs.forEach((r=>{e.querySelectorAll(r).forEach((e=>{e&&e.name&&e.value&&(t[e.name.trim()]=e.value.trim())}))}))})),Object.entries(t).map((([e,t])=>({name:e,value:t})))}return[]}},__WEBPACK_DEFAULT_EXPORT__=utils}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](r,r.exports,__webpack_require__),r.exports}__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={},utils=__webpack_require__(413);const query={metaobjects:'{\n offersMetaobjects: metaobjects(type: "$app:dealeasy-vds", first: 250) {\n nodes {\n field(key: "discount") {\n value\n }\n }\n }\n setupMetaobjects: metaobjects(type: "$app:dealeasy-vdSetups", first: 250) {\n nodes {\n field(key: "setup") {\n value\n }\n }\n }\n shop {\n id\n moneyFormat\n }\n localization {\n country {\n currency {\n isoCode\n symbol\n }\n }\n }\n }',product:"{\n id\n handle\n title\n tags\n collections(first: 200) {\n nodes {\n id\n }\n }\n featuredImage {\n url(transform: {maxHeight: $imageResolution, maxWidth: $imageResolution})\n altText\n }\n totalInventory\n availableForSale\n isGiftCard\n variants(first: 250) {\n nodes {\n id\n title\n availableForSale\n compareAtPrice {\n amount\n currencyCode\n }\n image {\n url(transform: {maxHeight: $imageResolution, maxWidth: $imageResolution})\n }\n price {\n amount\n currencyCode\n }\n quantityAvailable\n currentlyNotInStock\n selectedOptions {\n name\n value\n }\n }\n }\n }",collectionProducts:"collection(id: $id) {\n id\n products(first: $first, after: $after) {\n nodes {\n id\n handle\n title\n tags\n collections(first: 200) {\n nodes {\n id\n }\n }\n featuredImage {\n url(transform: {maxHeight: $imageResolution, maxWidth: $imageResolution})\n altText\n }\n totalInventory\n availableForSale\n isGiftCard\n variants(first: 250) {\n nodes {\n id\n title\n availableForSale\n compareAtPrice {\n amount\n currencyCode\n }\n image {\n url(transform: {maxHeight: $imageResolution, maxWidth: $imageResolution})\n }\n price {\n amount\n currencyCode\n }\n quantityAvailable\n currentlyNotInStock\n selectedOptions {\n name\n value\n }\n }\n }\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n }",collection:" {\n id\n title\n handle\n image {\n url(transform: {maxHeight: $imageResolution, maxWidth: $imageResolution})\n altText\n }\n }",discountCodesMutate:"mutation updateCartCodes($id: ID!, $discountCodes: [String!]!) {\n cartDiscountCodesUpdate(cartId: $id, discountCodes: $discountCodes) {\n cart {\n id\n discountCodes {\n applicable\n code\n }\n }\n userErrors {\n code\n field\n message\n }\n warnings {\n code\n message\n target\n }\n }\n }"},src_query=query;async function triggerManualCartRefresh(){return window.dispatchEvent(new Event("lb-dealeasy-manual-cart-refresh")),"undefined"==typeof stopTriggerManualCartRefresh&&(await manualCartRefresh(),void 0!==window.pickeasy&&"function"==typeof window.loadSlots&&"undefined"!=typeof stopIntegrationWithPickeasy&&setTimeout((()=>window.loadSlots()),200),!0)}function manualCartRefresh(){return new Promise((e=>{let t=null,r=null;Promise.all([fetch("/cart.js").then((e=>e.json())).catch((e=>(console.log("Error fetching cart data",e),null))),fetch("/cart?sections=cart-drawer,variant-added,sections--23563316330762__cart-drawer",{method:"GET",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json"}}).then((e=>e.json())).catch((e=>(console.log("Error fetching cart sections",e),null)))]).then((([n,o])=>{t=n,r=o,function(t,r){try{document.dispatchEvent(new Event("apps:product-added-to-cart"))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("cart:refresh"))}catch(e){console.log("Error while updating cart",e)}try{document.documentElement.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0}))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("obsidian:upsell:refresh")),document.dispatchEvent(new CustomEvent("obsidian:upsell:open"))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new Event("theme:cart:init",{bubbles:!0}))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new Event("theme:cart:reload",{bubbles:!0}))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new Event("update_cart"))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("cart:build"))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("cart:open"))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("cart:update",{detail:{data:{}}}))}catch(e){console.log("Error while updating cart",e)}if(t)try{window.dispatchEvent(new CustomEvent("theme:product:add",{detail:{response:t,button:void 0},bubbles:!0}))}catch(e){console.log("Error while updating cart",e)}if("function"==typeof window.SLIDECART_UPDATE)try{window.SLIDECART_UPDATE((()=>window.SLIDECART_OPEN()))}catch(e){console.log("Error while updating cart",e)}if(void 0!==window.theme&&void 0!==window.theme.ajaxCart&&"function"==typeof window.theme.ajaxCart.update)try{window.theme.ajaxCart.update()}catch(e){console.log("Error while updating cart",e)}if("undefined"!=typeof theme&&void 0!==theme.Cart&&"function"==typeof theme.Cart.updateCart)try{theme.Cart.updateCart()}catch(e){console.log("Error while updating cart",e)}if(void 0!==window.theme&&void 0!==window.theme.MiniCart&&"function"==typeof window.theme.MiniCart.update)try{theme.MiniCart.update()}catch(e){console.log("Error while updating cart",e)}if("function"==typeof window.icartCartActivityEvent)try{window.icartCartActivityEvent()}catch(e){console.log("Error while updating cart",e)}if("function"==typeof window.updateMiniCartContents)try{window.updateMiniCartContents()}catch(e){console.log("Error while updating cart",e)}if("function"==typeof window.loadEgCartDrawer)try{window.loadEgCartDrawer()}catch(e){console.log("Error while updating cart",e)}if(void 0!==window.cart&&"function"==typeof window.cart.getCart&&"function"==typeof window.cart.openCartDropdown)try{window.cart.getCart(),window.cart.openCartDropdown()}catch(e){console.log("Error while updating cart",e)}if(void 0!==window.ajaxCart&&"function"==typeof window.ajaxCart.load)try{window.ajaxCart.load()}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("cart:refresh"))}catch(e){console.log("Error while updating cart",e)}try{document.documentElement.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0}))}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("apps:product-added-to-cart"))}catch(e){console.log("Error while updating cart",e)}try{const e=document.querySelector("m-cart-drawer");e&&"function"==typeof e.onCartDrawerUpdate&&e.onCartDrawerUpdate()}catch(e){console.log("Error while updating m-cart-drawer",e)}if(void 0!==window.HsCartDrawer&&"function"==typeof window.HsCartDrawer.updateSlideCart)try{if("undefined"!=typeof globalDebounce)globalDebounce("hscartdrawer",(function(){try{HsCartDrawer.updateSlideCart()}catch(e){console.log(e)}}),100);else try{HsCartDrawer.updateSlideCart()}catch(e){console.log(e)}}catch(e){console.log(e)}if(void 0!==window.HS_SLIDE_CART_OPEN&&"function"==typeof window.HS_SLIDE_CART_OPEN)if("undefined"!=typeof globalDebounce)globalDebounce("hscartdraweropen",(function(){try{window.HS_SLIDE_CART_OPEN()}catch(e){console.log(e)}}),100);else try{window.HS_SLIDE_CART_OPEN()}catch(e){console.log(e)}try{const e=document.getElementById("site-cart");null!==e&&e.show()}catch(e){console.log("Error while updating cart",e)}if("undefined"!=typeof CartJS&&"function"==typeof CartJS.getCart)try{CartJS.getCart()}catch(e){console.log("Error while updating cart",e)}if("undefined"!=typeof Shopify&&void 0!==Shopify.theme&&void 0!==Shopify.theme.jsAjaxCart&&"function"==typeof Shopify.theme.jsAjaxCart.updateView)try{Shopify.theme.jsAjaxCart.updateView(),setTimeout((()=>Shopify.theme.jsAjaxCart.showDrawer()),800)}catch(e){console.log("Error while updating cart",e)}try{const e=document.querySelector("cart-drawer")||document.querySelector("cart-notification")||document.querySelector("mini-cart");if(null!==e&&"function"==typeof e.renderContents){const r=e.getSectionsToRender?e.getSectionsToRender().map((e=>e.id)).join(","):"cart-drawer,cart-notification-product,cart-notification-button,cart-icon-bubble,header,header-mini-cart-content,header-mini-cart-footer,mini-cart,cart-icon-bubble,mobile-cart-icon-bubble";t&&fetch(`/cart?sections=${r}`,{method:"GET",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json"}}).then((e=>e.json())).then((r=>{try{if(t&&t.items){const n={sections:r,key:t.items[0]?.key,id:t.items[0]?.id};e.renderContents(n),e.classList.toggle("is-empty",0===t.items.length);const o=document.querySelector("#CartCount");o&&t.item_count&&(o.innerText=t.item_count)}else document.querySelector(".cart-count-bubble")?.remove()}catch(e){console.log("Error while updating cart",e)}})).catch((e=>console.log("Error while updating cart",e)))}}catch(e){console.log("Error while updating cart",e)}try{const e=document.querySelector("cart-drawer");e&&("function"==typeof e.cartRefreshHandler&&e.cartRefreshHandler(),"function"==typeof e.handleCartRender&&e.handleCartRender(),"function"==typeof e.open&&setTimeout((()=>e.open()),400),"function"==typeof e.openDrawer&&e.openDrawer(),"function"==typeof e.openMenuDrawer&&setTimeout((()=>e.openMenuDrawer()),500))}catch(e){console.log("Error while updating cart",e)}try{void 0!==window.ajaxCart&&"function"==typeof window.ajaxCart.load&&window.ajaxCart.load()}catch(e){console.log("Error while updating cart",e)}try{document.dispatchEvent(new CustomEvent("obsidian:upsell:refresh")),document.dispatchEvent(new CustomEvent("obsidian:upsell:open"))}catch(e){console.log("Error while updating cart",e)}try{const e=document.querySelector("cart-drawer");e&&"function"==typeof e.cartRefreshHandler&&(e.cartRefreshHandler(),"function"==typeof e.open&&e.open())}catch(e){console.log("Error while updating cart",e)}var n=document.getElementById("site-cart");if(null!==n)try{n.show()}catch(e){console.log("Error while updating cart",e)}if("undefined"!=typeof CartJS&&"function"==typeof CartJS.getCart)try{CartJS.getCart()}catch(e){console.log(e)}if(void 0!==window.SLIDECART_UPDATE&&void 0!==window.SLIDECART_OPEN)try{window.SLIDECART_UPDATE((()=>window.SLIDECART_OPEN()))}catch(e){bundlerConsole.log(e)}if("undefined"!=typeof Shopify&&void 0!==Shopify.theme&&void 0!==Shopify.theme.jsAjaxCart&&"function"==typeof Shopify.theme.jsAjaxCart.updateView)try{Shopify.theme.jsAjaxCart.updateView()}catch(e){console.log("Error while updating cart",e)}if(t&&r)try{const e={...t};e.sections=r.sections,document.dispatchEvent(new Event("variant:add",{bubbles:!0,detail:{items:e.items,cart:e}}))}catch(e){console.log("Error while updating cart",e)}try{const e=document.querySelector("cart-drawer")||document.querySelector("cart-notification");if(e&&"function"==typeof e.renderContents){const r=(e.getSectionsToRender?e.getSectionsToRender():[]).map((e=>e.id)).join(","),n=Shopify.routes.root??"/";t&&fetch(`${n}cart?sections=${r}`,{method:"GET",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json"}}).then((e=>e.clone().json())).then((r=>{try{const n={...r};if(t&&t.items.length>0){const o=document.querySelector('[name="id"]')?.value,i=t.items.find((e=>e.id===o))?.key||t.items[0].key,a=r[`cart-notification-product-${i}`];a&&(n["cart-notification-product"]=a),e.renderContents({sections:n,key:i}),e.classList.contains("is-empty")&&e.classList.remove("is-empty")}else document.querySelector(".cart-count-bubble")?.remove(),e.renderContents({sections:n})}catch(e){console.error("[Safe cart refresh failed]",e)}})).catch((e=>console.error("[Safe cart refresh failed]",e)))}}catch(e){console.error("[Safe cart refresh failed]",e)}e()}(t,r)}))}))}var config=__webpack_require__(384);const cartHandler={addToCartQueue:[],isProcessingAddToCart:!1,appliedDiscountCodes:[],getCart:async()=>{try{let e=await fetch(`https://${window.location.hostname}/cart.js`);if(e?.ok){let t=await e.json();if(t)return cartHandler.formatCart(t)}return}catch(e){return void console.error("fn.getCart",e)}},getStorefrontCart:async(e,t)=>{try{const r=await fetch(`https://${Shopify.shop}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:src_query.cart,variables:{cartId:e}})});if(r&&r.ok&&200===r.status){return(await r.json()).data.cart}return}catch(e){return void console.error("fn.getStorefrontCart",e)}},addToCart:async(e,t=!1)=>new Promise((r=>{cartHandler.addToCartQueue.push({items:e,isListenable:t,resolve:r}),cartHandler.isProcessingAddToCart||cartHandler.processAddToCartQueue()})),processAddToCartQueue:async()=>{if(0===cartHandler.addToCartQueue.length)return void(cartHandler.isProcessingAddToCart=!1);cartHandler.isProcessingAddToCart=!0;const{items:e,isListenable:t,resolve:r}=cartHandler.addToCartQueue.shift();try{const n=await fetch(`https://${window.location.hostname}/cart/add.js${t?"":"?src=dealeasy"}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify({items:e})});if(n){const o=await n.json();window.dispatchEvent(new CustomEvent("lb-dealeasy-add-to-cart",{detail:{...o,isListenable:t,items:e}})),200===n.status?r({success:!0,items:cartHandler.formatCartItems(o.items)}):r({success:!1,message:o.description||"Can't add product to cart",res:n})}else r({success:!1,message:"Can't add product to cart",res:n})}catch(e){console.error("fn.addToCart : ",e),r({success:!1,message:"Error while adding product on cart",res:e})}setTimeout((()=>{cartHandler.processAddToCartQueue()}),10)},updateCart:async(e,t=!1)=>{try{const r=await fetch(`https://${window.location.hostname}/cart/update.js${t?"":"?src=dealeasy"}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify({updates:e})});if(r&&r.ok&&200===r.status){const n=await r.json();return window.dispatchEvent(new CustomEvent("lb-dealeasy-update-cart",{detail:{...n,isListenable:t,items:e}})),{success:!0,...cartHandler.formatCart(n)}}return{success:!1,message:"Can't change cart",res:r}}catch(e){return console.error("fn.updateCart : ",e),{success:!1,message:"Can't change cart",res:e}}},changeCart:async(e,t=!1)=>{try{const r=await fetch(`https://${window.location.hostname}/cart/change.js${t?"":"?src=dealeasy"}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)});if(r&&r.ok&&200===r.status){const n=await r.json();return window.dispatchEvent(new CustomEvent("lb-dealeasy-change-cart",{detail:{...n,isListenable:t,item:e}})),{success:!0,...cartHandler.formatCart(n)}}return{success:!1,message:"Can't change cart",res:r}}catch(e){return console.error("fn.changeCart : ",e),{success:!1,message:"Can't change cart",res:e}}},appendDiscountCodesOnCartForm:()=>{try{function e(e,t){const r=new URL(`https://${window.location.hostname}${e}`);return t?.length&&r.searchParams.set("discount",t.join(",")),r.pathname+r.search}if(cartHandler.appliedDiscountCodes.length){return document.querySelectorAll("form[action='/cart'][method='post']").forEach((t=>{const r=e(t.action,cartHandler.appliedDiscountCodes);if(r!==t.getAttribute("action"))return t.setAttribute("action",r),t.setAttribute("lb-dealeasy-cart-action",r),!0})),!0}return!1}catch(t){return console.error("fn.appendDiscountCodesOnCartForm : ",t),!1}},getDiscountCodesFromStorage:(e=[],t)=>{try{if(utils.A.isNotPrivateTab()){const r=JSON.parse(sessionStorage.getItem("dealeasy-discount-code-sources")??"{}");e.length?r[t]=e:delete r[t],sessionStorage.setItem("dealeasy-discount-code-sources",JSON.stringify(r));const n=Object.entries(r).reduce(((e,[r,n])=>"selleasy"===t?[...n,...e]:[...e,...n]),[]);return[...new Set(n)].filter(Boolean)}return e.filter(Boolean)}catch(e){return console.error("fn.getDiscountCodesFromStorage : ",e),[]}},cartValueGoalsDiscountCodes:[],volumeDiscountCodes:[],bogoDiscountCodes:[],gwpDiscountCodes:[],setDiscountCodes:(e,t=[])=>{"cartValueGoals"===e?cartHandler.cartValueGoalsDiscountCodes=t:"volumeDiscounts"===e?cartHandler.volumeDiscountCodes=t:"bogo"===e?cartHandler.bogoDiscountCodes=t:"gwp"===e&&(cartHandler.gwpDiscountCodes=t)},getDiscountCodes:()=>{if(utils.A.isNotPrivateTab()){const e=JSON.parse(sessionStorage.getItem("dealeasy-discount-codes")??"[]"),t=[...new Set([...cartHandler.bogoDiscountCodes,...cartHandler.gwpDiscountCodes,...cartHandler.cartValueGoalsDiscountCodes,...cartHandler.volumeDiscountCodes])];return t.some((t=>!e.includes(t)))?t:[]}},applyDiscountCodesToCart:async(e,t,r,n)=>{try{if(t){utils.A.log("Mutating discount codes",{src:t,codes:e}),"selleasy"===t&&await utils.A.customWait(500);const o=cartHandler.getDiscountCodesFromStorage(e,t),i=r||(await cartHandler.getCart()).id,a=window.lbDealeasy.myShopifyDomain;if(n=n||await src_setupHandler.getStoreFrontAccessToken(a),o&&o.length&&i&&n){const e=await fetch(`https://${a}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":n},body:JSON.stringify({query:src_query.discountCodesMutate,variables:{id:i,discountCodes:o}})});if(e&&e.ok&&200===e.status){const t=(await e.json())?.data?.cartDiscountCodesUpdate;if(t.userErrors.length||t.warnings.length)return utils.A.errorLog("Cart code discount update failed",t),!1;const r=t.cart.discountCodes.filter((e=>e.applicable)).map((e=>e.code));return cartHandler.appliedDiscountCodes=r,cartHandler.appendDiscountCodesOnCartForm(),utils.A.isNotPrivateTab()&&sessionStorage.setItem("dealeasy-discount-codes",JSON.stringify(o)),r.length>0}}}return!1}catch(e){return console.error("fn.applyDiscountCodesToCart : ",e),!1}},getCartPayloadFromRequest:(e,t)=>{try{if(e&&t&&["/cart/update","/cart/change"].some((t=>e.includes(t)))){const e=JSON.parse(t);if(e&&e.token&&e.items)return cartHandler.formatCart(e)}return}catch(e){return void console.error("fn.getCartPayloadFromRequest",e)}},getCartLineItemProducts:async(e,t,r)=>{try{if(e&&e.length){const n=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-cart-products")||"[]"):[],o=e.filter((e=>!n.some((t=>t.id===e.productGid))));if(o&&o.length){const e=await src_setupHandler.getProducts(t,r,"ID",o.map((e=>e.productGid)));e&&e.length&&n.push(...e)}return sessionStorage.setItem("dealeasy-cart-products",JSON.stringify(n)),e.map(((e,t,r)=>{const o=n.find((t=>t.id===e.productGid)),i=o?.variants.find((t=>t.id===e.id));if(o){const n=r.filter((e=>o.id===e.productGid)).reduce(((e,t)=>e+t.quantity),0);return{index:t,id:o.id,totalProductQuantity:n,lineItemQuantity:e.lineItemQuantity,lineSubTotalPrice:e.lineSubTotalPrice,lineTotalPrice:e.lineTotalPrice,price:i.price,tags:o.tags,collections:o.collections,variants:o.variants,currentVariant:{id:e.id,title:e.title},variantId:e.variantId,handle:o.handle,properties:e.properties,key:e.key,alreadyHasOtherAppDiscount:e.lineLevelDiscountsTitles,isSellingPlanAllocated:e.isSellingPlanAllocated}}return null})).filter(Boolean)}return[]}catch(e){return console.error("fn.getCartLineItemProducts",e),[]}},formatCart:e=>{try{let t=document.cookie.match("(^|;)\\s*cart\\s*=\\s*([^;]+)")?.pop()||void 0,r=t&&t.includes(e.token)?`gid://shopify/Cart/${decodeURIComponent(t)}`:`gid://shopify/Cart/${e.token}`;return lbDealeasy.cartId=r,{id:r,attributes:e.attributes,items:cartHandler.formatCartItems(e.items),itemCount:e.item_count,orderDiscounts:e.cart_level_discount_applications?.map((e=>({title:e.title,discountedAmount:e.total_allocated_amount}))),productDiscounts:[].concat(...e.items.map((e=>e.line_level_discount_allocations||[]))).map((e=>({title:e.discount_application.title,discountedAmount:e.discount_application.total_allocated_amount}))),subTotal:e.original_total_price/100,total:e.total_price/100}}catch(e){return void console.error("fn.formatCart : ",e)}},formatCartItems:e=>{try{return e.map(((e,t)=>JSON.parse(JSON.stringify({index:t,goalValue:e.properties&&e.properties.__dealeasy_gift_product?utils.A.getCartGoalPrice(e.properties.__dealeasy_gift_product):void 0,handle:e.handle,productGid:`gid://shopify/Product/${e.product_id}`,productId:e.product_id,id:`gid://shopify/ProductVariant/${e.variant_id}`,variantId:e.variant_id,lineItemQuantity:e.quantity,properties:e.properties,price:e.presentment_price,lineSubTotalPrice:e.original_line_price/100,lineTotalPrice:e.line_price/100,key:e.key,isGiftCard:e.gift_card,lineLevelDiscountsTitles:e.line_level_discount_allocations.map((e=>e.discount_application.title)),isSellingPlanAllocated:e.selling_plan_allocation?.selling_plan?.id??!1}))))}catch(e){return console.error("fn.formatCartItems : ",e),[]}},refreshCart:async()=>{try{return window.location.href.includes("/cart")?window.location.reload():await triggerManualCartRefresh(),!0}catch(e){return!1}},postAtcCartRefresh:e=>new Promise(((t,r)=>{try{switch(e){case"refresh_cart":triggerManualCartRefresh(),t(!0);break;case"reload_page":setTimeout((()=>{window.location.reload(),t(!0)}),500);break;case"redirect_to_checkout":setTimeout((()=>{const e=utils.A.getRootRoute();window.location=e&&"/"!==e?`https://${window.location.hostname}${e}cart/checkout`:`https://${window.location.hostname}/cart/checkout`,t(!0)}),500);break;default:setTimeout((()=>{let e=utils.A.getRootRoute();window.location=e&&"/"!==e?`https://${window.location.hostname}${e}cart`:`https://${window.location.hostname}/cart`,t(!0)}),800)}}catch(e){console.error("fn.postAtcCartRefresh : ",e),r(e)}}))},src_cartHandler=cartHandler,offersHandler={getOffers:async(e,t,r,n)=>{try{const o=t.map((e=>offersHandler.formatOffer(e))).filter(Boolean),i=await offersHandler.filterOffers(e,o,r,n);return i&&i.length?{discounts:i.filter((e=>"DISCOUNT"===e.offer&&"VOLUME_DISCOUNT"===e.discountCategory)),cartValueGoals:i.filter((e=>"DISCOUNT"===e.offer&&["SHIPPING_DISCOUNT","FREE_GIFT_DISCOUNT","ORDER_DISCOUNT"].includes(e.discountCategory))),bundles:i.filter((e=>"BUNDLE"===e.offer)),recommendations:i.filter((e=>"RECOMMENDATION"===e.offer)),bogo:i.filter((e=>"DISCOUNT"===e.offer&&"BOGO_DISCOUNT"===e.discountCategory)),hasCodeDiscounts:i.some((e=>"DISCOUNT"===e.offer&&e.isCodeDiscount)),gwp:i.filter((e=>"DISCOUNT"===e.offer&&"GIFT_WITH_PRODUCT_DISCOUNT"===e.discountCategory))}:void 0}catch(e){return void console.error("fn.getOffers: ",e)}},formatOffer:e=>{try{const t=Shopify.locale;if("BUNDLE"===e.offer)return{...e,componentsType:e.componentsType??"products",widgetType:e.widgetType??"widget#bundle",translation:e.translations[t]??e.translations.default};if("RECOMMENDATION"===e.offer)return{...e,widgetType:e.widgetType??"widget#recommendation"};{const r=JSON.parse(e.metafields.find((e=>e&&e.key&&e.key.includes("lb-dealeasy-config")))?.value??null),n=JSON.parse(e.metafields.find((e=>e&&e.key&&e.key.includes("dealeasy-translations")))?.value??null);if(r&&offersHandler.isActiveDiscount(e.startsAt,e.endsAt)){const o={...r,offer:"DISCOUNT",createdAt:e.createdAt,translation:n?n[t]??n.default:null,discountId:e.discountId,title:e.title,combinesWith:e.combinesWith,isCodeDiscount:e.discountId.includes("DiscountCode"),discountCode:e.discountId.includes("DiscountCode")?e.discountCode:null,currencyCode:r.currencyCode,currencyFormat:r.currencyFormat,discountsToB2BCustomers:!1!==r.discountsToB2BCustomers,customerSelectionType:r.customerSelectionType??"ALL",customerSelection:r.customerSelection??[],autoApplyCodeDiscount:r.autoApplyCodeDiscount??!0};return["SHIPPING_DISCOUNT","FREE_GIFT_DISCOUNT","ORDER_DISCOUNT"].includes(r.discountCategory)?{...o,widgetType:r.widgetType??"widget#cvgProgressBar",goalType:r.goalType,cartGoals:r.cartGoals,discountCategory:r.discountCategory,appliesTo:r.appliesTo??"ALL_COUNTRIES",countriesToInclude:r.countriesToInclude??[],countriesToExclude:r.countriesToExclude??[]}:"BOGO_DISCOUNT"===r.discountCategory?{...o,widgetType:e.widgetType??"widget#bogo",exclusionType:r.exclusionType??"PRODUCTS",enableExclusion:r.enableExclusion??!1,excludedProductIds:r.excludedProductIds??[],excludedCollectionIds:r.excludedCollectionIds??[],excludedTags:r.excludedTags??[]}:"GIFT_WITH_PRODUCT_DISCOUNT"===r.discountCategory?{...o,widgetType:e.widgetType??"widget#giftWithProduct"}:{...o,type:r.type,widgetType:r.widgetType??"widget#vdtable",fixedQuantityDiscount:r.fixedQuantityDiscount??!1,selectorToBuyMinQty:r.selectorToBuyMinQty??!1,minQtySelectorIsDefault:r.minQtySelectorIsDefault??!1,enableExclusion:r.enableExclusion??!1,excludedProductIds:r.excludedProductIds??[],discountsToSubscriptionProducts:(r.discountsToSubscriptionProducts??!1)||(r.appliesOnSubscription??!1),excludedCollectionIds:r.excludedCollectionIds??[],excludedTags:r.excludedTags??[],exclusionType:r.exclusionType??"PRODUCTS",discountCategory:"VOLUME_DISCOUNT"}}}return}catch(e){return void console.error("fn.formatOffers: ",e)}},filterOffers:async(e,t,r,n)=>{try{const o=t.map((e=>e.customerSelectionType&&"SPECIFIC_SEGMENTS"===e.customerSelectionType?e.customerSelection:[])).flat();let i;o&&o.length&&n&&n.id&&(utils.A.log("Have segments based offers : ",o),i=await src_setupHandler.getCustomerSegmentsMembership(e,n.id,o));return t.filter((e=>{if("BUNDLE"===e.offer)return!0;if("RECOMMENDATION"===e.offer)return e.isActive;if(r)return e.discountsToB2BCustomers;if("ALL"===e.customerSelectionType)return!0;if("SPECIFIC_CUSTOMERS"===e.customerSelectionType&&n&&n.id)return e.customerSelection.includes(n.id);if("SPECIFIC_SEGMENTS"===e.customerSelectionType&&i&&n&&n.id){const t=i.segmentMemberships.filter((e=>e.isMember)).map((e=>e.segmentId));return e.customerSelection.some((e=>t.includes(e)))}return!("SPECIFIC_TAGS"!==e.customerSelectionType||!n||!n.tags)&&e.customerSelection.some((e=>n.tags.toLowerCase().includes(e.toLowerCase())))}))}catch(e){return void console.error("fn.filterOffers: ",e)}},isActiveDiscount:(e,t)=>{if("function"==typeof dayjs){const r=dayjs(),n=dayjs(e),o=t?dayjs(t):null;return r.isAfter(n)&&(!o||r.isBefore(o))}return!1},getMaximumProductDiscount:(e,t,r=!1)=>{try{const n=e=>{const r=e.enableExclusion?offersHandler.filterProductsByExclusion(e,[t]):[t];if(!r.length)return!1;switch(e.appliesTo){case"PRODUCTS":return e.selectedProductIds?.some((e=>r.some((t=>t.id===e||t.id.includes(e)))));case"VARIANTS":return r.some((t=>e.selectedVariantIds?.includes(t.currentVariant?.id)));case"TAGS":const t=e.selectedTags&&e.selectedTags.length?e.selectedTags.map((e=>e.toLowerCase())):[];return r.some((e=>e.tags.some((e=>t.includes(e.toLowerCase())))));case"COLLECTIONS":return e.selectedCollectionIds?.some((e=>r.some((t=>t.collections.includes(e)))));case"ALL":return!0;default:return!1}},o=e.filter(n).reverse();if(o&&o.length){const e=o.reduce(((e,t)=>(t.tiers?.[t.tiers.length-1]?.value??0)>(e?e.tiers?.[e.tiers.length-1]?.value??0:0)?t:e),null);if(r&&e&&"ALL"===e.applicationStrategy){const r=e.tiers?.[0]?.quantity??0;if(r&&t.quantity{try{const r=[];for(const n of e){const e=offersHandler.getMaximumProductDiscount(t,n,!0);if(e&&(r.includes(e.discountCode)||r.push(e.discountCode)),5===r.length)break}return r.filter(Boolean)}catch(e){return void console.error("fn.getDiscountCodesForCartProducts : ",e)}},getCartLinePromotions:(e,t,r)=>{try{const n=[],o=e.map((e=>offersHandler.getMaximumProductDiscount(t,e))).filter((e=>e&&e.isSupportedSellingPlan)),i=o.filter((e=>e&&"MAXIMUM"===e.applicationStrategy));i.forEach((e=>{const t=i.filter((t=>t.id===e.id)).reduce(((e,t)=>e+t.product.lineItemQuantity),0),r=e.tiers.sort(((e,t)=>e.quantity-t.quantity)).find((e=>e.quantity>t));if(r){const o=e.product;n.push({discount:{id:e.id,discountValue:r.value,discountType:e.type,volumeDiscountType:"widget#vdcards"===e.widgetType?"QUANTITY_SELECTOR_DISCOUNTS":"TABLE_DISCOUNTS"},cartLineItem:{id:o.id,variantId:o.currentVariant.id,handle:o.handle,key:o.key,index:o.index,quantityToQualify:r.quantity-t,quantity:o.lineItemQuantity}})}}));const a=o.filter((e=>e&&"ALL"===e.applicationStrategy));return a.forEach((e=>{let t=0;t="VARIANTS"===e.appliesTo?e.product.lineItemQuantity:a.filter((t=>t.product.id===e.product.id)).reduce(((e,t)=>e+t.product.lineItemQuantity),0);const r=e.tiers.sort(((e,t)=>e.quantity-t.quantity)).find((e=>e.quantity>t));if(r){const o=e.product;n.push({discount:{id:e.id,discountValue:r.value,discountType:e.type,volumeDiscountType:"widget#vdcards"===e.widgetType?"QUANTITY_SELECTOR_DISCOUNTS":"TABLE_DISCOUNTS"},cartLineItem:{id:o.id,variantId:o.currentVariant.id,handle:o.handle,key:o.key,index:o.index,quantityToQualify:r.quantity-t,quantity:o.lineItemQuantity}})}})),n.sort(((e,t)=>e.cartLineItem.index-t.cartLineItem.index)).filter((e=>"ALL_DISCOUNTS"===r||e.discount.volumeDiscountType===r))}catch(e){return void console.error("fn.getCartLinePromotions : ",e)}},getBundleComponents:async(e,t,r,n=[],o,i=50,a=null)=>{try{const s=[];let d={cursor:null,hasNextPage:!1,alreadyQueriedItems:[]};if("collections"===o){const o=Array.from(new Set(r.flatMap((e=>e.collections)))).filter((e=>!n.includes(e))),c=await src_setupHandler.getPaginatedCollectionProducts(e,t,o,n,i,a);if(c&&c.products){const e=r.map((e=>({...e,products:c.products.filter((t=>e.collections.some((e=>t.collections.includes(e)))))})));s.push(...e),d=c.pagination}}else{const o=Array.from(new Set(r.flatMap((e=>e.products.map((e=>e.id)))))),c=await src_setupHandler.getPaginatedProducts(e,t,o,n,i,a);if(c&&c.products){const e=r.map((e=>({...e,products:e.products.map((e=>{const t=c.products.find((t=>t.id===e.id));if(!t)return null;const r=e.variants.map((e=>t.variants.find((t=>t.id===e)))).filter(Boolean);return r.length?{...t,variants:r}:null})).filter(Boolean)})));s.push(...e),d=c.pagination}}return s.length?{components:s,pagination:d}:void 0}catch(e){return void console.error("fn.getBundleComponents : ",e)}},getFormattedBundle:(e,t)=>{try{return{id:t.id,handle:t.handle,title:t.title,onlineStoreUrl:t.onlineStoreUrl,translation:e.translation,trackChildProductInventory:e.trackChildProductInventory,componentsType:e.componentsType??"products",components:e.components,bundleType:e.bundleType??"FIXED_PRICE_BUNDLE",discountType:e.discountType??"NONE",bundleOptions:e.bundleOptions.map((e=>t.variants.find((t=>t.id===e.srcVariantId))?{quantity:e.quantity,srcVariantId:e.srcVariantId,value:e.value}:null)).filter(Boolean)}}catch(e){return void console.error("fn.getFormattedBundle : ",e)}},getCartGoalValues:async(e,t,r,n,o)=>{try{const{countryCode:i,currencyRate:a,currencyCode:s}=utils.A.getStoreCurrencyAndCountry(),d=offersHandler.getCombinableCartValueGoals(e,t.orderDiscounts&&t.orderDiscounts.length>0,t.productDiscounts&&t.productDiscounts.length>0),[c,l,u]=await Promise.all([offersHandler.getShippingGoals(d.filter((e=>"SHIPPING_DISCOUNT"===e.discountCategory)),i,a,s),offersHandler.getFreeGiftGoals(d.filter((e=>"FREE_GIFT_DISCOUNT"===e.discountCategory)),r,n,o,i,a,s),offersHandler.getOrderGoals(d.filter((e=>"ORDER_DISCOUNT"===e.discountCategory)),i,a,s)]);return[...c,...l,...u].sort(((e,t)=>e.goalValue-t.goalValue))}catch(e){return void console.error("fn.getCartGoalValues : ",e)}},getCombinableCartValueGoals:(e,t,r)=>{try{const n=[];return e.forEach((e=>{let o=!1;const i=n.find((e=>"ORDER_DISCOUNT"===e.discountCategory)),a=n.find((e=>"FREE_GIFT_DISCOUNT"===e.discountCategory));switch(e.discountCategory){case"SHIPPING_DISCOUNT":o=e.combinesWith.orderDiscounts?!i||i.combinesWith.shippingDiscounts:!t,o&&(o=e.combinesWith.productDiscounts?!a||a.combinesWith.shippingDiscounts:!r);break;case"FREE_GIFT_DISCOUNT":o=e.combinesWith.orderDiscounts?!i||i.combinesWith.productDiscounts:!t;break;case"ORDER_DISCOUNT":o=e.combinesWith.productDiscounts?!a||a.combinesWith.orderDiscounts:!r}o&&n.push(e)})),n}catch(e){return console.error("fn.getCombinableCartValueGoals : ",e),[]}},getShippingGoals:(e,t,r,n)=>{try{if(e&&e.length){const o=e.map((e=>offersHandler.isApplicableCartGoal(e,t)?{title:e.title.replace("DE-",""),discountId:e.discountId,shippingCartGoals:e.cartGoals.map(((t,o)=>({id:`cart-goal-${o}`,offer:"DISCOUNT",discountCategory:"SHIPPING_DISCOUNT",title:e.title.replace("DE-",""),discountId:e.discountId,currencyCode:e.currencyCode,currencyFormat:e.currencyFormat,isCodeDiscount:e.isCodeDiscount,discountCode:e.discountCode,offerType:e.offerType,goalValue:e.currencyCode===n?Number(t.goalValue):Number(t.goalValue)*r,offerValue:Number(t.offerValue),translation:e.translation,widgetType:e.widgetType,considerCartTotal:e.useTotalPriceForShipping??!1,excludeGiftCards:e.excludeGiftCards??!1,autoApplyCodeDiscount:e.autoApplyCodeDiscount??!0}))),maxOfferValue:e.cartGoals.reduce(((e,t)=>Math.max(e,Number(t.offerValue))),0)}:null)).filter(Boolean).sort(((e,t)=>t.maxOfferValue-e.maxOfferValue)).sort(((e,t)=>dayjs().unix(t.createdAt)-dayjs().unix(e.createdAt)));if(o&&o.length){const e=o.find((e=>"SPECIFIC_COUNTRIES"===e.appliesTo));return e?e.shippingCartGoals:o[0].shippingCartGoals}}return[]}catch(e){return console.error("fn.getShippingGoals : ",e),[]}},getFreeGiftGoals:async(e,t,r,n,o,i,a)=>{try{const s=e.filter((e=>offersHandler.isApplicableCartGoal(e,o))).sort(((e,t)=>dayjs().unix(t.createdAt)-dayjs().unix(e.createdAt)));if(s&&s.length){const e=s.find((e=>"SPECIFIC_COUNTRIES"===e.appliesTo)),d=e||s[0];if(d&&d.cartGoals&&d.cartGoals.length){const e=d.cartGoals.flatMap((e=>e.offerValue.map((e=>e))));let s=[];const c=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-gift-products")||"{}"):void 0;if(c&&c.productVariants&&dayjs().diff(dayjs.unix(c.createdAt),"minutes")<5){e.flatMap((e=>e.variants)).every((e=>c.productVariants.some((t=>t.id===e))))&&(s=c.productVariants)}if(!s.length){const e=d.cartGoals.flatMap((e=>e.offerValue.map((e=>e.id)))),n=await src_setupHandler.getProducts(t,r,"ID",Array.from(new Set(e)));n&&n.length&&(utils.A.isNotPrivateTab()&&sessionStorage.setItem("dealeasy-gift-products",JSON.stringify({productVariants:n.flatMap((e=>e.variants)),createdAt:dayjs().unix()})),s=n.flatMap((e=>e.variants)))}if(s&&s.length){const e=[],t=d.appliesTo&&"SPECIFIC_COUNTRIES"===d.appliesTo?`-${o}`:"";return window.dealeasyRemoveNotEligibleGift=d.removeNotEligibleGift,d.cartGoals.forEach((r=>{const o=d.currencyCode===n?Number(r.goalValue):Number(r.goalValue)/i,c=r.offerValue.flatMap((e=>e.variants)).map((e=>s.find((t=>t.id===e&&t.availableForSale)))).filter(Boolean);c&&c.length&&e.push({id:`${o}-${n}${t}`,lineItemProperty:`${o}-${n}${t}`,offer:"DISCOUNT",discountCategory:"FREE_GIFT_DISCOUNT",title:d.title.replace("DE-",""),discountId:d.discountId,currencyCode:d.currencyCode,currencyFormat:d.currencyFormat,isCodeDiscount:d.isCodeDiscount,discountCode:d.discountCode,translation:d.translation,widgetType:d.widgetType,goalValue:d.currencyCode===a?Number(r.goalValue):Number(r.goalValue)*i,offerValue:c,offerType:"PRODUCT_VARIANTS",addProductAgainIfRemoved:d.addProductAgainIfRemoved,removeNotEligibleGift:d.removeNotEligibleGift,freeGiftAdditionType:d.freeGiftAdditionType??"AUTOMATIC",giftsProvidingMode:d.giftsProvidingMode??"SINGLE",excludeGiftCards:d.excludeGiftCards??!1,autoApplyCodeDiscount:d.autoApplyCodeDiscount??!0})})),e}}}return[]}catch(e){return console.error("fn.getFreeGiftGoals : ",e),[]}},getOrderGoals:(e,t,r,n)=>{try{if(e&&e.length){const o=e.map((e=>offersHandler.isApplicableCartGoal(e,t)?{title:e.title.replace("DE-",""),discountId:e.discountId,orderGoals:e.cartGoals.map(((t,o)=>({id:`cart-goal-${o}`,offer:"DISCOUNT",discountCategory:"ORDER_DISCOUNT",title:e.title.replace("DE-",""),discountId:e.discountId,currencyCode:e.currencyCode,currencyFormat:e.currencyFormat,isCodeDiscount:e.isCodeDiscount,discountCode:e.discountCode,goalValue:e.currencyCode===n?Number(t.goalValue):Number(t.goalValue)*r,offerType:e.offerType,offerValue:Number(t.offerValue),translation:e.translation,widgetType:e.widgetType,excludeGiftCards:e.excludeGiftCards??!1,autoApplyCodeDiscount:e.autoApplyCodeDiscount??!0}))),maxOfferValue:e.cartGoals.reduce(((e,t)=>Math.max(e,Number(t.offerValue))),0)}:null)).filter(Boolean).sort(((e,t)=>t.maxOfferValue-e.maxOfferValue)).sort(((e,t)=>dayjs().unix(t.createdAt)-dayjs().unix(e.createdAt)));if(o&&o.length){const e=o.find((e=>"SPECIFIC_COUNTRIES"===e.appliesTo));return e?e.orderGoals:o[0].orderGoals}}return[]}catch(e){return console.error("fn.getOrderGoals : ",e),[]}},isApplicableCartGoal:(e,t)=>{try{return"SPECIFIC_COUNTRIES"!==e.appliesTo?!e.countriesToExclude||!e.countriesToExclude.includes(t):!(!e.countriesToInclude||!e.countriesToInclude.includes(t))}catch(e){return console.error("fn.isApplicableCartGoal : ",e),!1}},getExistingGiftGoals:(e=[])=>{try{return e.filter((e=>1===e.lineItemQuantity&&e.properties&&Object.keys(e.properties).some((t=>"__dealeasy_gift_product"===t&&e.properties.__dealeasy_gift_product)))).map((e=>({goalValue:utils.A.getCartGoalPrice(e.properties.__dealeasy_gift_product),...e})))}catch(e){return console.error("fn.getExistingGiftProducts : ",e),[]}},getEligibleGiftGoals:(e,t,r)=>{try{if("MULTIPLE"===r){const r=e.reverse().filter((e=>e.goalValue<=t));if(r&&r.length)return r}else{const r=e.reverse().find((e=>e.goalValue<=t));if(r)return[r]}return[]}catch(e){return console.error("fn.getEligibleGiftProducts : ",e),[]}},removeNotEligibleProducts:async(e,t,r,n,o,i=!1,a=[])=>{try{if(t&&t.length){const s={},d=a.length>0&&offersHandler.isOtherCountryGiftsInCart(t,a[0].lineItemProperty);if(d&&utils.A.log("other country gifts in cart : ",d),r||i||d){t.forEach((e=>{s[e.key]=0}));const e=await src_cartHandler.updateCart(s);return e&&e.success?(offersHandler.removeRemovedProductsFromStorage(t),{success:!0,productsWithRemovedGiftAttributes:[]}):void 0}{const r=n+t.reduce(((e,t)=>e+t.price),0),i=offersHandler.getEligibleGiftGoals(e,r,o),d=utils.A.getSetDifference(i,a,"goalValue");if(d&&d.length){t.forEach((e=>{s[e.key]=0}));const e=await src_cartHandler.updateCart(s);return e&&e.success?(offersHandler.removeRemovedProductsFromStorage(t),{success:!0,productsWithRemovedGiftAttributes:[]}):void 0}{let e;const r=[];for(const n of t){const t=e&&e.items?e.items.find((e=>e.variantId===n.variantId&&e.properties.__dealeasy_gift_product))?.key:n.key;t&&(e=await src_cartHandler.changeCart({id:t,properties:{__dealeasy_gift_product:""}}),e&&r.push(n))}return r&&r.length?(offersHandler.removeRemovedProductsFromStorage(t),{success:!0,productsWithRemovedGiftAttributes:r}):void 0}}}return}catch(e){return void console.error("fn.removeNotEligibleProducts : ",e)}},getModifiedUnclaimedProducts:(e,t,r)=>{try{let n=utils.A.getSetUnion(e,t,"goalValue");return utils.A.getSetDifference(n,r,"goalValue")}catch(e){return console.error("fn.getModifiedUnclaimedProducts : ",e),[]}},removeRemovedProductsFromStorage:e=>{try{if(utils.A.isNotPrivateTab()){const t=JSON.parse(sessionStorage.getItem("dealeasy-added-gift-goals")||"[]"),r=e.map((e=>e.properties.__dealeasy_gift_product)),n=t.filter((e=>!r.includes(e)));return sessionStorage.setItem("dealeasy-added-gift-goals",JSON.stringify(n)),!0}return!1}catch(e){return console.error("fn.removeRemovedProductsFromStorage : ",e),!1}},isOtherCountryGiftsInCart:(e,t)=>{try{const[r,n,o]=t.split("-");if(o){return e.some((e=>{const[t,r,n]=e.properties.__dealeasy_gift_product.split("-");return n!==o}))}return e.some((e=>{const[t,r,n]=e.properties.__dealeasy_gift_product.split("-");return void 0!==n}))}catch(e){return console.error("fn.isOtherCountryGiftsInCart : ",e),!1}},getEligibleProductsToAdd:(e,t)=>{try{const r=(utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-added-gift-goals")||"[]"):[]).map((e=>utils.A.getCartGoalPrice(e))),n=[],o=[];return e.forEach((e=>{r.includes(e.goalValue)?t?n.push(e):o.push(e):n.push(e)})),{eligibleGoalsToAdd:n,unClaimedProducts:o}}catch(e){return console.error("fn.getEligibleProductsToAdd : ",e),{eligibleGoalsToAdd:[],unClaimedProducts:[]}}},addProductsToCart:async(e,t=!1)=>{try{const r=await src_cartHandler.addToCart(e,t);if(utils.A.isNotPrivateTab()&&r.success){const t=e.map((e=>e.properties.__dealeasy_gift_product)),r=JSON.parse(sessionStorage.getItem("dealeasy-added-gift-goals")||"[]");sessionStorage.setItem("dealeasy-added-gift-goals",JSON.stringify(Array.from(new Set([...r,...t]))))}return r}catch(e){return console.error("fn.addProductsToCart : ",e),!1}},checkProductsSync:(e,t,r)=>{try{const n=e.map((e=>e.productId)),o={shopifyRecommendations:[],manualRecommendations:[]},i=r.recommendationType,a=t?.shopifyRecommendations?.map((e=>e.cartItemId))||[],s=t?.manualRecommendations?.map((e=>e.id))||[];switch(i){case"SHOPIFY":o.shopifyRecommendations=Array.from(new Set(n.filter((e=>!a.includes(e)))));break;case"MANUAL":o.manualRecommendations=Array.from(new Set(r?.selectedItems?.filter((e=>!s.includes(e))))||[]).map((e=>e.split("/").pop()));break;case"HYBRID":const e=new Set(n.filter((e=>!a.includes(e)))),t=new Set(r?.selectedItems?.filter((e=>!s.includes(e)))||[]);o.shopifyRecommendations=Array.from(e),o.manualRecommendations=Array.from(t).map((e=>e.split("/").pop()))}return o}catch(e){return console.error("fn.checkProductsSync : ",e),[]}},fetchRecommendations:async(e,t,r,n)=>{try{let o=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-recommendations")||"{}"):{};(o.shopifyRecommendations?.length&&o.shopifyRecommendations[0]?.variants?.currencyCode!==Shopify.currency||o.manualRecommendations?.length&&o.manualRecommendations[0]?.currencyCode!==Shopify.currency)&&(o={shopifyRecommendations:[],manualRecommendations:[]});const i={shopifyRecommendations:o?.shopifyRecommendations||[],manualRecommendations:o?.manualRecommendations||[]},a=offersHandler.checkProductsSync(r,i,n);let s=[],d=[];"SHOPIFY"===n.recommendationType?s=await src_setupHandler.fetchShopifyRecommendations(e,t,a.shopifyRecommendations,n.recommendationIntent):"MANUAL"===n.recommendationType&&a?.length>0?d=await src_setupHandler.fetchManualRecommendations(e,t,a.manualRecommendations):[s,d]=await Promise.all([src_setupHandler.fetchShopifyRecommendations(e,t,a.shopifyRecommendations,n.recommendationIntent),src_setupHandler.fetchManualRecommendations(e,t,a.manualRecommendations)]);const c={shopifyRecommendations:"MANUAL"!==n.recommendationType&&s.length?[...i.shopifyRecommendations,...s]:i.shopifyRecommendations,manualRecommendations:"SHOPIFY"!==n.recommendationType&&d.length?[...i.manualRecommendations,...d]:i.manualRecommendations};switch(sessionStorage.setItem("dealeasy-recommendations",JSON.stringify(c)),n.recommendationType){case"SHOPIFY":return c.shopifyRecommendations.flatMap((e=>e.products));case"MANUAL":return c.manualRecommendations;default:return[...c.shopifyRecommendations.flatMap((e=>e.products)),...c.manualRecommendations]}}catch(e){return console.error("fn.fetchRecommendations:",e),[]}},selectOptimalProductsForMilestone:(e,t=[],r,n,o=10,i=!1,a=[])=>{try{let s=t.map((e=>e.productId));const d=offersHandler.destructureProducts(e);let c=[];c=i?d.filter((e=>!s.includes(e.productId)&&e.availableForSale&&e.price>0&&!a.includes(e.productId))):d.filter((e=>e.availableForSale&&e.price>0&&!a.includes(e.productId)));const l=n-r,u=c.map((e=>({...e,priceDifference:e.price-l,absDifference:Math.abs(e.price-l)}))).sort(((e,t)=>0===e.absDifference?-1:0===t.absDifference?1:e.absDifference===t.absDifference?e.absDifference>50?e.priceDifference-t.priceDifference:t.priceDifference-e.priceDifference:e.absDifference-t.absDifference));return offersHandler.restructureProducts(u).slice(0,o)}catch(e){return console.error("fn.getSortedRecommendations:",e),[]}},destructureProducts:e=>{const t=[],r=new Set;return e.forEach((e=>{e.availableForSale&&e.variants.forEach((n=>{r.has(n.variantId)||(r.add(n.variantId),t.push({variantId:Number(n.variantId),title:n.title,price:n.price,compareAtPrice:n.compareAtPrice,availableForSale:n.availableForSale,selectedOptionsTitle:n.selectedOptionsTitle,onlineStoreUrl:n.onlineStoreUrl,currencyCode:n.currencyCode,imageSrc:n.imageSrc,productOnlineStoreUrl:e.onlineStoreUrl,productTitle:e.title,productId:Number(e.id.split("/").pop()),productHandle:e.handle,productImageSrc:e.imageSrc}))}))})),t},restructureProducts(e){const t={};return e.forEach((e=>{const r=e.productId;t[r]||(t[r]={id:r,handle:e.productHandle,title:e.productTitle,availableForSale:e.productAvailableForSale,imageSrc:e.productImageSrc,onlineStoreUrl:e.productOnlineStoreUrl,variants:[]}),t[r].variants.push({variantId:e.variantId,title:e.title,availableForSale:e.availableForSale,selectedOptionsTitle:e.selectedOptionsTitle,imageSrc:e.imageSrc,onlineStoreUrl:e.onlineStoreUrl,price:e.price,currencyCode:e.currencyCode,compareAtPrice:e.compareAtPrice})})),Object.values(t)},getBogoOffersOnCart:async(e,t,r=void 0)=>{try{const n=offersHandler.getEligibleBogos(e,t);if(n&&n.length){return(await Promise.all(n.map((e=>{const t=e.tiers.sort(((e,t)=>t.buyQuantity-e.buyQuantity)),n=e.eligibleProducts,o="SAME_PRODUCT"===e.rewardStrategy,i=e.usageLimit.enabled?Number(e.usageLimit.maxUsesPerOrder):1/0,a=o?offersHandler.generateSameProductBogoCombinations(t,n,i,r):offersHandler.generateMixedProductBogoCombinations(t,n,i);return a&&a.length?{...e,combinations:a}:null})))).filter(Boolean)}return[]}catch(e){return console.error("fn.getBogoForCart : ",e),[]}},getBogoOfferForCurrentProduct:async(e,t,r=[])=>{try{const n=offersHandler.getEligibleBogos(t,[e]);let o=null;if(n&&n.length){const e=r.filter((e=>n.some((t=>t.discountId===e.discountId)))),t=e.filter((e=>"SAME_PRODUCT"!==e.rewardStrategy||e.combinations.some((e=>e.isCurrentProduct))));let i=[];if(e&&e.length&&t&&t.length){if(i=t.map((e=>{const t="SAME_PRODUCT"===e.rewardStrategy?e.combinations.filter((e=>e.isCurrentProduct)):e.combinations,r=t.reduce(((e,t)=>Math.min(e,t.requiredFulfillQuantity)),1/0);return{...e,combinations:t,minRequiredQuantity:r}})),i&&i.length){const e=i.sort(((e,t)=>e.minRequiredQuantity-t.minRequiredQuantity))[0];e&&(o=e)}}else{const e=n.map((e=>{const t=e.tiers.sort(((e,t)=>t.buyQuantity-e.buyQuantity)).reduce(((e,t)=>Math.max(e,t.buyQuantity)),0);return{...e,maxBuyQuantity:t}})).sort(((e,t)=>t.maxBuyQuantity-e.maxBuyQuantity))[0];if(e){const t=e.tiers.sort(((e,t)=>e.buyQuantity-t.buyQuantity))[0];o={...e,combinations:[{type:"notFulfilled",buyQuantity:t.buyQuantity,getQuantity:t.getQuantity,requiredFulfillQuantity:t.buyQuantity+t.getQuantity,requiredBuyQuantity:t.buyQuantity,requiredGetQuantity:t.getQuantity}]}}}}const i=o?.combinations.filter((e=>"fulfilled"===e.type)),a=o?.combinations.filter((e=>"fulfilled"!==e.type&&!i.some((t=>t.buyQuantity>=e.buyQuantity))));return{...o,tiers:o?.tiers.sort(((e,t)=>e.buyQuantity-t.buyQuantity)),renderCombination:i?.length?i.sort(((e,t)=>t.buyQuantity-e.buyQuantity))[0]:a?.length?a[0]:null}}catch(e){return console.error("fn.getBogoOfferForCurrentProduct : ",e),null}},getEligibleBogos:(e,t)=>{try{return e.map((e=>{const r=e.enableExclusion?offersHandler.filterProductsByExclusion(e,t):t;if(!r.length)return null;let{appliesTo:n,selectedItems:o}=e;const i="PRODUCTS"===n?r.filter((e=>o.includes(e.id))):"COLLECTIONS"===n?r.filter((e=>e.collections.some((e=>o.includes(e))))):r;return{...e,eligibleProducts:i.sort(((e,t)=>t.price-e.price))}})).filter((e=>e?.eligibleProducts?.length))}catch(e){return console.error("fn.getEligibleBogos : ",e),[]}},generateMixedProductBogoCombinations:(e,t,r)=>{try{const n=[],o=[],i=[];let a=[...t];for(const t of e)for(;;){const{buyQuantity:e,getQuantity:r}=t,{combinedProducts:s,requiredQuantity:d}=offersHandler.allocateProducts(a,e);if(d>0){i.push({tier:t.buyQuantity,type:"notFulfilled",buyQuantity:e,getQuantity:r,buyProducts:s,getProducts:[],requiredBuyQuantity:d,requiredGetQuantity:r,requiredFulfillQuantity:d+r});break}const c=offersHandler.updateQuantities(a,s).filter((e=>e.lineItemQuantity>0)),{combinedProducts:l,requiredQuantity:u}=offersHandler.allocateProducts(c,r,!0);if(u>0){o.push({type:"partiallyFulfilled",buyQuantity:e,getQuantity:r,buyProducts:s,getProducts:l,requiredBuyQuantity:0,requiredGetQuantity:r,requiredFulfillQuantity:u});break}const p=offersHandler.mergeProductQuantities([...s,...l]);a=offersHandler.updateQuantities(a,p).filter((e=>e.lineItemQuantity>0)),n.push({type:"fulfilled",buyQuantity:e,getQuantity:r,buyProducts:s,getProducts:l,requiredBuyQuantity:0,requiredGetQuantity:0,requiredFulfillQuantity:0})}return[...n,...o.sort(((e,t)=>e.requiredFulfillQuantity-t.requiredFulfillQuantity)),...i.sort(((e,t)=>e.requiredFulfillQuantity-t.requiredFulfillQuantity))].slice(0,r)}catch(e){return console.error("fn.generateMixedProductBogoCombinations : ",e),[]}},generateSameProductBogoCombinations:(e,t,r,n=void 0)=>{try{const o=t.reduce(((e,t)=>(e[t.id]||(e[t.id]=[]),e[t.id].push({...t}),e)),{}),i=[],a=[],s=[];for(const[t,r]of Object.entries(o)){let o=[...r];for(const r of e){const{buyQuantity:e,getQuantity:d}=r;for(;;){const r=t===n,{combinedProducts:c,requiredQuantity:l}=offersHandler.allocateProducts(o,e);if(l>0){s.push({type:"notFulfilled",buyQuantity:e,getQuantity:d,buyProducts:c,getProducts:[],requiredBuyQuantity:l,requiredGetQuantity:d,requiredFulfillQuantity:l+d,isCurrentProduct:r});break}const u=offersHandler.updateQuantities(o,c).filter((e=>e.lineItemQuantity>0)),{combinedProducts:p,requiredQuantity:g}=offersHandler.allocateProducts(u,d);if(g>0){a.push({type:"partiallyFulfilled",buyQuantity:e,getQuantity:d,buyProducts:c,getProducts:p,requiredBuyQuantity:0,requiredGetQuantity:g,requiredFulfillQuantity:g,isCurrentProduct:r});break}const f=offersHandler.mergeProductQuantities([...c,...p]);o=offersHandler.updateQuantities(o,f).filter((e=>e.lineItemQuantity>0)),i.push({type:"fulfilled",buyQuantity:e,getQuantity:d,buyProducts:c,getProducts:p,requiredBuyQuantity:0,requiredGetQuantity:0,requiredFulfillQuantity:0,isCurrentProduct:r})}}}return[...i,...a.sort(((e,t)=>e.requiredFulfillQuantity-t.requiredFulfillQuantity)),...s.sort(((e,t)=>e.requiredFulfillQuantity-t.requiredFulfillQuantity))].slice(0,r)}catch(e){return console.error("fn.generateSameProductBogoCombinations : ",e),[]}},allocateProducts:(e,t,r=!1)=>{const n=r?[...e].reverse():[...e],o=[];let i=t;for(const e of n){if(i<=0)break;const t=Math.min(e.lineItemQuantity,i);t>0&&(o.push({...e,lineItemQuantity:t}),i-=t)}return{combinedProducts:o,requiredQuantity:i}},updateQuantities:(e,t)=>{const r=new Map(t.map((e=>[`${e.id}-${e.index}-${e.variantId}`,e.lineItemQuantity])));return e.map((e=>{const t=`${e.id}-${e.index}-${e.variantId}`,n=r.get(t)||0;return{...e,lineItemQuantity:e.lineItemQuantity-n}}))},mergeProductQuantities:e=>{const t=new Map;for(const r of e){const e=`${r.id}-${r.index}-${r.variantId}`;t.has(e)?t.get(e).lineItemQuantity+=r.lineItemQuantity:t.set(e,{...r})}return Array.from(t.values())},getCartGwpCombinations:async(e,t,r,n)=>{try{let o=n.filter((e=>e.properties&&e.properties.__dealeasy_gwp));const i=await src_cartHandler.getCartLineItemProducts(n.filter((e=>!e.properties?.__dealeasy_gwp&&!e.properties?.__dealeasy_gift_product)),e,t),a=r.map((e=>offersHandler.formatGiftWithProductOffer(e,i))).filter((e=>e.eligibleProductIds.length)).sort(((e,t)=>t.eligibleProductIds.length-e.eligibleProductIds.length)),s=[],d=[];if(i&&i.length){let e=[...i];for(const t of a){const r=e.filter((e=>t.eligibleProductIds.includes(e.id)));e=e.filter((e=>!t.eligibleProductIds.includes(e.id)));const n=o.filter((e=>e.properties.__dealeasy_gwp.includes(t.offerId)&&t.giftProductVariantIds.includes(e.id)));o=o.filter((e=>!(e.properties.__dealeasy_gwp.includes(t.offerId)&&t.giftProductVariantIds.includes(e.id))));const i="MULTIPLY_SAME_GIFT"===t.discountStrategy?offersHandler.getMultiplyGwpCombinations(t,r,n,t.usageLimit?.enabled?Number(t.usageLimit.maxUsesPerOrder):1/0):offersHandler.getUpgradeGwpCombinations(t,r,n);if(i&&(s.push(...i.combinations||[]),e=i.remainingProducts.length?[...i.remainingProducts,...e]:e,d.push(...i.productsToRemove||[])),!e.length)break}}return{combinations:s,productsToRemove:[...d,...o].filter(((e,t,r)=>r.findIndex((t=>t.index===e.index))===t))}}catch(e){return console.error("fn.getCartGwpCombinations : ",e),[]}},getMultiplyGwpCombinations:(e,t,r,n)=>{try{const o=[],{offerId:i,rewardStrategy:a,tiers:s}=e,d=s[0],c=d.buyQuantity;if("SUM_QUANTITY"===a){const a=[...t],s=[...r],l=a.reduce(((e,t)=>e+t.lineItemQuantity),0),u=Math.min(Math.floor(l/c),n),p=u>0?u%c:c-l;if(p&&o.push({id:`${i}-${Date.now()}`,type:"notFulfilled",addedProducts:[],buyQuantity:c,requiredBuyQuantity:p,productsToBeAdded:d.selectedItems,translation:d.translation,...e}),0===u)return{combinations:o,productsToRemove:s,remainingProducts:a};const g=u*c,f=u,{allocatedProducts:m,remainingProducts:y}=offersHandler.gwpAllocateProducts(a,g);if(m.length){const{allocatedProducts:t,remainingProducts:r}=offersHandler.gwpAllocateProducts(s,f);return t.length({id:`${i}-${Date.now()+n}`,type:"partiallyFulfilled",buyQuantity:c,addedProducts:[],productsToBeAdded:d.selectedItems,requiredBuyQuantity:0,addedCombinationIds:t.map((e=>e.properties.__dealeasy_gwp)),translation:d.translation,...e})))),o.push({id:`${i}-${Date.now()}`,type:"fulfilled",buyQuantity:c,addedProducts:t,productsToBeAdded:d.selectedItems,requiredBuyQuantity:0,translation:d.translation,...e}),{combinations:o.sort(((e,t)=>e.requiredBuyQuantity-t.requiredBuyQuantity)),productsToRemove:r,remainingProducts:y}}return{combinations:o,productsToRemove:s,remainingProducts:a}}{const a=t.reduce(((e,t)=>{const r=t.id.split("/").pop();return e[r]||(e[r]=[]),e[r].push(t),e}),{});let s=[...r];const l=[],u=[];for(const[t,r]of Object.entries(a)){const a=[...r],p=s.filter((e=>e.properties.__dealeasy_gwp.includes(t)));s=s.filter((e=>!e.properties.__dealeasy_gwp.includes(t)));const g=a.reduce(((e,t)=>e+t.lineItemQuantity),0),f=Math.min(Math.floor(g/c),n),m=f>0?f%c:c-g;if(m&&o.push({id:`${i}-${t}-${Date.now()}`,type:"notFulfilled",buyQuantity:c,addedProducts:[],requiredBuyQuantity:m,productsToBeAdded:d.selectedItems,translation:d.translation,...e}),0===f){l.push(...p),u.push(...a);continue}const y=f*c,h=f,{allocatedProducts:b,remainingProducts:S}=offersHandler.gwpAllocateProducts(a,y);if(b.length){const{allocatedProducts:r,remainingProducts:n}=offersHandler.gwpAllocateProducts(p,h);r.length({id:`${i}-${t}-${Date.now()+o}`,type:"partiallyFulfilled",buyQuantity:c,addedProducts:[],requiredBuyQuantity:0,productsToBeAdded:d.selectedItems,addedCombinationIds:r.map((e=>e.properties.__dealeasy_gwp)),translation:d.translation,...e})))),o.push(...Array.from({length:r.length}).map(((t,n)=>({id:r[n].properties.__dealeasy_gwp,type:"fulfilled",buyQuantity:c,addedProducts:[r[n]],productsToBeAdded:d.selectedItems,translation:d.translation,requiredBuyQuantity:0,...e})))),l.push(...n),u.push(...S)}else l.push(...p),u.push(...a)}return{combinations:o.sort(((e,t)=>e.requiredBuyQuantity-t.requiredBuyQuantity)),productsToRemove:[...l,...s],remainingProducts:u}}}catch(e){return console.error("fn.getMultiplyGwpCombinations : ",e),[]}},getUpgradeGwpCombinations:(e,t,r)=>{try{const n=[],{offerId:o,rewardStrategy:i,tiers:a,allowGiftStacking:s}=e;if("SUM_QUANTITY"===i){let i=[...r];const d=t.reduce(((e,t)=>e+t.lineItemQuantity),0),c=s?a.filter((e=>e.buyQuantity<=d)).sort(((e,t)=>e.buyQuantity-t.buyQuantity)):[a.find((e=>e.buyQuantity<=d))].filter(Boolean),l=a.filter((e=>e.buyQuantity>d&&!c.some((t=>t.buyQuantity===e.buyQuantity))));l.length&&l.forEach((t=>{const r=t.buyQuantity,i=r-d;i&&n.push({id:`${o}-${r}`,type:"notFulfilled",addedProducts:[],buyQuantity:r,requiredBuyQuantity:i,productsToBeAdded:t.selectedItems,translation:t.translation,...e})}));const u=[],p=[];for(const r of c){const a=r.buyQuantity,s=i.filter((e=>e.properties.__dealeasy_gwp.includes(`-${a}`)));i=i.filter((e=>!e.properties.__dealeasy_gwp.includes(`-${a}`)));const{allocatedProducts:d,remainingProducts:c}=offersHandler.gwpAllocateProducts(t,a);if(d.length){const{allocatedProducts:t,remainingProducts:i}=offersHandler.gwpAllocateProducts(s,1);t.length?n.push(...Array.from({length:t.length}).map(((n,o)=>({id:t[o].properties.__dealeasy_gwp,type:"fulfilled",buyQuantity:r.buyQuantity,requiredBuyQuantity:0,addedProducts:[t[o]],productsToBeAdded:r.selectedItems,translation:r.translation,...e})))):n.push({id:`${o}-${a}`,type:"partiallyFulfilled",addedProducts:[],buyQuantity:r.buyQuantity,requiredBuyQuantity:0,productsToBeAdded:r.selectedItems,translation:r.translation,...e}),u.push(...i),c.push(...c)}else u.push(...s),c.push(...t)}return{combinations:n.sort(((e,t)=>e.requiredBuyQuantity-t.requiredBuyQuantity)),productsToRemove:[...u,...i],remainingProducts:p}}{const i=t.reduce(((e,t)=>{const r=t.id.split("/").pop();return e[r]||(e[r]=[]),e[r].push(t),e}),{});let d=[...r];const c=[],l=[];for(const[t,r]of Object.entries(i)){const i=r.reduce(((e,t)=>e+t.lineItemQuantity),0),u=s?a.filter((e=>e.buyQuantity<=i)).sort(((e,t)=>e.buyQuantity-t.buyQuantity)):[a.find((e=>e.buyQuantity<=i))].filter(Boolean),p=a.filter((e=>e.buyQuantity>i&&!u.some((t=>t.buyQuantity===e.buyQuantity))));p.length&&p.forEach((r=>{const a=r.buyQuantity,s=a-i;s&&n.push({id:`${o}-${a}-${t}`,type:"notFulfilled",addedProducts:[],buyQuantity:a,requiredBuyQuantity:s,productsToBeAdded:r.selectedItems,translation:r.translation,...e})}));for(const i of u){const a=i.buyQuantity,s=d.filter((e=>e.properties.__dealeasy_gwp.includes(`-${a}-${t}`)));d=d.filter((e=>!e.properties.__dealeasy_gwp.includes(`-${a}-${t}`)));const{allocatedProducts:u,remainingProducts:p}=offersHandler.gwpAllocateProducts(r,a);if(u.length){const{allocatedProducts:r,remainingProducts:d}=offersHandler.gwpAllocateProducts(s,1);r.length?n.push(...Array.from({length:r.length}).map(((t,n)=>({id:r[n].properties.__dealeasy_gwp,type:"fulfilled",buyQuantity:i.buyQuantity,requiredBuyQuantity:0,addedProducts:[r[n]],productsToBeAdded:i.selectedItems,translation:i.translation,...e})))):n.push({id:`${o}-${a}-${t}`,type:"partiallyFulfilled",buyQuantity:i.buyQuantity,requiredBuyQuantity:0,addedProducts:[],productsToBeAdded:i.selectedItems,translation:i.translation,...e}),c.push(...d),l.push(...p)}else c.push(...s),l.push(...r)}}return{combinations:n.sort(((e,t)=>e.requiredBuyQuantity-t.requiredBuyQuantity)),productsToRemove:[...c,...d],remainingProducts:l}}}catch(e){return console.error("fn.getUpgradeGwpCombinations : ",e),[]}},gwpAllocateProducts:(e,t)=>{const r=[],n=[];for(let o=0;o0;o++){const i=e[o],a=i.lineItemQuantity;a<=t?(r.push(i),t-=a):(r.push({...i,lineItemQuantity:t}),n.push({...i,lineItemQuantity:a-t}),t=0)}return 0===t&&n.push(...e.slice(r.length)),{allocatedProducts:r,remainingProducts:n}},getGwpEligibleCombinations:e=>{try{const t=[],r=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-added-gwp-gifts")||"[]"):[];return e.forEach((e=>{if("MULTIPLY_SAME_GIFT"===e.discountStrategy){const n=e.id.split("-").slice(0,"SUM_QUANTITY"===e.rewardStrategy?1:2).join("-");r.filter((t=>!e.addedCombinationIds.includes(t))).some((e=>e.includes(n)))?e.isMandatory&&t.push(e):t.push(e)}else r.includes(e.id)?e.isMandatory&&t.push(e):t.push(e)})),t}catch(e){return console.error("fn.getGwpEligibleCombinations : ",e),[]}},formatGiftWithProductOffer:(e,t)=>{let r=offersHandler.getEligibleGwpProducts(e.appliesTo,e.selectedItems,t);e.enableExclusion&&(r=offersHandler.filterProductsByExclusion(e,r));const n=e.tiers.flatMap((e=>e.selectedItems.flatMap((e=>e.id)))),o=e.translation?.tiers?.sort(((e,t)=>e.index-t.index))??[];return{offerId:e.discountId.split("/").pop(),eligibleProductIds:r.map((e=>e.id)).filter((e=>!n.includes(e))),tiers:[...e.tiers].sort(((e,t)=>e.buyQuantity-t.buyQuantity)).map(((e,t)=>({...e,translation:o[t]??{}}))).sort(((e,t)=>t.buyQuantity-e.buyQuantity)),giftProductVariantIds:e.tiers.flatMap((e=>e.selectedItems.flatMap((e=>e.variants)))),rewardStrategy:e.rewardStrategy,discountStrategy:e.discountStrategy,currencyCode:e.currencyCode,currencyFormat:e.currencyFormat,strategy:e.discountStrategy,autoAddGifts:"AUTOMATIC"===e.giftAdditionType,isMandatory:e.isGiftMandatory,usageLimit:e.usageLimit,allowGiftStacking:e.allowGiftStacking,isCodeDiscount:e.isCodeDiscount,discountCode:e.discountCode,appliesTo:e.appliesTo,selectedItems:e.selectedItems,autoApplyCodeDiscount:e.autoApplyCodeDiscount}},getEligibleGwpProducts:(e,t,r)=>{try{const n=new Set(t);switch(e){case"PRODUCTS":const e=[];for(const t of r)n.has(t.id)&&e.push(t);return e;case"COLLECTIONS":const t=[];for(const e of r)e.collections?.some((e=>n.has(e)))&&t.push(e);return t;default:return r}}catch(e){return console.error("fn.getEligibleGwpProducts : ",e),[]}},removeGwpGifts:async(e=[])=>{try{const t={};e.forEach((e=>{t[e.key]=0}));const r=await src_cartHandler.updateCart(t);if(r&&r.success){if(utils.A.isNotPrivateTab()){const t=JSON.parse(sessionStorage.getItem("dealeasy-added-gwp-gifts")||"[]").filter((t=>!e.some((e=>e.properties.__dealeasy_gwp===t))));sessionStorage.setItem("dealeasy-added-gwp-gifts",JSON.stringify(t))}return!0}return!1}catch(e){return void console.error("fn.removeGwpGifts : ",e)}},addGwpProductsToCart:async(e,t=!1)=>{try{const r=await src_cartHandler.addToCart(e,t);if(utils.A.isNotPrivateTab()&&r.success){const t=e.map((e=>e.properties.__dealeasy_gwp)),r=JSON.parse(sessionStorage.getItem("dealeasy-added-gwp-gifts")||"[]");sessionStorage.setItem("dealeasy-added-gwp-gifts",JSON.stringify(Array.from(new Set([...r,...t]))))}return r}catch(e){return console.error("fn.addGwpProductsToCart : ",e),!1}},getGiftProductsForCombinations:async(e,t,r=[])=>{try{let n=[];const o=r.flatMap((e=>e.productsToBeAdded)),i=Array.from(new Set(o.flatMap((e=>e.variants)))),a=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-gwp-variants")||"{}"):void 0;if(a&&a.productVariants&&dayjs().diff(dayjs.unix(a.createdAt),"minutes")<5&&i.every((e=>a.productVariants.some((t=>t.id===e))))&&n.push(...a.productVariants),!n.length){const r=Array.from(new Set(o.map((e=>e.id)))),a=await src_setupHandler.getProducts(e,t,"ID",r);if(a&&a.length){const e=a.flatMap((e=>e.variants)).filter((e=>i.includes(e.id)));n.push(...e),sessionStorage.setItem("dealeasy-gwp-variants",JSON.stringify({productVariants:e,createdAt:dayjs().unix()}))}}n=n.filter(((e,t,r)=>r.findIndex((t=>t.id===e.id))===t));const s=r.map((e=>{const t=e.productsToBeAdded.flatMap((e=>e.variants)),r=n.filter((e=>t.includes(e.id))).map((t=>({...t,lineItemProperty:e.id}))).filter((e=>e.availableForSale));return{...e,isProductsFetched:!0,productsToBeAdded:r}}));return s.filter((e=>e.productsToBeAdded.length))}catch(e){return console.error("fn.getGiftProductsForCombinations : ",e),[]}},filterProductsByExclusion:(e,t=[])=>{try{switch(e.exclusionType){case"PRODUCTS":return t.filter((t=>!e.excludedProductIds.includes(t.id)));case"COLLECTIONS":return t.filter((t=>!t.collections.some((t=>e.excludedCollectionIds.includes(t)))));case"TAGS":return t.filter((t=>!t.tags.some((t=>e.excludedTags.includes(t)))));default:return t}}catch(e){return console.error("fn.getEligibleProductsForBogoAndVolumeDiscount : ",e),[]}},getProductGwpCombinations:async(e,t,r,n=[],o=[])=>{try{const i=n.filter((e=>offersHandler.formatGiftWithProductOffer(e,[r]).eligibleProductIds.length));if(i&&i.length){let n=o.filter((e=>e.properties&&e.properties.__dealeasy_gwp));const a=await src_cartHandler.getCartLineItemProducts(o.filter((e=>!e.properties?.__dealeasy_gwp&&!e.properties?.__dealeasy_gift_product)),e,t),s=i.map((e=>offersHandler.formatGiftWithProductOffer(e,a))).filter((e=>"INDIVIDUAL_QUANTITY"===e.rewardStrategy?e.eligibleProductIds.includes(r.id):e.eligibleProductIds)).filter((e=>e.eligibleProductIds.length)).sort(((e,t)=>t.eligibleProductIds.length-e.eligibleProductIds.length));if(s&&s.length){const o=s[0],i=a.filter((e=>o.eligibleProductIds.includes(e.id))),d=n.filter((e=>n.filter((t=>t.properties.__dealeasy_gwp.includes(o.offerId)&&o.giftProductVariantIds.includes(e.id))))),c="MULTIPLY_SAME_GIFT"===o.discountStrategy?offersHandler.getMultiplyGwpCombinations(o,i,d,o.usageLimit.enabled?o.usageLimit.maxUsesPerOrder:1/0):offersHandler.getUpgradeGwpCombinations(o,i,d);if(c&&c.combinations&&c.combinations.length){const n=r.id.split("/").pop(),i=c.combinations.filter((e=>"INDIVIDUAL_QUANTITY"!==e.rewardStrategy||e.id.includes(n))),a="MULTIPLY_SAME_GIFT"===o.discountStrategy?i.slice(0,1):i;return await offersHandler.getGiftProductsForCombinations(e,t,a)}}const d={...r,lineItemQuantity:0},c=i.map((e=>offersHandler.formatGiftWithProductOffer(e,[d]))).filter((e=>e.eligibleProductIds.length)).sort(((e,t)=>e.tiers.reduce(((e,t)=>Math.max(e,t.buyQuantity)),0)-t.tiers.reduce(((e,t)=>Math.max(e,t.buyQuantity)),0)))[0];if(c){const r="MULTIPLY_SAME_GIFT"===c.discountStrategy?offersHandler.getMultiplyGwpCombinations(c,[d],[],c.usageLimit.enabled?c.usageLimit.maxUsesPerOrder:1/0):offersHandler.getUpgradeGwpCombinations(c,[d],[]);if(r&&r.combinations&&r.combinations.length){const n="MULTIPLY_SAME_GIFT"===c.discountStrategy?r.combinations.slice(0,1):r.combinations;return await offersHandler.getGiftProductsForCombinations(e,t,n)}}}return[]}catch(e){return console.error("fn.getProductGwpCombinations : ",e),[]}}},src_offers=offersHandler,setupHandler={useInContext:"boolean"!=typeof dealeasyUseInContext||dealeasyUseInContext,imageResolution:"number"==typeof dealeasyImageResolution?dealeasyImageResolution:400,storeSetup:void 0,setStoreSetup:e=>{setupHandler.storeSetup=e},getStoreSetup:()=>setupHandler.storeSetup,getSetup:()=>{const e=setupHandler.getStoreSetup();if(e){const t=[];return Object.entries(e.offers).forEach((([e,r])=>{e&&r&&"object"==typeof r&&r.length&&t.push(...r)})),{discounts:t,setups:e.widgetSetups,product:e.product,shopSetup:e.shop}}},getStoreFrontAccessToken:async e=>{try{if("string"==typeof dealeasyPublicAccessToken&&""!==dealeasyPublicAccessToken)return dealeasyPublicAccessToken;if(utils.A.isNotPrivateTab()){const e=localStorage.getItem("lb-dealeasy-access-token");if(e&&""!==e)return e}const t=await fetch(`${config.A.HOST}/api/public/storefront/token?myshopifyDomain=${encodeURIComponent(e)}`,{method:"GET",headers:{"Content-Type":"application/json","cache-control":"max-age=3600"},mode:"cors"});if(t.ok){const e=await t.json();if(e?.publicAccessToken)return utils.A.isNotPrivateTab()&&localStorage.setItem("lb-dealeasy-access-token",e.publicAccessToken),e.publicAccessToken}return}catch(e){return void console.error("fn.getStoreFrontAccessToken: ",e)}},getStoreData:async(e,t,r,n)=>{try{const o=await fetch(`https://${e}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:src_query.metaobjects})});if(o.ok){const t=await o.json();if(t&&t.data){return{offers:await src_offers.getOffers(e,t.data.offersMetaobjects?.nodes?.filter((e=>e?.field?.value)).map((e=>JSON.parse(e.field.value))),r,n),widgetSetups:t.data.setupMetaobjects?.nodes?.filter((e=>e?.field?.value)).map((e=>JSON.parse(e.field.value))),shop:{id:t.data.shop?.id,shopCurrency:{currencyFormat:t.data.shop?.moneyFormat,currencyCode:t.data.localization?.country?.currency?.isoCode,currencySymbol:t.data.localization?.country?.currency?.symbol}}}}}return}catch(e){return void console.error("fn.getStoreSetup : ",e)}},getCurrentPageProduct:async(e,t)=>{try{const r=utils.A.getPageProductHandle(window.location.pathname);if(r){const n=Shopify.country,o=utils.A.getLocale(),i=setupHandler.useInContext?`@inContext(country: ${n}, language: ${o})`:"",a="boolean"==typeof dealeasyIsB2BCustomer&&dealeasyIsB2BCustomer,s="boolean"==typeof dealeasyUsingTranslatedHandles&&dealeasyUsingTranslatedHandles;let d,c;if(a||s){const e=await fetch(utils.A.getProductRequestURL(r));e.ok&&(c=await e.json(),c&&(d={query:`query productQuery($id: ID!, $imageResolution: Int!) ${i} { product(id: $id)${src_query.product} }`,variables:{id:`gid://shopify/Product/${c.id}`,imageResolution:setupHandler.imageResolution}}))}else d={query:`query productQuery($handle: String!, $imageResolution: Int!) ${i} { product(handle: $handle)${src_query.product} }`,variables:{handle:r,imageResolution:setupHandler.imageResolution}};const l=await fetch(`https://${e}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify(d)});if(l?.ok){const e=await l.json();if(e&&e.data&&e.data.product)return setupHandler.formatProductResponse(e.data.product,c,a)}}return}catch(e){return void console.error("fn.getCurrentPageProduct : ",e)}},getProducts:async(e,t,r,n)=>{try{const o=Shopify.country,i=utils.A.getLocale(),a=setupHandler.useInContext?`@inContext(country: ${o}, language: ${i})`:"",s=n.map(((e,t)=>"ID"===r?`product${t}: product(id: "${e}")${src_query.product}`:`product${t}: product(handle: "${e}")${src_query.product}`)).join(""),d=await fetch(`https://${e}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:`query productsQuery($imageResolution: Int!) ${a} { ${s} }`,variables:{imageResolution:setupHandler.imageResolution}})});if(d?.ok){const e=await d.json();if(e&&e.data)return Object.values(e.data).filter(Boolean).map((e=>setupHandler.formatProductResponse(e)))}return}catch(e){return void console.error("fn.getProducts : ",e)}},formatProductResponse:(e,t=void 0,r=!1)=>{try{return{id:e.id,handle:e.handle,title:e.title,tags:e.tags,collections:e.collections?.nodes?.map((e=>e.id)),availableForSale:e.availableForSale,imageSrc:e.featuredImage?.url,imageAltText:e.featuredImage?.altText,totalInventory:e.totalInventory,onlineStoreUrl:utils.A.getProductOnlineStoreURL(e.handle),isGiftCard:e.isGiftCard,hasOnlyDefaultVariant:e.variants&&e.variants.nodes&&1===e.variants.nodes.length,variants:e.variants?.nodes?.map((n=>({id:n.id,productId:e.id,productHandle:e.handle,productTitle:e.title,productImageSrc:e.featuredImage?.url,productImageAltText:e.featuredImage?.altText,productOnlineStoreUrl:utils.A.getProductOnlineStoreURL(e.handle),hasOnlyDefaultVariant:e.variants&&e.variants.nodes&&1===e.variants.nodes.length,variantId:n.id.split("/").pop(),title:n.title.replaceAll("/","-"),availableForSale:n.availableForSale,quantityAvailable:n.quantityAvailable,currentlyNotInStock:n.currentlyNotInStock,selectedOptionsTitle:n.selectedOptions.map((e=>e.name)).join(" - "),imageSrc:n.image?.url??e.featuredImage?.url,onlineStoreUrl:utils.A.getProductOnlineStoreURL(e.handle,n.id.split("/").pop()),price:r&&t&&t.variants.some((e=>n.id.includes(e.id)))?Number(t.variants.find((e=>n.id.includes(e.id))).price)/100:Number(n.price.amount),currencyCode:n.price.currencyCode,compareAtPrice:r&&t&&t.variants.some((e=>n.id.includes(e.id)))?Number(t.variants.find((e=>n.id.includes(e.id))).compare_at_price)/100:n.compareAtPrice?Number(n.compareAtPrice.amount||0):void 0,compareAtPriceCurrencyCode:n.compareAtPrice?n.compareAtPrice?.currencyCode:void 0})))}}catch(e){return void console.error("fn.formatProductResponse : ",e)}},getWidgetSetupByType:e=>{try{const t=setupHandler.getStoreSetup();return t&&t.widgetSetups?t.widgetSetups.find((t=>t.recordType===e)):void 0}catch(e){return void console.error("fn.getWidgetSetupByType : ",e)}},getPaginatedCollectionProducts:async(e,t,r,n=[],o=50,i=null)=>{try{let a=0,s=!1,d=!1,c=o;const l=[],u=[];do{const p=r[a],g=await setupHandler.getCollectionProducts(e,t,p,n,c,i);g&&g.products&&(g.products.forEach((e=>{l.some((t=>t.id===e.id))||l.push(e)})),l.length{try{const i=r.filter((e=>!n.includes(e))).slice(0,o),a=await setupHandler.getProducts(e,t,"ID",i);if(a&&a.length){const e=[...new Set([...n,...i])];return{products:a,pagination:{previousItems:e,hasNextPage:e.length{try{const a=Shopify.country,s=utils.A.getLocale(),d=setupHandler.useInContext?`@inContext(country: ${a}, language: ${s})`:"",c=await fetch(`https://${e}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:`query collectionQuery($id: ID!, $first: Int!, $after: String, $imageResolution: Int!) ${d} { ${src_query.collectionProducts} }`,variables:{id:r,first:o,after:i,imageResolution:setupHandler.imageResolution}})});if(c?.ok){const e=await c.json();if(e&&e.data&&e.data.collection){const t=e.data.collection,o=t.products.nodes.map((e=>setupHandler.formatProductResponse(e))).filter((e=>!e.collections.some((e=>e!==r&&n.includes(e)))));return{id:t.id,products:o,pageInfo:t.products.pageInfo}}}return}catch(e){return void console.error("fn.getCollectionProducts : ",e)}},getCustomerSegmentsMembership:async(e,t,r)=>{try{if(utils.A.isNotPrivateTab()){const e=JSON.parse(sessionStorage.getItem(`lb-dealeasy-customer-membership-${t}`)??"{}");if(e&&e.createdAt&&dayjs().diff(dayjs.unix(e.createdAt),"minutes")<5&&e.segmentMemberships&&e.segmentMemberships.length&&e.segmentMemberships.length===r.length&&e.segmentMemberships.every((e=>r.includes(e.segmentId))))return e}const n=await fetch(`${config.A.HOST}/api/public/customer/segments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({myshopifyDomain:e,customerId:t,segmentIds:r})});if(n.ok&&200===n.status){const e=await n.json();if(e&&e.segmentMemberships)return sessionStorage.setItem(`lb-dealeasy-customer-membership-${t}`,JSON.stringify({segmentMemberships:e.segmentMemberships,customerId:e.customerId,createdAt:dayjs().unix()})),e}return}catch(e){return void console.error("fn.getCustomerSegmentsMembership : ",e)}},fetchShopifyRecommendations:async(e,t,r,n)=>{try{const o=Shopify.country,i=utils.A.getLocale(),a=setupHandler.useInContext?`@inContext(country: ${o}, language: ${i})`:"",s=r.map(((e,t)=>`product${t}: productRecommendations(productId: "${`gid://shopify/Product/${e}`}", intent: ${n}) ${src_query.product}`)).join(""),d=await fetch(`https://${e}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:`query productRecommendations($imageResolution: Int!) ${a} { ${s} }`,variables:{imageResolution:setupHandler.imageResolution}})});if(d.ok){const e=await d.json();if(e&&e.data){return r.map(((t,r)=>({cartItemId:t,products:e.data[`product${r}`]?.map((e=>setupHandler.formatProductResponse(e)))||[]})))}}return[]}catch(e){return console.error("fn.fetchShopifyRecommendations : ",e),[]}},fetchManualRecommendations:async(e,t,r)=>{try{let n=r.map((e=>e.includes("gid")?e:`gid://shopify/Product/${e}`));const o=await setupHandler.getProducts(e,t,"ID",n);return o&&o.length?o:[]}catch(e){return console.error("fn.fetchManualRecommendations : ",e),[]}},formatCollectionResponse:e=>{try{return{id:e.id,title:e.title,handle:e.handle,imageSrc:e.image?.url||null,onlineStoreUrl:utils.A.getCollectionOnlineStoreURL(e.handle)}}catch(e){return void console.error("fn.formatCollectionResponse : ",e)}},getCollections:async(e,t,r)=>{try{if(!Array.isArray(r)||!r.length)return[];const n=Shopify.country,o=utils.A.getLocale(),i=setupHandler.imageResolution,a=setupHandler.useInContext?`@inContext(country: ${n}, language: ${o})`:"",s=r.map(((e,t)=>`Collection${t}: collection(id: "${e}") ${src_query.collection}`)).join("\n"),d=await fetch(`https://${e}/api/${config.A.API_VERSION}/graphql.json`,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":t},body:JSON.stringify({query:`query getCollections($imageResolution: Int!) ${a} {\n ${s}\n }`,variables:{imageResolution:i}})}),c=await d.json();return Object.values(c.data).filter(Boolean).map(setupHandler.formatCollectionResponse).filter(Boolean)}catch(e){return console.error("fn.getCollections:",e),[]}},getResources:async(e,t)=>{try{const{myShopifyDomain:r,accessToken:n}=setupHandler.getStoreSetup();if(r&&n){const o="PRODUCTS"===e?await setupHandler.getProducts(r,n,"ID",t):await setupHandler.getCollections(r,n,t);if(o&&o.length)return o}return[]}catch(e){return console.error("fn.getResources : ",e),[]}}},src_setupHandler=setupHandler,integrations={detectIntegration:(e,t)=>"function"==typeof window.lbOrdereasyGetProducts||(window.addEventListener(e,t),!1),getDibsSellingPlanData:async(e,t={})=>{try{if(e?.length){const r=e.map((e=>e.id.split("/").pop())),n=await window.lbOrdereasyGetProducts({productIds:r,locale:utils.A.getLocale(),countryCode:Shopify.country}),o={};if(n){for(const e of n){const r=e.id.split("/").pop(),n=t?.[r]||[],i=(n.length?e.variants.filter((e=>n.includes(e.id.split("/").pop()))):e.variants).filter((e=>e.applicableSellingPlans?.length>0));i.length&&(o[r]=i)}return Object.keys(o).length>0?o:void 0}return o}return{}}catch(e){return console.error("integrations.processDibsSellingPlanData:",e),{}}}},src_integrations=integrations,vdWidgetHandler={setup:void 0,nudgeSetup:void 0,setSetup:e=>(vdWidgetHandler.setup=e,vdWidgetHandler),getSetup:()=>vdWidgetHandler.setup,widgetAppBlockSelectors:{"widget#vdtable":"#lb-volume-discount","widget#vdcards":"#lb-vd-cards"},widgetTags:{1:{"widget#vdtable":"lb-volume-discount","widget#vdcards":"lb-vd-cards"},2:{"widget#vdtable":"lb-volume-discount","widget#vdcards":"lb-vd-qty-selector"}},setNudgeSetup:e=>(vdWidgetHandler.nudgeSetup=e,vdWidgetHandler),getNudgeSetup:()=>vdWidgetHandler.nudgeSetup,lazyPositionListener:void 0,removalListener:void 0,vdNudgeRenderCount:0,formMutationObserver:void 0,lastFormState:void 0,disconnectListeners:()=>(vdWidgetHandler.lazyPositionListener&&vdWidgetHandler.lazyPositionListener.disconnect(),vdWidgetHandler.removalListener&&vdWidgetHandler.removalListener.disconnect(),vdWidgetHandler.resetRenderState(),!0),lastUpdatedFormPayload:void 0,dibsSellingPlanData:void 0,resourceType:void 0,resetRenderState:()=>{vdWidgetHandler._renderState={isRendering:!1,lastRenderTime:0,pendingRender:!1,renderCount:0,maxRenders:5,throttleTime:500}},render:()=>{try{const{discount:e,product:t,widgetSetup:r,shop:n}=vdWidgetHandler.getSetup()??{};if(e&&t&&r&&n){const o=vdWidgetHandler.widgetTags[r.settings?.version??1][r.recordType],i=vdWidgetHandler.widgetAppBlockSelectors[r.recordType];if(utils.A.positionWidget(r.position,o,i)){const i=document.querySelector(o),a={code:Shopify.currency?.active,rate:Shopify.currency?.rate},s=r.translations[Shopify.locale]||r.translations.default;if(i){if("widget#vdcards"===r.recordType){utils.A.hideElementsOnPage(screen.width>480?r.settings.desktopDefaultActionSelectors:r.settings.mobileDefaultActionSelectors),vdWidgetHandler.registerQtySelectorListeners(r.settings,e?.discountToSubscriptionProducts),vdWidgetHandler.registerIntergration();let o=[],d=!1;r.settings&&r.settings.version>1?o=r.settings.listenToProductPageVariantChange?[t.currentVariant]:t.variants:(o=t.variants.filter((e=>e.availableForSale)),o.length||(d=!0)),i.discount=e,i.setup={...r,translation:s},i.translation=s,i.shopCurrency=n.shopCurrency,i.presentmentCurrency=a,i.productVariants=o,i.disableAtcButton=d,i.editableQtySelector="boolean"==typeof editableQtySelector&&editableQtySelector}else i.discount=e,i.setup={...r,translation:s},i.productPrice={amount:t.currentVariant.price,currencyCode:t.currentVariant.currencyCode},i.shopCurrency=n.shopCurrency,i.presentmentCurrency=a;return!0}}}return!1}catch(e){return console.error("vdWidgetHandler.render : ",e),!1}},registerQtySelectorListeners:e=>{try{const t=document.querySelector("lb-vd-qty-selector")||document.querySelector("lb-vd-cards");return"true"===t?.getAttribute("is-qty-selector-listeners-registered")||("MANUAL_DETECT_ATC"==e.buyButtonType||"AUTO_DETECT_ATC"==e.buyButtonType?(t.addEventListener("lb-dealeasy-qs-completed",(async t=>{t&&t.detail&&t.detail.selectedVariants&&(vdWidgetHandler.disableAtcButtons(e.buyButtonSelectors,!1),vdWidgetHandler.appendQtySelectorAttributeOnProductForm(t.detail),vdWidgetHandler.lastUpdatedFormPayload=t.detail)})),t.addEventListener("lb-dealeasy-qs-not-completed",(async t=>{t&&t.detail&&t.detail.selectedVariants&&(vdWidgetHandler.disableAtcButtons(e.buyButtonSelectors,!1),vdWidgetHandler.appendQtySelectorAttributeOnProductForm(void 0),vdWidgetHandler.lastUpdatedFormPayload=void 0)})),vdWidgetHandler.appendQtySelectorAttributeOnProductForm(vdWidgetHandler.lastUpdatedFormPayload),vdWidgetHandler.productFormMutationListener()):vdWidgetHandler.registerQtySelectorAtcListener(),t?.setAttribute("is-qty-selector-listeners-registered","true")),!0}catch(e){return console.error("vdWidgetHandler.registerQtySelectorListeners : ",e),!1}},registerQtySelectorAtcListener:()=>{try{document.addEventListener("lbDealeasyAddProductsToCart",(async e=>{try{if(e&&e.detail&&e.detail.selectedVariants&&e.detail.selectedVariants.length){const{discount:t,widgetSetup:r}=vdWidgetHandler.getSetup()??{};let n=[],o="";const i=utils.A.getProductFormsOnPage(),{productFormProperties:a,productFormAttributes:s}=utils.A.getFormAttributesAndProperties(i),d=r?.settings?.listenToProductPageVariantChange,c=d?s:s.filter((e=>!["selling_plan","id","quantity"].includes(e.name))),l="boolean"==typeof dealeasyDontUseFormProperties&&dealeasyDontUseFormProperties,u=t?.discountToSubscriptionProducts,p=vdWidgetHandler.dibsSellingPlanData?vdWidgetHandler.dibsSellingPlanData.map((e=>({...e,remainingQuantity:e.applicableQuantity}))):[];let g;if(n=e.detail.selectedVariants.filter((e=>e.quantity>0)).map((e=>{let t=e.quantity,r=null;if(p&&u){const n=p.find((t=>t.isDefault&&t.availableVariants.includes(e.variantId)));n&&(n.remainingQuantity!==1/0&&(t=Math.min(e.quantity,n.remainingQuantity),n.remainingQuantity-=t,t!==e.quantity&&(o=n.quantityError)),r=d?s.find((e=>"selling_plan"===e.name))?.value:n.id)}if(t>0){const n={id:e.variantId,quantity:t,properties:l?{}:Object.fromEntries(a.map((e=>[e.name,e.value]))),...Object.fromEntries(c.map((e=>[e.name,e.value])))};return r&&(n.selling_plan=r),n}return null})).filter((e=>null!==e)),!n.length)return window.dispatchEvent(new CustomEvent("lbDealeasyProductsNotAddedInCart",{detail:{success:!1,message:""!==o?o:""}})),!1;g=await src_cartHandler.addToCart(n,!0),await src_cartHandler.postAtcCartRefresh(e.detail.settings?.atcBtnAction),g.success?(window.dispatchEvent(new CustomEvent("lbDealeasyProductsAddedToCart",{detail:g})),window.dispatchEvent(new CustomEvent("lb-dealeasy-qty-selector-added-to-cart",{detail:{status:"success",...g}})),r.settings?.resetQuantitySelectorOnAtc&&setTimeout((()=>{window.dispatchEvent(new CustomEvent("lb-dealeasy-qs-refresh",{detail:{src:"lb-vd-qty-selector"}}))}),50),o&&window.dispatchEvent(new CustomEvent("lb-dealeasy-warning",{detail:{message:""!==o?o:""}}))):(window.dispatchEvent(new CustomEvent("lbDealeasyProductsNotAddedInCart",{detail:{success:!1,message:g.message}})),window.dispatchEvent(new CustomEvent("lb-dealeasy-qty-selector-added-to-cart",{detail:{status:"error",...g}})))}return!1}catch(e){return console.error("vdWidgetHandler.registerQtySelectorListeners : ",e),!1}}))}catch(e){return console.error("vdWidgetHandler.registerQtySelectorAtcListener : ",e),!1}},appendQtySelectorAttributeOnProductForm:e=>{try{const t=utils.A.getProductFormsOnPage(),{widgetSetup:r}=vdWidgetHandler.getSetup()??{};r.settings?.resetQuantitySelectorOnAtc&&t.forEach((e=>{e.addEventListener("submit",(e=>{e.target.action&&e.target.action.includes("/cart/add")&&setTimeout((()=>{window.dispatchEvent(new CustomEvent("lb-dealeasy-qs-refresh",{detail:{src:"lb-vd-qty-selector"}}))}),50)}))})),t.forEach((e=>{e.querySelectorAll("#lb-dealeasy-qs-attribute").forEach((e=>e.remove()))}));let n="";if(e&&e.selectedVariants){const{productFormProperties:o,productFormAttributes:i}=utils.A.getFormAttributesAndProperties(t),{attributes:a,isQuantityManipulated:s}=vdWidgetHandler.getQtySelectorAttributes(e.selectedVariants,o,i);n=s,a.length?utils.A.disableOriginalFormAttributes(t):(vdWidgetHandler.disableAtcButtons(r.settings.buyButtonSelectors,!0),window.dispatchEvent(new CustomEvent("lb-dealeasy-warning",{detail:{message:n}}))),t.forEach((e=>{a.forEach((t=>{e.insertAdjacentHTML("beforeend",t)}))}))}return vdWidgetHandler.dibsSellingPlanData&&t.forEach((e=>{e.addEventListener("submit",(e=>{e.target.action&&e.target.action.includes("/cart/add")&&window.dispatchEvent(new CustomEvent("lb-dealeasy-warning",{detail:{message:n}}))}))})),!0}catch(e){return console.error("vdWidgetHandler.appendQtySelectorAttributeOnProductForm : ",e),!1}},productFormMutationListener:()=>{try{const e=utils.A.getProductFormsOnPage(),t=["input","select","textarea"];return e.length>0&&(vdWidgetHandler.formMutationObserver=new MutationObserver((e=>{let r=!1;e.forEach((e=>{if(!e.target||"lb-dealeasy-qs-attribute"!==e.target.id){if("childList"===e.type){Array.from(e.addedNodes).concat(Array.from(e.removedNodes)).some((e=>e.nodeType===Node.ELEMENT_NODE&&("lb-dealeasy-qs-attribute"!==e.id&&!e.querySelector("#lb-dealeasy-qs-attribute")&&(t.includes(e.tagName.toLowerCase())||e.querySelector(t.join(","))))))&&(r=!0)}if("attributes"===e.type&&e.target){const n=e.target;if("lb-dealeasy-qs-attribute"===n.id)return;t.includes(n.tagName.toLowerCase())&&(r=!0)}}})),r&&setTimeout((()=>{vdWidgetHandler.lastFormState!==vdWidgetHandler.getFormState()&&(vdWidgetHandler.lastFormState=vdWidgetHandler.getFormState(),vdWidgetHandler.appendQtySelectorAttributeOnProductForm(vdWidgetHandler.lastUpdatedFormPayload))}),50)})),e.forEach((e=>{e&&e.nodeType===Node.ELEMENT_NODE&&vdWidgetHandler.formMutationObserver.observe(e,{childList:!0,subtree:!0,attributes:!0})}))),!0}catch(e){return console.error("vdWidgetHandler.productFormMutationListener:",e),!1}},getFormState:()=>{try{const e=utils.A.getProductFormsOnPage(),t={};return e.forEach(((e,r)=>{const n=e.querySelectorAll('input:not([id="lb-dealeasy-qs-attribute"]), select, textarea'),o=Array.from(n).map((e=>e.outerHTML));t[r]=o.join("")})),JSON.stringify(t)}catch(e){return console.error("vdWidgetHandler.getFormState:",e),""}},cleanupFormMutationObserver:()=>{try{return vdWidgetHandler.formMutationObserver?.disconnect(),vdWidgetHandler.formMutationObserver=void 0,vdWidgetHandler.lastFormState=void 0,!0}catch(e){return console.error("vdWidgetHandler.cleanupFormMutationObserver:",e),!1}},getQtySelectorAttributes:(e,t=[],r=[])=>{try{const n=[],{discount:o,widgetSetup:i}=vdWidgetHandler.getSetup()??{},a=i?.settings?.listenToProductPageVariantChange,s=o?.discountToSubscriptionProducts,d=a?r:r.filter((e=>"selling_plan"!==e.name)),c=vdWidgetHandler.dibsSellingPlanData?vdWidgetHandler.dibsSellingPlanData.map((e=>({...e,remainingQuantity:e.applicableQuantity}))):[];let l="";return e.forEach(((e,r)=>{let o=e.quantity,i="";if(c&&s){const t=c.find((t=>t.isDefault&&t.availableVariants.includes(e.variantId)));t&&(t?.remainingQuantity!==1/0&&(o=Math.min(e.quantity,t.remainingQuantity),t.remainingQuantity-=o,o!=e.quantity&&(l=t.quantityError)),a||(i=``))}if(o>0){const a=[``,``,``,...t.map((e=>``)),...d.map((e=>``))];i&&a.push(i),n.push(...a)}})),{attributes:n,isQuantityManipulated:l}}catch(e){return console.error("vdWidgetHandler.getQtySelectorAttributes : ",e),[]}},disableAtcButtons:(e,t=!1)=>{try{return utils.A.getBuyButtonsOnProductForms(e).forEach((e=>{e.disabled=t,vdWidgetHandler.listenAtcButtonStates(e,t)})),!0}catch(e){return console.error("vdWidgetHandler.disableAtcButtons : ",e),!1}},listenAtcButtonStates:(e,t)=>{try{const r=new MutationObserver((n=>{n.forEach((n=>{"attributes"===n.type&&"disabled"===n.attributeName&&(e.disabled=t,r.disconnect())}))}));return r.observe(e,{attributes:!0,attributeFilter:["disabled"]}),!0}catch(e){return console.error("vdWidgetHandler.listenAtcButtonStates : ",e),!1}},renderVdNudge:(e=!1)=>{try{vdWidgetHandler._renderState||(vdWidgetHandler._renderState={isRendering:!1,lastRenderTime:0,pendingRender:!1,renderCount:0,maxRenders:5,throttleTime:500});const t=vdWidgetHandler._renderState,r=Date.now();if(t.isRendering||r-t.lastRenderTime{t.pendingRender=!1,vdWidgetHandler.renderVdNudge(!0)}),t.throttleTime)),!1;if(t.isRendering=!0,t.lastRenderTime=r,t.renderCount++,t.renderCount>t.maxRenders)return vdWidgetHandler.disconnectListeners(),!1;const{widgetSetup:n,cartLinePromotions:o,shop:i}=vdWidgetHandler.getNudgeSetup()??{};if(n&&o&&o.length&&i){if(vdWidgetHandler.positionVdNudge(n.position,o)){const r=document.querySelectorAll("lb-vd-nudge"),a={code:Shopify.currency?.active,rate:Shopify.currency?.rate},s=n.translations[Shopify.locale]||n.translations.default;return vdWidgetHandler.vdNudgeRenderCount=r.length,o.forEach(((e,t)=>{const o=Array.from(r).at(t);o&&(o.discount=e.discount,o.cartLineItem=e.cartLineItem,o.setup=n,o.translation=s,o.shopCurrency=i.shopCurrency,o.presentmentCurrency=a)})),e||(vdWidgetHandler.observeElementRemoval((()=>{vdWidgetHandler._renderState.renderCount=0,vdWidgetHandler.renderVdNudge(!0)})),vdWidgetHandler.registerVdNudgeListeners()),t.isRendering=!1,!0}}else vdWidgetHandler.disconnectListeners(),utils.A.removeWidgetOnPage("vd-nudge");return t.isRendering=!1,!1}catch(e){return vdWidgetHandler._renderState&&(vdWidgetHandler._renderState.isRendering=!1),console.error("vdWidgetHandler.renderVdNudge : ",e),!1}},registerVdNudgeListeners:(e=!1)=>{try{return vdWidgetHandler.isVdNudgeListenersRegistered&&!e||(document.addEventListener("lb-dealeasy-vdn-add-to-cart",(async e=>{if(e&&e.detail&&"lb-vd-nudge"===e.detail.src){const t=e.detail,r={[t.key]:t.quantityToAdd},n=await src_cartHandler.updateCart(r,!0);if(n.success){const e=window.location.pathname.includes("/cart")?"reload_page":"refresh_cart";return await src_cartHandler.postAtcCartRefresh(e),window.dispatchEvent(new CustomEvent("lb-dealeasy-vdn-did-atc",{detail:{src:"lb-vd-nudge",...n}})),!0}window.dispatchEvent(new CustomEvent("lb-dealeasy-vdn-did-atc",{detail:{src:"lb-vd-nudge",...n}})),utils.A.errorLog("VdNudge atc error : ",n)}return!1})),vdWidgetHandler.isVdNudgeListenersRegistered=!0),!0}catch(e){return console.error("vdWidgetHandler.registerVdNudgeListeners : ",e),!1}},positionVdNudge:(e,t)=>{try{const r=window.location.pathname.includes("/cart")?e.cartPageLineCssSelector:e.cartDrawerLineCssSelector,n=window.location.pathname.includes("/cart")?e.cartPageLineItemCssSelector:e.cartDrawerLineItemCssSelector,o=window.location.pathname.includes("/cart")?e.cartPageLineItemPosition:e.cartDrawerLineItemPosition;if(r&&n&&o)if(utils.A.removeWidgetOnPage("vd-nudge"),document.querySelector(r)){const e=[];t.forEach((t=>{const i=Array.from(document.querySelectorAll(r)).at(t.cartLineItem.index);if(i){const e=i.querySelector(n);if(e){const t=document.createElement("lb-vd-nudge");e.insertAdjacentElement(o,t)}}else e.push(t.cartLineItem.index)})),e.length&&vdWidgetHandler.lazyLoadVdNudge(r)}else vdWidgetHandler.lazyLoadVdNudge(r);return!0}catch(e){return console.error("vdWidgetHandler.positionVdNudge : ",e),!1}},lazyLoadVdNudge:e=>{try{return vdWidgetHandler.observeElementInjection(e,(()=>{vdWidgetHandler.renderVdNudge()})),!0}catch(e){return console.error("vdWidgetHandler.lazyLoadVdNudge : ",e),!1}},observeElementInjection:(e,t)=>{try{const r=document.querySelector(e);return r?void t(r):(vdWidgetHandler.lazyPositionListener=new MutationObserver((r=>{r.some((r=>{if("childList"!==r.type)return!1;const n=Array.from(r.addedNodes).find((t=>t instanceof Element&&(!!t.matches(e)||t.querySelector(e))));if(n){const r=n.matches(e)?n:n.querySelector(e);return t(r),vdWidgetHandler.lazyPositionListener.disconnect(),!0}return!1}))})),vdWidgetHandler.lazyPositionListener.observe(document.body,{childList:!0,subtree:!0}),!0)}catch(e){return console.error("vdWidgetHandler.observeElementInjection : ",e),!1}},observeElementRemoval:e=>{try{let t;vdWidgetHandler.removalListener=new MutationObserver((()=>{const r=document.querySelectorAll("lb-vd-nudge").length;vdWidgetHandler.vdNudgeRenderCount&&vdWidgetHandler.vdNudgeRenderCount!==r&&(t&&clearTimeout(t),t=setTimeout((()=>{e()}),250))})),vdWidgetHandler.removalListener.observe(document.body,{childList:!0,subtree:!0})}catch(e){return console.error("vdWidgetHandler.observeElementRemoval : ",e),!1}},registerIntergration:()=>{try{const{product:e,discount:t}=vdWidgetHandler.getSetup()??{};return e&&t&&t.discountToSubscriptionProducts&&src_integrations.detectIntegration("lbOrdereasyProductReady",vdWidgetHandler.initDibsIntegration()),!0}catch(e){return console.error("vdWidgetHandler.registerIntergration : ",e),!1}},initDibsIntegration:async()=>{try{const{product:e,widgetSetup:t,discount:r}=vdWidgetHandler.getSetup()??{},{settings:n}=t??{};if("function"==typeof window.lbOrdereasyGetProducts&&r&&r.discountToSubscriptionProducts){const t=await src_integrations.getDibsSellingPlanData([e]),o=[];if(t){const i=vdWidgetHandler.transformProductDataForSellingPlans(t[e.id.split("/").pop()]);return o.push(...i),vdWidgetHandler.dibsSellingPlanData=o,"MANUAL_DETECT_ATC"!=n?.buyButtonType&&"AUTO_DETECT_ATC"!=n?.buyButtonType||vdWidgetHandler.appendQtySelectorAttributeOnProductForm(vdWidgetHandler.lastUpdatedFormPayload,r?.discountToSubscriptionProducts),!0}}}catch(e){return console.error("vdWidgetHandler.initDibsIntegration : ",e),!1}},transformProductDataForSellingPlans:e=>{try{const t=[];return e.forEach((e=>{e.applicableSellingPlans.forEach((r=>{const n=r.id.split("/").pop(),{associatedResourceType:o,availableQuantity:i,cartQuantity:a,contents:s}=r.sellingPlanGroup||{};if("variant"===o){const o=i?i-(a||0):1/0;t.push({id:n,isDefault:r.isDefault,availableVariants:[e.id.split("/").pop()],applicableQuantity:o,quantityError:s?.quantityValidationMessage})}else if("product"===o){const o=t.find((e=>e.id===n));if(o)o.availableVariants.includes(e.id.split("/").pop())||(o.availableVariants.push(e.id.split("/").pop()),o.applicableQuantity!==1/0&&(o.applicableQuantity-=a||0));else{const o=i?i-(a||0):1/0;t.push({id:n,isDefault:r.isDefault,availableVariants:[e.id.split("/").pop()],applicableQuantity:o,quantityError:s?.quantityValidationMessage})}}}))})),t}catch(e){return console.error("vdWidgetHandler.transformProductDataForSellingPlans error:",e),[]}}},widget_vd=vdWidgetHandler,mmbWidgetHandler={setup:void 0,setSetup:e=>(mmbWidgetHandler.setup=e,mmbWidgetHandler),getSetup:()=>mmbWidgetHandler.setup,lastFormState:void 0,formMutationObserver:void 0,lastUpdatedFormPayload:void 0,renderBundleBuilder:()=>{try{const{bundle:e,currentVariantId:t,components:r,pagination:n,widgetSetup:o,shop:i}=mmbWidgetHandler.getSetup()??{};if(e&&t&&r&&o&&i&&utils.A.positionWidget(o.bundleBuilder.position,"lb-bundle-builder","#lb-bundle-builder")){const a=document.querySelector("lb-bundle-builder"),s={code:Shopify.currency?.active,rate:Shopify.currency?.rate},d={...o.bundleBuilder.translations[Shopify.locale]||o.bundleBuilder.translations.default,bundleProductPicker:o.bundleProductPicker?.translations[Shopify.locale]||o.bundleProductPicker?.translations.default,bundleViewer:o.bundleViewer?.translations[Shopify.locale]||o.bundleViewer?.translations.default};if(a)return a.bundle=e,a.currentVariantId=t,a.components=r,a.pagination=n,a.setup={...o.bundleBuilder,bundleProductPicker:o.bundleProductPicker,bundleViewer:o.bundleViewer},a.translation=d,a.shopCurrency=i.shopCurrency,a.presentmentCurrency=s,a.editableQtySelector="boolean"==typeof editableQtySelector&&editableQtySelector,utils.A.hideElementsOnPage(screen.width>480?o.bundleBuilder.settings.desktopDefaultActionSelectors:o.bundleBuilder.settings.mobileDefaultActionSelectors),mmbWidgetHandler.registerBundlePopupListeners(),mmbWidgetHandler.registerBundleBuilderListeners(o.bundleBuilder.settings,"RenderBundleBuilder"),!0}return!1}catch(e){return console.error("mmbWidgetHandler.renderBundleBuilder : ",e),!1}},renderRelatedBundles:()=>{try{const{bundles:e,widgetSetup:t,shop:r}=mmbWidgetHandler.getSetup()??{};if(e&&t&&r&&utils.A.positionWidget(t.relatedBundles.position,"lb-related-bundles","#lb-related-bundles")){const n=document.querySelector("lb-related-bundles"),o={code:Shopify.currency?.active,rate:Shopify.currency?.rate},i=t.relatedBundles.translations[Shopify.locale]||t.relatedBundles.translations.default;if(n)return n.bundles=e,n.setup=t.relatedBundles,n.translation=i,n.shopCurrency=r.shopCurrency,n.presentmentCurrency=o,utils.A.hideElementsOnPage(screen.width>480?t.relatedBundles.settings.desktopDefaultActionSelectors:t.relatedBundles.settings.mobileDefaultActionSelectors),!0}return!1}catch(e){return console.error("mmbWidgetHandler.renderRelatedBundles : ",e),!1}},productFormMutationListener:()=>{try{const e=utils.A.getProductFormsOnPage(),t=["input","select","textarea"];return e.length>0&&(mmbWidgetHandler.formMutationObserver=new MutationObserver((e=>{let r=!1;e.forEach((e=>{if(!e.target||"lb-dealeasy-bundle-attribute"!==e.target.id){if("childList"===e.type){Array.from(e.addedNodes).concat(Array.from(e.removedNodes)).some((e=>e.nodeType===Node.ELEMENT_NODE&&("lb-dealeasy-bundle-attribute"!==e.id&&!e.querySelector("#lb-dealeasy-bundle-attribute")&&(t.includes(e.tagName.toLowerCase())||e.querySelector(t.join(","))))))&&(r=!0)}if("attributes"===e.type&&e.target){const n=e.target;if("lb-dealeasy-bundle-attribute"===n.id)return;t.includes(n.tagName.toLowerCase())&&(r=!0)}}})),r&&setTimeout((()=>{mmbWidgetHandler.lastFormState!==mmbWidgetHandler.getFormState()&&(mmbWidgetHandler.lastFormState=mmbWidgetHandler.getFormState(),mmbWidgetHandler.appendBundleAttributeOnProductForm(mmbWidgetHandler.lastUpdatedFormPayload,"ProductFormMutationListener"))}),50)})),e.forEach((e=>{e&&e.nodeType===Node.ELEMENT_NODE&&mmbWidgetHandler.formMutationObserver.observe(e,{childList:!0,subtree:!0,attributes:!0})}))),!0}catch(e){return console.error("mmbWidgetHandler.productFormMutationListener:",e),!1}},getFormState:()=>{try{const e=utils.A.getProductFormsOnPage(),t={};return e.forEach(((e,r)=>{const n=e.querySelectorAll('input:not([id="lb-dealeasy-bundle-attribute"]), select, textarea'),o=Array.from(n).map((e=>e.outerHTML));t[r]=o.join("")})),JSON.stringify(t)}catch(e){return console.error("mmbWidgetHandler.getFormState:",e),""}},cleanupFormMutationObserver:()=>{try{return mmbWidgetHandler.formMutationObserver?.disconnect(),mmbWidgetHandler.formMutationObserver=void 0,mmbWidgetHandler.lastFormState=void 0,!0}catch(e){return console.error("mmbWidgetHandler.cleanupFormMutationObserver:",e),!1}},registerBundleBuilderListeners:e=>{try{const t=document.querySelector("lb-bundle-builder");if(!("true"===t?.getAttribute("is-bundle-builder-listeners-registered"))){if("USE_BUNDLE_ATC"==e.buyButtonType)mmbWidgetHandler.registerBundleAtcListeners();else{utils.A.getProductFormsOnPage().forEach((e=>{e.addEventListener("submit",(e=>{e.target.action&&e.target.action.includes("/cart/add")&&window.dispatchEvent(new CustomEvent("lb-dealeasy-bb-refresh",{detail:{src:"lb-bundle-builder"}}))}))})),t.addEventListener("lb-dealeasy-bb-completed",(t=>{t.detail&&t.detail.bundle&&t.detail.selectedVariants&&(mmbWidgetHandler.disableAtcButtons(e.buyButtonSelectors,!1),mmbWidgetHandler.appendBundleAttributeOnProductForm(t.detail,"lb-dealeasy-bb-completed"),mmbWidgetHandler.lastUpdatedFormPayload=t.detail)})),t.addEventListener("lb-dealeasy-bb-incompleted",(()=>{mmbWidgetHandler.disableAtcButtons(e.buyButtonSelectors,!0),mmbWidgetHandler.appendBundleAttributeOnProductForm(void 0,"lb-dealeasy-bb-incompleted"),mmbWidgetHandler.lastUpdatedFormPayload=void 0})),mmbWidgetHandler.productFormMutationListener(),mmbWidgetHandler.appendBundleAttributeOnProductForm(mmbWidgetHandler.lastUpdatedFormPayload,"RegisterBundleBuilderListeners")}t.addEventListener("lb-dealeasy-bb-get-next-page",(e=>{e&&e.detail&&"lb-bundle-builder"===e.detail.src&&mmbWidgetHandler.paginateBundleBuilderProducts(e.detail)})),t.addEventListener("lb-dealeasy-bb-native-add-to-cart",(e=>{if(e&&e.detail&&"lb-bundle-builder"===e.detail.src){const t=e.detail.settings.buyButtonSelectors,r=utils.A.getAddToCartButtonOnPage(t);r&&r.click()}})),t.setAttribute("is-bundle-builder-listeners-registered","true")}return!0}catch(e){return console.error("mmbWidgetHandler.registerBundleBuilderListeners : ",e),!1}},registerBundlePopupListeners:()=>{try{const e=document.querySelector("lb-bundle-builder");return"true"===e?.getAttribute("is-popup-listener-registered")||(e.addEventListener("lb-dealeasy-pp-open",(e=>{const t=utils.A.appendModalOnPage();return t&&(t.modalType=e.detail.modalType,t.source=e.detail.source,t.modalSetup=e.detail,t.style.display="block"),!0})),e.addEventListener("lb-dealeasy-bv-open",(e=>{const t=utils.A.appendModalOnPage();return t&&(t.modalType=e.detail.modalType,t.source=e.detail.source,t.modalSetup=e.detail,t.style.display="block"),!0})),e.setAttribute("is-popup-listener-registered","true")),!0}catch(e){return console.error("mmbWidgetHandler.registerProductPickerListeners : ",e),!1}},registerBundleAtcListeners:()=>{try{return document.querySelector("lb-bundle-builder").addEventListener("lb-dealeasy-bb-add-to-cart",(async e=>{try{if(e&&e.detail&&"lb-bundle-builder"===e.detail.src){const{bundle:t,srcVariantId:r,srcProductId:n,selectedVariants:o,settings:i}=e.detail;if(t&&r&&o){const e=utils.A.getProductFormsOnPage(),{productFormProperties:a,productFormAttributes:s}=utils.A.getFormAttributesAndProperties(e),d=s.filter((e=>!["selling_plan","id","quantity"].includes(e.name))),c=[];if("DYNAMIC_PRICE_BUNDLE"===t.bundleType){const e=t.discount?`${t.discount.value}-${t.discount.type}`:void 0,i=`DB-${n}-${r}-${dayjs().unix()}${e?`-${e}`:""}`;o.forEach((e=>{c.push({...Object.fromEntries(d.map((e=>[e.name,e.value]))),id:e.variantId,quantity:e.quantity,properties:{__de_bundle_id:i,...Object.fromEntries(a.map((e=>[e.name,e.value])))}})}))}else{const e=`FB-${n}-${r}`,t=o.reduce(((e,t)=>(e[t.variantId]=t.quantity,e)),{}),i=o.reduce(((e,t)=>(e[t.title]=`x ${t.quantity}`,e)),{});c.push({id:r,quantity:1,properties:{__de_bundle_id:e,__de_bundle:JSON.stringify(t),...i,...Object.fromEntries(a.map((e=>[e.name,e.value])))},...Object.fromEntries(d.map((e=>[e.name,e.value])))})}const l=await src_cartHandler.addToCart(c,!0);return l.success?(await src_cartHandler.postAtcCartRefresh(i?.atcBtnAction),window.dispatchEvent(new CustomEvent("lb-dealeasy-bb-added-to-cart",{detail:{src:"lb-bundle-builder",status:"success",...l}})),!0):(window.dispatchEvent(new CustomEvent("lb-dealeasy-bb-added-to-cart",{detail:{src:"lb-bundle-builder",status:"error",...l}})),utils.A.errorLog("Bundle builder atc error",l),!1)}}return window.dispatchEvent(new CustomEvent("lb-dealeasy-bb-added-to-cart",{detail:{src:"lb-bundle-builder",status:"error"}})),utils.A.errorLog("Bundle builder atc error",addToCartRes),!1}catch(e){return console.error("mmbWidgetHandler.registerBundleAtcListeners : ",e),window.dispatchEvent(new CustomEvent("lb-dealeasy-bb-added-to-cart",{detail:{src:"lb-bundle-builder",status:"error"}})),utils.A.errorLog("Bundle builder atc error",e),!1}})),!0}catch(e){return console.error("mmbWidgetHandler.registerBundleAtcListeners : ",e),!1}},paginateBundleBuilderProducts:async({previousItems:e=[],cursor:t=null,maxNumberOfProductsToQuery:r=50})=>{try{const{bundle:n}=mmbWidgetHandler.getSetup(),{myShopifyDomain:o,accessToken:i}=src_setupHandler.getStoreSetup();if(n&&n.components&&o&&i){const a=await src_offers.getBundleComponents(o,i,n.components,e,n.componentsType,r,t);if(a&&a.components)return window.dispatchEvent(new CustomEvent("lb-dealeasy-bb-next-page",{detail:{src:"lb-bundle-builder",...a}})),!0}return window.dispatchEvent(new CustomEvent("lb-dealeasy-bb-next-page",{detail:{src:"lb-bundle-builder"}})),!1}catch(e){return console.error("mmbWidgetHandler.paginateBundleBuilderProducts : ",e),!1}},getBundleAttributes:(e,t,r,n,o)=>{try{const i=[];if("DYNAMIC_PRICE_BUNDLE"===e.bundleType){const a=e.discount?`${e.discount.value}-${e.discount.type}`:void 0,s=`DB-${t}-${r}-${dayjs().unix()}${a?`-${a}`:""}`,{productFormAttributes:d,productFormProperties:c}=utils.A.getFormAttributesAndProperties(o),l=d.filter((e=>!["selling_plan","id","quantity"].includes(e.name)));n.forEach(((e,t)=>{i.push(``,``,``,``),c.forEach((e=>{i.push(``)})),l.forEach((e=>{i.push(``)}))}))}else{const e=`FB-${t}-${r}`,o=n.reduce(((e,t)=>(e[t.variantId]=t.quantity,e)),{});i.push(``,``),n.forEach((e=>{i.push(``)}))}return i}catch(e){return console.error("mmbWidgetHandler.getBundleAttributes : ",e),[]}},appendBundleAttributeOnProductForm:(e,t="")=>{try{const t=utils.A.getProductFormsOnPage();if(t.forEach((e=>{e.querySelectorAll("#lb-dealeasy-bundle-attribute").forEach((e=>e.remove()))})),e){const{bundle:r,srcProductId:n,srcVariantId:o,selectedVariants:i}=e,a=mmbWidgetHandler.getBundleAttributes(r,n,o,i,t);"DYNAMIC_PRICE_BUNDLE"===r.bundleType&&utils.A.disableOriginalFormAttributes(t),t.forEach((e=>{a.forEach((t=>{e.insertAdjacentHTML("beforeend",t)}))}))}return!0}catch(e){return console.error("mmbWidgetHandler.appendBundleAttributeOnProductForm : ",e),!1}},disableAtcButtons:(e,t=!1)=>{try{return utils.A.getBuyButtonsOnProductForms(e).forEach((e=>{e.disabled=t,mmbWidgetHandler.listenAtcButtonStates(e,t)})),!0}catch(e){return console.error("mmbWidgetHandler.disableAtcButtons : ",e),!1}},listenAtcButtonStates:(e,t)=>{try{const r=new MutationObserver((n=>{n.forEach((n=>{"attributes"===n.type&&"disabled"===n.attributeName&&(e.disabled=t,r.disconnect())}))}));return r.observe(e,{attributes:!0,attributeFilter:["disabled"]}),!0}catch(e){return console.error("mmbWidgetHandler.listenAtcButtonStates : ",e),!1}}},widget_mmb=mmbWidgetHandler,cpbWidgetHandler={setup:void 0,recommendationSetup:void 0,setSetup:e=>(cpbWidgetHandler.setup=e,cpbWidgetHandler),getSetup:()=>cpbWidgetHandler.setup,setRecommendationSetup:e=>(cpbWidgetHandler.recommendationSetup=e,cpbWidgetHandler),getRecommendationSetup:()=>cpbWidgetHandler.recommendationSetup,cpbRenderCount:0,cpbLastRenderCartTotal:0,recommendationRenderCount:0,recommendationLastRenderCartTotal:0,lazyPositionListener:void 0,removalListener:void 0,recommendationLazyPositionListener:void 0,recommendationRemovalListener:void 0,isCpbListenersRegistered:!1,isRecommendationListenersRegistered:!1,disconnectListeners:()=>(cpbWidgetHandler.lazyPositionListener&&cpbWidgetHandler.lazyPositionListener.disconnect(),cpbWidgetHandler.removalListener&&cpbWidgetHandler.removalListener.disconnect(),cpbWidgetHandler.resetRenderState(),!0),disconnectRecommendationListeners:()=>(cpbWidgetHandler.recommendationLazyPositionListener&&cpbWidgetHandler.recommendationLazyPositionListener.disconnect(),cpbWidgetHandler.recommendationRemovalListener&&cpbWidgetHandler.recommendationRemovalListener.disconnect(),cpbWidgetHandler.resetRecommendationRenderState(),!0),resetRenderState:()=>{cpbWidgetHandler._renderState={isRendering:!1,lastRenderTime:0,pendingRender:!1,renderCount:0,maxRenders:15,throttleTime:500}},resetRecommendationRenderState:()=>{cpbWidgetHandler._recommendationRenderState={isRendering:!1,lastRenderTime:0,pendingRender:!1,renderCount:0,maxRenders:5,throttleTime:500}},render:(e=!1)=>{try{cpbWidgetHandler._renderState||cpbWidgetHandler.resetRenderState();const t=cpbWidgetHandler._renderState,r=Date.now();if(t.isRendering||r-t.lastRenderTime{t.pendingRender=!1,cpbWidgetHandler.render(!0)}),t.throttleTime)),!1;if(t.isRendering=!0,t.lastRenderTime=r,t.renderCount++,t.renderCount>t.maxRenders)return cpbWidgetHandler.disconnectListeners(),!1;const{cartValueGoals:n,cartTotal:o,unClaimedGiftProducts:i,selectedProducts:a,widgetSetup:s,shop:d}=cpbWidgetHandler.getSetup()??{};if(n&&o>=0&&s&&d&&cpbWidgetHandler.positionCartProgressBar(s.position)){const r=document.querySelectorAll("lb-cart-progress-bar"),c={code:Shopify.currency?.active,rate:Shopify.currency?.rate},l=s.translations[Shopify.locale]||s.translations.default;return cpbWidgetHandler.cpbRenderCount=r.length,r.forEach((e=>{e.cartValueGoals=n,e.cartTotal=cpbWidgetHandler.cpbLastRenderCartTotal,e.setup=s,e.translation=cpbWidgetHandler.getTransaltions(l,s.translations.default),e.shopCurrency=d.shopCurrency,e.presentmentCurrency=c,e.unClaimedGiftProducts=i,e.selectedProducts=a,e.minimizeFreeGiftTitle="undefined"==typeof minimizeFreeGiftTitle||minimizeFreeGiftTitle,e.isRtlLanguageStore="undefined"!=typeof isRtlLanguageStore&&isRtlLanguageStore})),setTimeout((()=>{r.forEach((e=>{e.cartTotal=o})),cpbWidgetHandler.cpbLastRenderCartTotal=o,requestAnimationFrame((()=>{cpbWidgetHandler.renderRecommendations()}))}),800),e||(cpbWidgetHandler.observeElementRemoval((()=>{cpbWidgetHandler._renderState.renderCount=0,cpbWidgetHandler.render(!0)})),cpbWidgetHandler.registerCartProgressBarListeners(),cpbWidgetHandler.registerRecommendationListeners()),t.isRendering=!1,!0}return t.isRendering=!1,!1}catch(e){return cpbWidgetHandler._renderState&&(cpbWidgetHandler._renderState.isRendering=!1),console.error("cpbWidgetHandler.renderCartProgressBar : ",e),!1}},renderRecommendations:(e=!1)=>{cpbWidgetHandler._recommendationRenderState||cpbWidgetHandler.resetRecommendationRenderState();const{recommendations:t,widgetSetup:r,shop:n}=cpbWidgetHandler.getRecommendationSetup()??{};if(!t?.length||!r||!n)return!1;e||cpbWidgetHandler.positionRecommendations(r.settings.widgetPosition);const o=document.querySelectorAll("lb-recommendations");if(!o.length)return!1;cpbWidgetHandler.recommendationRenderCount=o.length;const i=r.translations[Shopify?.locale]||r.translations.default,a={code:Shopify.currency?.active,rate:Shopify.currency?.rate};return o.forEach((e=>{e.recommendations=t,e.setup=r,e.translation=cpbWidgetHandler.getTransaltions(i,r.translations.default,"recommendations"),e.shopCurrency=n.shopCurrency,e.presentmentCurrency=a,e.isRtlLanguageStore="undefined"!=typeof isRtlLanguageStore&&isRtlLanguageStore})),!0},registerCartProgressBarListeners:(e=!1)=>{try{return cpbWidgetHandler.isCpbListenersRegistered&&!e||(document.addEventListener("lb-dealeasy-ol-open",(e=>{cpbWidgetHandler.renderOfferListPopup(e.detail)})),document.addEventListener("lb-dealeasy-gpp-update",(async e=>{if(e&&e.detail&&"lb-cart-progress-bar"===e.detail.source){const{productsToAdd:t=[]}=e.detail;if(t&&t.length)return await cpbWidgetHandler.updateCartAfterGiftProductPicker({source:"lb-cart-progress-bar",productsToAdd:t}),!0}return!1})),document.addEventListener("lb-dealeasy-gpp-open",(e=>{if(e&&e.detail)if("lb-cart-progress-bar"===e.detail.source)cpbWidgetHandler.openGiftProductPicker(e.detail);else if("lb-cpb-offers-list"===e.detail.source){const t={...e.detail,quickPreview:!0,backNavigation:()=>(document.dispatchEvent(new CustomEvent("lb-dealeasy-ol-open",{detail:e.detail.selectedProducts})),!0)};cpbWidgetHandler.openGiftProductPicker(t)}})),cpbWidgetHandler.isCpbListenersRegistered=!0),!0}catch(e){return console.error("cpbWidgetHandler.registerListeners : ",e),!1}},positionCartProgressBar:e=>{try{let t=!1;if("appBlock"===e.positionType){const r=document.querySelectorAll("#lb-cart-progress-bar");if(r&&r.length&&(r.forEach((e=>{if(!e.querySelector("lb-cart-progress-bar")){const t=document.createElement("lb-cart-progress-bar");e.insertAdjacentElement("beforeend",t)}})),t=!0),e.cartDrawer&&e.cartDrawer.isEnabled){const r=screen.width<=480?e.cartDrawer.mobilePosition:e.cartDrawer.desktopPosition,n=screen.width<=480?e.cartDrawer.mobileCssSelector?.split(",").map((e=>e.trim())):e.cartDrawer.desktopCssSelector?.split(",").map((e=>e.trim()));if(r&&n&&n.length){const e=[];document.querySelectorAll("lb-cart-progress-bar").forEach((t=>{t&&t.positionSelector&&e.push(t.positionSelector)})),[...new Set([...n])].filter((t=>!e.includes(t))).forEach((e=>{const t=document.querySelectorAll(e);t&&t.length?t.forEach((t=>{const n=document.createElement("lb-cart-progress-bar");n.positionedInCartDrawer=!0,n.positionSelector=e,t.insertAdjacentElement(r,n)})):cpbWidgetHandler.lazyLoadCartProgressBar(e)}))}t=!0}return t}{const t=screen.width<=480?e.mobilePosition:e.desktopPosition,r=screen.width<=480?e.mobileCssSelector.split(",").map((e=>e.trim())):e.desktopCssSelector.split(",").map((e=>e.trim())),n=screen.width<=480?e.cartDrawer?.mobilePosition:e.cartDrawer?.desktopPosition,o=e.cartDrawer&&e.cartDrawer.isEnabled?screen.width<=480?e.cartDrawer?.mobileCssSelector?.split(",").map((e=>e.trim())):e.cartDrawer?.desktopCssSelector?.split(",").map((e=>e.trim())):[],i=[];document.querySelectorAll("lb-cart-progress-bar").forEach((e=>{e&&e.positionSelector&&i.push(e.positionSelector)}));("aboveCartForm"===t?['form[action*="/cart"][method="post"]']:[...new Set([...r,...o])]).filter((e=>!i.includes(e))).forEach((e=>{const r=document.querySelectorAll(e);r&&r.length?r.forEach((r=>{const i=document.createElement("lb-cart-progress-bar");o.includes(e)?(i.positionedInCartDrawer=!0,i.positionSelector=e,r.insertAdjacentElement(n,i)):(i.positionSelector=e,r.insertAdjacentElement("aboveCartForm"===t?"afterbegin":t,i))})):cpbWidgetHandler.lazyLoadCartProgressBar(e)}))}return!0}catch(e){return console.error("cpbWidgetHandler.positionCartProgressBar : ",e),!1}},positionRecommendations:(e="ALL_PAGES")=>{try{const t=window.location.pathname.includes("/cart");return document.querySelectorAll("lb-cart-progress-bar").forEach((r=>{if(!r?.querySelector("lb-recommendations")){const n=document.createElement("lb-recommendations"),o=r.querySelector(".lb-rc-placeholder");o?"ALL_PAGES"===e?o.insertAdjacentElement("beforeend",n):(t&&("CART_PAGE"!==e||r.positionedInCartDrawer?"CART_AND_DRAWER"===e&&o.insertAdjacentElement("beforeend",n):o.insertAdjacentElement("beforeend",n)),"CART_DRAWER"!==e&&"CART_AND_DRAWER"!==e||!r.positionedInCartDrawer||(n.positionedInCartDrawer=!0,o.insertAdjacentElement("beforeend",n))):cpbWidgetHandler.lazyLoadRecommendations("lb-cart-progress-bar .lb-rc-placeholder")}})),!0}catch(e){return console.error("cpbWidgetHandler.positionRecommendations:",e),!1}},lazyLoadRecommendations:e=>{try{return cpbWidgetHandler.observeRecommendationElementInjection(e,(()=>{cpbWidgetHandler.renderRecommendations("Cpb lazyLoadRecommendations")})),!0}catch(e){return console.error("cpbWidgetHandler.lazyLoadRecommendations:",e),!1}},observeRecommendationElementInjection:(e,t)=>{try{const r=document.querySelector(e);return r?void t(r):(cpbWidgetHandler.lazyPositionListener=new MutationObserver((r=>{r.some((r=>{if("childList"!==r.type)return!1;const n=Array.from(r.addedNodes).find((t=>t instanceof Element&&(!!t.matches(e)||t.querySelector(e))));if(n){const r=n.matches(e)?n:n.querySelector(e);return t(r),cpbWidgetHandler.lazyPositionListener.disconnect(),!0}return!1}))})),cpbWidgetHandler.lazyPositionListener.observe(document.body,{childList:!0,subtree:!0}),!0)}catch(e){return console.error("cpbWidgetHandler.observeElementInjection:",e),!1}},observeRecommendationElementRemoval:e=>{try{return cpbWidgetHandler.recommendationRemovalListener=new MutationObserver((()=>{const t=document.querySelectorAll("lb-recommendations").length;cpbWidgetHandler.recommendationRenderCount&&cpbWidgetHandler.recommendationRenderCount!==t&&e()})),cpbWidgetHandler.recommendationRemovalListener.observe(document.body,{childList:!0,subtree:!0}),!0}catch(e){return console.error("cpbWidgetHandler.observeRecommendationElementRemoval:",e),!1}},registerRecommendationListeners:(e=!1)=>{try{return cpbWidgetHandler.isRecommendationListenersRegistered&&!e||(document.addEventListener("lb-dealeasy-rc-atc",(async e=>{try{if(e&&e.detail&&"lb-recommendations"===e.detail.src){let t=e.detail;if(t.productsToAdd&&t.productsToAdd.length){let e=await src_cartHandler.addToCart(t.productsToAdd,!0);if(e&&e.success){const t=window.location.pathname.includes("/cart")?"reload_page":"refresh_cart";return await src_cartHandler.postAtcCartRefresh(t),window.dispatchEvent(new CustomEvent("lb-dealeasy-rc-did-atc",{detail:{src:"lb-recommendations",...e}})),!0}window.dispatchEvent(new CustomEvent("lb-dealeasy-rc-did-atc",{detail:{src:"lb-recommendations",...e}})),utils.A.errorLog("Recommendation atc error : ",e)}}return!1}catch(e){return console.error("cpbWidgetHandler.registerRecommendationListeners : ",e),!1}})),cpbWidgetHandler.isRecommendationListenersRegistered=!0),!0}catch(e){return console.error("cpbWidgetHandler.registerRecommendationListeners : ",e),!1}},renderOfferListPopup:e=>{try{const{cartValueGoals:t,widgetSetup:r,shop:n}=cpbWidgetHandler.getSetup();if(t&&t.length&&r&&n){const o={cartValueGoals:t,setup:r.offersPopup,shopCurrency:n.shopCurrency,presentmentCurrency:{code:Shopify.currency?.active,rate:Shopify.currency?.rate},translation:r.translations[Shopify.locale]||r.translations.default,selectedProducts:e.selectedProducts??[]},i=utils.A.appendModalOnPage();if(i)return i.modalType="lb-cpb-offers-list",i.source="lb-cart-progress-bar",i.modalSetup=o,i.style.display="block",!0}return!1}catch(e){return console.error("cpbWidgetHandler.renderOfferPopup : ",e),!1}},renderGiftProductPicker:async(e,t,r=[],n=[],o=!1,i=void 0)=>{try{if(r&&r.length&&e&&t){const a=e.translations[Shopify.locale]||e.translations.default,s=r[0].addProductAgainIfRemoved,d={giftProductOptions:r.map((e=>({id:e.id,goalValue:e.goalValue,currencyCode:e.currencyCode,currencyFormat:e.currencyFormat,translation:e.translation,productVariants:e.offerValue}))),selectedGiftVariants:n,lineItemPropertyKey:"__dealeasy_gift_product",quickPreview:o,backNavigation:i,isMandatoryGiftSelection:s,isStackableGiftSelection:r.length>1,setup:e.freeGiftPopup,shopCurrency:t.shopCurrency,initialGiftProductDisplayCount:"number"==typeof dealeasyGppInitialProductCount?dealeasyGppInitialProductCount:3,presentmentCurrency:{code:Shopify.currency?.active,rate:Shopify.currency?.rate},translation:cpbWidgetHandler.getTransaltions(a,e.translations.default,"giftProductPicker")};await utils.A.checkModalOnPage("lb-cart-progress-bar");const c=utils.A.appendModalOnPage();if(c)return c.modalType="lb-gift-product-picker",c.source="lb-cart-progress-bar",c.modalSetup=d,c.style.display="block",new Promise(((e,t)=>{c.addEventListener("lb-dealeasy-gpp-update",(r=>{if(r.detail){const{productsToAdd:t=[],productsToRemove:n=[],productOptionsToBeIgnored:o=[]}=r.detail;e({src:"lb-gift-product-picker",productsToAdd:t,productsToRemove:n,productOptionsToBeIgnored:o})}t(void 0)}))}))}return}catch(e){return void console.error("cpbWidgetHandler.renderGiftProductPicker : ",e)}},openGiftProductPicker:async e=>{try{const{widgetSetup:t,shop:r}=cpbWidgetHandler.getSetup();if(e.giftProductOptions&&e.giftProductOptions.length&&t&&r){const{giftProductOptions:n,selectedGiftVariants:o=[],quickPreview:i=!1,backNavigation:a}=e,s=await cpbWidgetHandler.renderGiftProductPicker(t,r,n,o,i,a);if(s)return await cpbWidgetHandler.updateCartAfterGiftProductPicker(s),window.dispatchEvent(new CustomEvent("lb-dealeasy-gpp-close",{detail:{src:"openGiftProductPicker"}})),!0}return!1}catch(e){return console.error("cpbWidgetHandler.openGiftProductPicker : ",e),!1}},updateCartAfterGiftProductPicker:async e=>{try{let t,r;if(e.productsToRemove&&e.productsToRemove.length){const r=await src_cartHandler.getCart(),n=r.items.filter((e=>e.properties.__dealeasy_gift_product&&e.properties.__dealeasy_gift_product)).filter((t=>e.productsToRemove.includes(t.variantId.toString())));if(n&&n.length){const r={};n.forEach((e=>{r[e.key]=0})),t=await src_cartHandler.updateCart(r,!(e.productsToAdd&&e.productsToAdd.length))}}if(e.productsToAdd&&e.productsToAdd.length&&(r=await src_offers.addProductsToCart(e.productsToAdd,!0)),e.productOptionsToBeIgnored&&e.productOptionsToBeIgnored.length){const t=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-added-gift-goals")||"[]"):[];t.push(...e.productOptionsToBeIgnored),sessionStorage.setItem("dealeasy-added-gift-goals",JSON.stringify(t))}return(t&&t.success||r&&r.success)&&await src_cartHandler.refreshCart(),!0}catch(e){return console.error("cpbWidgetHandler.updateCartAfterGiftProductPicker : ",e),!1}},lazyLoadCartProgressBar:e=>{try{return cpbWidgetHandler.observeElementInjection(e,(()=>{cpbWidgetHandler.render(),cpbWidgetHandler.renderRecommendations("")})),!0}catch(e){return console.error("cpbWidgetHandler.lazyLoadCartProgressBar : ",e),!1}},observeElementInjection:(e,t)=>{try{const r=document.querySelector(e);return r?void t(r):(cpbWidgetHandler.lazyPositionListener=new MutationObserver((r=>{r.some((r=>{if("childList"!==r.type)return!1;const n=Array.from(r.addedNodes).find((t=>t instanceof Element&&(!!t.matches(e)||t.querySelector(e))));if(n){const r=n.matches(e)?n:n.querySelector(e);return t(r),cpbWidgetHandler.lazyPositionListener.disconnect(),!0}return!1}))})),cpbWidgetHandler.lazyPositionListener.observe(document.body,{childList:!0,subtree:!0}),!0)}catch(e){return console.error("cpbWidgetHandler.observeElementInjection : ",e),!1}},observeElementRemoval:e=>{try{cpbWidgetHandler.removalListener=new MutationObserver((()=>{const t=document.querySelectorAll("lb-cart-progress-bar").length;cpbWidgetHandler.cpbRenderCount&&cpbWidgetHandler.cpbRenderCount!==t&&e()})),cpbWidgetHandler.removalListener.observe(document.body,{childList:!0,subtree:!0})}catch(e){return console.error("cpbWidgetHandler.observeElementRemoval : ",e),!1}},getTransaltions:(e,t,r="cartProgressBar")=>"giftProductPicker"===r?{headerText:e.freeGiftPopupHeaderText||t.freeGiftPopupHeaderText,descriptionText:e.freeGiftPopupTitleText||t.freeGiftPopupTitleText,atcText:e.freeGiftPopupAtcBtnText||t.freeGiftPopupAtcBtnText,claimedText:e.freeGiftPopupClaimedBtnText||t.freeGiftPopupClaimedBtnText,freePriceText:e.freeGiftPopupDiscountText||t.freeGiftPopupDiscountText,claimText:e.freeGiftPopupSelectBtnText||t.freeGiftPopupSelectBtnText,ignoreGiftText:e.freeGiftPopupIgnoreBtnText||t.freeGiftPopupIgnoreBtnText,continueText:e.freeGiftPopupContinueBtnText||t.freeGiftPopupContinueBtnText,warningText:e.freeGiftPopupInfoText||t.freeGiftPopupInfoText,previousNavText:e.freeGiftMultipleTierBackBtnText||t.freeGiftMultipleTierBackBtnText,stackableHeaderText:e.freeGiftMultipleTierHeaderText||t.freeGiftMultipleTierHeaderText,stackableDescriptionText:e.freeGiftMultipleTierTitleText||t.freeGiftMultipleTierTitleText}:"recommendations"===r?{recommendationTitleText:e?.recommendationTitleText||t?.recommendationTitleText,recommendationAtcBtnText:e?.recommendationAtcBtnText||t?.recommendationAtcBtnText,recommendationPreviewBtnText:e?.recommendationPreviewBtnText||t?.recommendationPreviewBtnText}:{...e,freeShippingDiscountText:e.freeShippingDiscountText||t.freeShippingDiscountText,shippingDiscountText:e.shippingDiscountText||t.shippingDiscountText,freeGiftDiscountText:e.freeGiftDiscountText||t.freeGiftDiscountText,tieredCartDiscountText:e.tieredCartDiscountText||t.tieredCartDiscountText,emptyCartText:e.emptyCartText||t.emptyCartText,progressText:e.progressText||t.progressText,achievedText:e.achievedText||t.achievedText,unlockedRewardsText:e?.unlockedRewardsText||t?.unlockedRewardsText,popupHeaderText:e.popupHeaderText||t?.popupHeaderText,popupDiscountDetailText:e.popupDiscountDetailText||t.popupDiscountDetailText,popupShippingDiscountHeading:e.popupShippingDiscountHeading||t.popupShippingDiscountHeading,popupFreeGiftDiscountHeading:e.popupFreeGiftDiscountHeading||t.popupFreeGiftDiscountHeading,popupTieredCartDiscountHeading:e.popupTieredCartDiscountHeading||t.popupTieredCartDiscountHeading}},widget_cpb=cpbWidgetHandler,bogoWidgetHandler={setup:void 0,setSetup:e=>(bogoWidgetHandler.setup=e,bogoWidgetHandler),getSetup:()=>bogoWidgetHandler.setup,bogoOfferResources:void 0,render:()=>{try{const{currentProductBogoOffer:e,widgetSetup:t}=bogoWidgetHandler.getSetup(),r=t?.bogoBanner;if(e&&e?.renderCombination&&r&&utils.A.positionWidget(r.position,"lb-bogo-banner","#lb-bogo-banner")){const t=document.querySelector("lb-bogo-banner");if(t)return t.offer=e,t.currentTierCombination=e.renderCombination,t.setup=r,t.translation=r.translations[Shopify.locale]||r.translations.default,bogoWidgetHandler.registerBogoBannerListeners(),bogoWidgetHandler.getResources(e.appliesTo,e.selectedItems),bogoWidgetHandler.preloadResources(e.appliesTo,e.selectedItems),!0}return!1}catch(e){return console.error("bogoWidgetHandler.render : ",e),!1}},registerBogoBannerListeners:()=>{try{const e=document.querySelector("lb-bogo-banner");return"true"===e?.getAttribute("is-bogo-banner-listeners-registered")||(e.setAttribute("is-bogo-banner-listeners-registered","true"),e.addEventListener("lb-bgb-redirect-to-other-products",(e=>{if("lb-bogo-banner"===e.detail.src&&e.detail.resourceType&&e.detail.resouces){const e=bogoWidgetHandler.bogoOfferResources;e&&e.length&&(e.length>1?bogoWidgetHandler.renderProductsList(e):window.open(e[0].onlineStoreUrl,"_blank"))}return!0}))),!0}catch(e){return console.error("bogoWidgetHandler.registerBogoBannerListeners : ",e),!1}},preloadResources:async(e,t)=>{try{const r=await src_setupHandler.getResources(e,t);return!(!r||!r.length)&&(bogoWidgetHandler.bogoOfferResources=r,!0)}catch(e){return console.error("bogoWidgetHandler.preloadResources : ",e),!1}},getResources:async(e,t)=>{try{const{myShopifyDomain:r,accessToken:n}=src_setupHandler.getStoreSetup();if(r&&n){const o="PRODUCTS"===e?await src_setupHandler.getProducts(r,n,"ID",t):await src_setupHandler.getCollections(r,n,t);if(o&&o.length)return bogoWidgetHandler.bogoOfferResources=o,!0}return!1}catch(e){return console.error("bogoWidgetHandler.getResources : ",e),!1}},renderProductsList:(e=[])=>{try{const{widgetSetup:t}=bogoWidgetHandler.getSetup();if(t&&t.productsList&&e.length){const r=t.productsList.translations[Shopify.locale]||t.productsList.translations.default,n=utils.A.appendModalOnPage();n.source="lb-bogo-banner",n.modalType="lb-products-list",n.modalSetup={setup:{...t.productsList,translation:r},translation:r,resources:e},document.querySelector("lb-dealeasy-modal").style.display="block"}return!1}catch(e){return console.error("bogoWidgetHandler.renderProductsList : ",e),!1}}},widget_bogo=bogoWidgetHandler,gwpWidgetHandler={setup:void 0,setSetup:e=>(gwpWidgetHandler.setup=e,gwpWidgetHandler),getSetup:()=>gwpWidgetHandler.setup,render:()=>{try{const{combinations:e,widgetSetup:t,shop:r,currentProduct:n}=gwpWidgetHandler.getSetup(),o=t?.giftWithProductBanner,i={code:Shopify.currency?.active,rate:Shopify.currency?.rate};if(e&&e.length&&o&&utils.A.positionWidget(o.position,"lb-gift-with-product","#lb-gift-with-product")){const t=document.querySelector("lb-gift-with-product");if(t)return t.combinations=e,t.setup=o,t.product=n,t.translation=o.translations[Shopify.locale]||o.translations.default,t.shopCurrency=r.shopCurrency,t.presentmentCurrency=i,gwpWidgetHandler.registergiftWithProductBannerListeners(),gwpWidgetHandler.otherProductNavigation(e[0].appliesTo,e[0].selectedItems.filter((e=>e!==n.id)),e[0].rewardStrategy),!0}}catch(e){return console.error("gwpWidgetHandler.render : ",e),!1}},registergiftWithProductBannerListeners:()=>{try{const e=document.querySelector("lb-gift-with-product");"true"===e?.getAttribute("is-listeners-registered")||(e.setAttribute("is-listeners-registered","true"),document.addEventListener("lb-dealeasy-pl-open",(e=>{e&&e.detail&&"lb-gift-with-product"===e.detail.src&&gwpWidgetHandler.renderProductsList(e.detail.resources)})),document.addEventListener("lb-dealeasy-gpp-update",(async e=>{if(e&&e.detail&&"lb-gift-with-product"===e.detail.src)return!(!e?.detail?.productsToAdd||!e.detail.productsToAdd.length)&&(await gwpWidgetHandler.updateGiftProductsOnCart(e.detail),!0)})),document.addEventListener("lb-dealeasy-gpp-open",(e=>{if(e&&e.detail&&"lb-gift-with-product"===e.detail.src){const{widgetSetup:t,shop:r}=gwpWidgetHandler.getSetup();gwpWidgetHandler.openGiftProductPicker(e.detail.giftProductOptions,e.detail.selectedGiftVariants,t?.giftProductPicker,r)}})))}catch(e){return console.error("gwpWidgetHandler.registergiftWithProductBannerListeners : ",e),!1}},otherProductNavigation:async(e,t,r)=>{try{if("ALL"===e||"INDIVIDUAL_QUANTITY"===r||0===t.length)return!0;{const r=await src_setupHandler.getResources(e,t);return!(!r||!r.length)&&(window.dispatchEvent(new CustomEvent("lb-dealeasy-gwp-other-product-navigation",{detail:{resources:r,required:!0,src:"lb-gift-with-product"}})),!0)}}catch(e){return console.error("gwpWidgetHandler.otherProductNavigation : ",e),!1}},renderProductsList:(e=[])=>{try{const{widgetSetup:t}=gwpWidgetHandler.getSetup();if(t&&t.productsList&&e.length){const r=t.productsList.translations[Shopify.locale]||t.productsList.translations.default,n=utils.A.appendModalOnPage();n.source="lb-gift-with-product",n.modalType="lb-products-list",n.modalSetup={setup:{...t.productsList,translation:r},translation:r,resources:e},document.querySelector("lb-dealeasy-modal").style.display="block"}return!1}catch(e){return console.error("gwpWidgetHandler.renderProductsList : ",e),!1}},renderGiftProductPicker:async(e=[],t=[],r,n)=>{try{if(e&&e.length&&r&&n){const o=r.translations[Shopify.locale]||r.translations.default,i=e[0].isMandatory,a={giftProductOptions:e.map((e=>({id:e.id,currencyCode:e.currencyCode,currencyFormat:e.currencyFormat,productVariants:e.productsToBeAdded}))),selectedGiftVariants:t,lineItemPropertyKey:"__dealeasy_gwp",quickPreview:!1,backNavigation:void 0,isMandatoryGiftSelection:i,isStackableGiftSelection:e.length>1,setup:r,translation:o,shopCurrency:n.shopCurrency,presentmentCurrency:{code:Shopify.currency?.active,rate:Shopify.currency?.rate},initialGiftProductDisplayCount:"number"==typeof dealeasyGppInitialProductCount?dealeasyGppInitialProductCount:3};await utils.A.checkModalOnPage("lb-gift-with-product");const s=utils.A.appendModalOnPage();return s?(s.modalType="lb-gift-product-picker",s.source="lb-gift-with-product",s.modalSetup=a,s.style.display="block",new Promise(((e,t)=>{s.addEventListener("lb-dealeasy-gpp-update",(r=>{if(r.detail){const{productsToAdd:t=[],productsToRemove:n=[],productOptionsToBeIgnored:o=[]}=r.detail;e({src:"lb-gift-product-picker",productsToAdd:t,productsToRemove:n,productOptionsToBeIgnored:o})}t(void 0)}))}))):void 0}}catch(e){return console.error("gwpWidgetHandler.renderGiftProductPicker : ",e),!1}},openGiftProductPicker:async(e=[],t=[],r,n)=>{try{if(e&&e.length){const o=await gwpWidgetHandler.renderGiftProductPicker(e,t,r,n);if(o)return await gwpWidgetHandler.updateGiftProductsOnCart(o),window.dispatchEvent(new CustomEvent("lb-dealeasy-gpp-close",{detail:{src:"openGiftProductPicker"}})),!0}return!1}catch(e){return console.error("gwpWidgetHandler.openGiftProductPicker : ",e),!1}},updateGiftProductsOnCart:async e=>{try{let t,r;if(e.productsToRemove&&e.productsToRemove.length){const r=await src_cartHandler.getCart(),n=r.items.filter((e=>e.properties.__dealeasy_gwp&&e.properties.__dealeasy_gwp)).filter((t=>e.productsToRemove.includes(t.variantId.toString())));if(n&&n.length){const r={};n.forEach((e=>{r[e.key]=0})),t=await src_cartHandler.updateCart(r,!(e.productsToAdd&&e.productsToAdd.length))}}if(e.productsToAdd&&e.productsToAdd.length&&(r=await src_offers.addGwpProductsToCart(e.productsToAdd,!0)),e.productOptionsToBeIgnored&&e.productOptionsToBeIgnored.length){const t=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-added-gwp-gifts")||"[]"):[];t.push(...e.productOptionsToBeIgnored),sessionStorage.setItem("dealeasy-added-gwp-gifts",JSON.stringify(t))}return(t&&t.success||r&&r.success)&&await src_cartHandler.refreshCart(),!0}catch(e){return console.error("gwpWidgetHandler.updateGiftProductsOnCart : ",e),!1}}},widget_gwp=gwpWidgetHandler;!function(e){const t=e.Shopify.shop,r="boolean"==typeof stopCartActionModification&&stopCartActionModification,n="boolean"==typeof dealeasyInterruptCartAction&&dealeasyInterruptCartAction,o="boolean"==typeof stopDiscountCodeAutoApply&&stopDiscountCodeAutoApply,i="boolean"==typeof dealeasyStopCartRefresh&&dealeasyStopCartRefresh,a="boolean"==typeof dealeasyDontUseJQueryListeners&&dealeasyDontUseJQueryListeners,s="boolean"==typeof dealeasyEnableDebounce&&dealeasyEnableDebounce,d="number"==typeof dealeasyDebounceWaitTime?dealeasyDebounceWaitTime:500,c="boolean"==typeof dealeasyIsB2BCustomer&&dealeasyIsB2BCustomer,l="object"==typeof dealeasyCustomer&&dealeasyCustomer.id?dealeasyCustomer:void 0;async function u(e){try{const{offers:t,product:r,shop:n}=src_setupHandler.getStoreSetup();if(t&&t.discounts.length&&r){const o=utils.A.getCurrentProduct(r,e);if(o){const e=src_offers.getMaximumProductDiscount(t.discounts,o),r=src_setupHandler.getWidgetSetupByType(e?.widgetType??"widget#vdtable");if(e&&r&&n)return utils.A.log("Volume discount",e),widget_vd.setSetup({discount:e,product:o,widgetSetup:r,shop:n}).render(),!0}}return utils.A.removeWidgetOnPage("volume-discount"),!1}catch(e){return console.error("fn.processVolumeDiscount : ",e),!1}}async function p(e){try{const{offers:r,product:n,shop:o}=src_setupHandler.getStoreSetup();if(r&&r.bundles.length&&n){const i=utils.A.getCurrentProduct(n,e),a=await src_setupHandler.getStoreFrontAccessToken(t),s=src_setupHandler.getWidgetSetupByType("widget#mmBundle"),d=r.bundles?.find((e=>e?.id===i?.id));if(d&&s&&o){const e=document.querySelector("lb-bundle-builder");if(e)return e.currentVariantId=i.currentVariant.id,!0;{const e=src_offers.getFormattedBundle(d,i),r="display_all"==s.bundleBuilder.settings.expandDisplayProductsCount?50:Number(s.bundleBuilder.settings.expandDisplayProductsCount),n=await src_offers.getBundleComponents(t,a,e.components,[],e.componentsType,r);if(e&&n&&n.components)return utils.A.log("Mix & match bundle",{parentBundle:e,bundleComponents:n}),widget_mmb.setSetup({bundle:e,currentVariantId:i.currentVariant.id,components:n.components,pagination:n.pagination,widgetSetup:s,shop:o}).renderBundleBuilder(),!0}}else{const e=r.bundles.filter((e=>!!e.showBundleOnChildProducts&&("collections"===e.componentsType?e.components.some((e=>e.collections.some((e=>i.collections.includes(e))))):e.components.some((e=>e.products.some((e=>{const t=e.id.includes(i.id),r=e.variants.some((e=>!i.currentVariant.id||e.includes(i.currentVariant.id)));return t&&r})))))));if(e.length){const r=await src_setupHandler.getProducts(t,a,"ID",Array.from(new Set(e.map((e=>e.id)))));if(r&&r.length)return utils.A.log("Related bundles",r),widget_mmb.setSetup({bundles:r,widgetSetup:s,shop:o}).renderRelatedBundles(),!0}}}return utils.A.removeWidgetOnPage("bundles"),!1}catch(e){return console.error("fn.processBundleDiscount : ",e),!1}}async function g(r,n){try{const{offers:o,shop:i}=src_setupHandler.getStoreSetup(),a=src_setupHandler.getWidgetSetupByType("widget#cvgProgressBar");if(r&&o&&o.cartValueGoals&&o.cartValueGoals.length&&i&&a){const s=await src_offers.getCartGoalValues(o.cartValueGoals,r,t,n,i.shopCurrency.currencyCode);if(s&&s.length){o.recommendations&&o.recommendations.length&&r.subTotal>0&&src_offers.fetchRecommendations(t,n,r.items,o.recommendations[0]);const d=s.some((e=>e.considerCartTotal)),c=s.some((e=>e.excludeGiftCards)),l=r.items.filter((e=>e.isGiftCard)).reduce(((e,t)=>e+t.lineSubTotalPrice),0),u=r.items.filter((e=>e.properties&&e.properties.__dealeasy_gwp)).reduce(((e,t)=>e+t.lineSubTotalPrice),0);let p=!1,g=[],f=[],m=c?r.subTotal-l:r.subTotal;m-=u;const y=r.items.filter((e=>!(c&&e.isGiftCard)||e.properties&&e.properties.__dealeasy_gwp));if(d)utils.A.log("Consider only shipping goals"),m=c?r.total-l:r.total;else{const t=s.filter((e=>"FREE_GIFT_DISCOUNT"===e.discountCategory));if(t&&t.length){const r=await async function(t,r,n,o,i){try{const{autoAddManualFg:a}=o.settings,s=n[0].addProductAgainIfRemoved,d=n[0].removeNotEligibleGift,c=n[0].freeGiftAdditionType,l=n[0].giftsProvidingMode;let u=src_offers.getExistingGiftGoals(t);r-=u.reduce(((e,t)=>e+t.price),0);const p=src_offers.getEligibleGiftGoals(n,r,l),g=utils.A.getSetDifference(u,p,"goalValue"),f=utils.A.getSetDifference(p,u,"goalValue"),m=g.length>0&&f.length>0&&"MULTIPLE"!==l,y=await src_offers.removeNotEligibleProducts(n,g,d,r,l,m,p);if(y&&y.success){const e=utils.A.getSetIntersection(u,y.productsWithRemovedGiftAttributes,"goalValue");r+=e.reduce(((e,t)=>e+t.price),0),u=utils.A.getSetDifference(u,e,"goalValue")}const{eligibleGoalsToAdd:h,unClaimedProducts:b}=p.length?src_offers.getEligibleProductsToAdd(f,s):{eligibleGoalsToAdd:[],unClaimedProducts:[]};let S=[];if("MANUAL"===c)if(a&&1===h.length&&1===h[0].offerValue.length)S=h.map((e=>({id:e.offerValue[0].id.split("/").pop(),quantity:1,properties:{__dealeasy_gift_product:e.lineItemProperty}})));else{const t=await widget_cpb.renderGiftProductPicker(o,i,h);if(e.dispatchEvent(new CustomEvent("lb-dealeasy-gpp-close",{detail:{src:"processGiftProducts"}})),t&&t.productsToAdd&&t.productsToAdd.length&&(S=t.productsToAdd),t?.productOptionsToBeIgnored&&t?.productOptionsToBeIgnored?.length){const e=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-added-gift-goals")||"[]"):[];e.push(...t.productOptionsToBeIgnored),sessionStorage.setItem("dealeasy-added-gift-goals",JSON.stringify(e))}}else S=h.map((e=>({id:e.offerValue[0].id.split("/").pop(),quantity:1,properties:{__dealeasy_gift_product:e.lineItemProperty}})));const C=!!S.length&&await src_offers.addProductsToCart(S);let v=C?utils.A.getSetUnion(u,C.items,"goalValue"):u,w=C?src_offers.getModifiedUnclaimedProducts(h,b,C.items):b;return{cartTotal:r,updated:C?.success||y?.success,unClaimedGiftProducts:w,selectedProducts:v}}catch(e){return void console.error("fn.processGiftProducts : ",e)}}(y,m,t,a,i);utils.A.log("Gift process result",r),r&&(m=r.cartTotal,p=r.updated,g=r.unClaimedGiftProducts,f=r.selectedProducts)}}if(widget_cpb.setSetup({cartValueGoals:s,widgetSetup:a,shop:i,unClaimedGiftProducts:g,cartTotal:m,selectedProducts:f}).render(),async function(e,r,n){try{const{offers:o,shop:i}=src_setupHandler.getStoreSetup(),a=src_setupHandler.getWidgetSetupByType("widget#cvgProgressBar"),s=await src_setupHandler.getStoreFrontAccessToken(t);if(o&&i&&a&&o.recommendations?.length&&e?.length&&r?.length&&n>0){const d=r.find((e=>e.goalValue>n))?.goalValue,c=r.filter((e=>"FREE_GIFT_DISCOUNT"===e.discountCategory)),l=c?Array.from(new Set(c.flatMap((e=>e.offerValue.map((e=>Number(e.productId.split("/").pop()))))))):[];if(d){const r=await src_offers.fetchRecommendations(t,s,e,o.recommendations[0]);if(r&&d>n){const t=src_offers.selectOptimalProductsForMilestone(r,e,n,d,o.recommendations[0].productDisplayLimit,o.recommendations[0].dontShowProductsInCart,l);if(t)return widget_cpb.setRecommendationSetup({recommendations:t,widgetSetup:a,cartTotal:n,shop:i}).renderRecommendations(),t.length||(widget_cpb.disconnectRecommendationListeners(),utils.A.removeWidgetOnPage("recommendations")),!0}}}return widget_cpb.setRecommendationSetup({recommendations:[],widgetSetup:a,cartTotal:n,shop:i}),widget_cpb.disconnectRecommendationListeners(),utils.A.removeWidgetOnPage("recommendations"),!1}catch(e){return console.error("fn.processRecommendations : ",e),!1}}(r.items,s,m),s.some((e=>e.isCodeDiscount&&e.autoApplyCodeDiscount))){const e=Array.from(new Set(s.filter((e=>e.goalValue<=m&&e.isCodeDiscount&&e.autoApplyCodeDiscount)).map((e=>e.discountCode))));src_cartHandler.setDiscountCodes("cartValueGoals",e)}return p}}return widget_cpb.disconnectListeners(),utils.A.removeWidgetOnPage("cart-progress-bar"),!1}catch(e){return console.error("fn.processCartValueGoals : ",e),!1}}async function f(e,r,n){try{const{offers:o,product:i}=src_setupHandler.getStoreSetup(),a=src_setupHandler.getWidgetSetupByType("widget#bogo");if(o&&o.bogo&&o.bogo.length&&a){const s=await src_cartHandler.getCartLineItemProducts(e.items,t,n),d=i?utils.A.getCurrentProduct(i,r):void 0,c=await src_offers.getBogoOffersOnCart(o.bogo,s,d?d.id:void 0),l=d?await src_offers.getBogoOfferForCurrentProduct(d,o.bogo,c):void 0;if(l&&(l?.renderCombination||l?.tiers?.length>1)){let e={...l,selectedItems:l?.selectedItems?.filter((e=>e!==d.id))};widget_bogo.setSetup({currentProductBogoOffer:e,widgetSetup:a}).render()}else utils.A.removeWidgetOnPage("bogo");const u=c.filter((e=>e.isCodeDiscount&&e.combinations.some((e=>"fulfilled"===e.type))&&e.autoApplyCodeDiscount)).map((e=>e.discountCode));return u&&u.length&&src_cartHandler.setDiscountCodes("bogo",u),!0}return!1}catch(e){return console.error("fn.processBogo : ",e),!1}}async function m(r,n,o){try{const{offers:i,product:a,shop:s}=src_setupHandler.getStoreSetup(),d=src_setupHandler.getWidgetSetupByType("widget#giftWithProduct");if(i&&i.gwp&&i.gwp.length&&d){src_offers.getGiftProductsForCombinations(t,o,i.gwp.map((e=>({productsToBeAdded:e.tiers.flatMap((e=>e.selectedItems)),...e}))));const c=await src_offers.getCartGwpCombinations(t,o,i.gwp,r.items);utils.A.log("Gwp combinations",c);const l=await async function(r,n,o,i,a){try{const s=!!o.length&&await src_offers.removeGwpGifts(o),d=src_offers.getGwpEligibleCombinations(n.filter((e=>"partiallyFulfilled"===e.type))),c=d.length?await src_offers.getGiftProductsForCombinations(t,r,d):[];if(c&&c.length){const t=[];c.filter((e=>e.autoAddGifts)).forEach((e=>{t.push({id:e.productsToBeAdded[0].id.split("/").pop(),quantity:1,properties:{__dealeasy_gwp:e.id}})}));const r=c.filter((e=>!e.autoAddGifts));if(r&&r.length){const n=await widget_gwp.renderGiftProductPicker(r,[],i,a);if(e.dispatchEvent(new CustomEvent("lb-dealeasy-gpp-close",{detail:{src:"processGwpCombinations"}})),n&&(n.productsToAdd&&n.productsToAdd.length&&t.push(...n.productsToAdd),n.productOptionsToBeIgnored&&n.productOptionsToBeIgnored.length)){const e=utils.A.isNotPrivateTab()?JSON.parse(sessionStorage.getItem("dealeasy-added-gwp-gifts")||"[]"):[];e.push(...n.productOptionsToBeIgnored),sessionStorage.setItem("dealeasy-added-gwp-gifts",JSON.stringify(Array.from(new Set(e))))}}const n=!!t.length&&await src_offers.addGwpProductsToCart(t);if(n&&n.success){return{didChanges:!0,combinations:c.filter((e=>n.items.some((t=>t.properties.__dealeasy_gwp===e.id))))}}}return{didChanges:s}}catch(e){return console.error("fn.processGwpCombinations : ",e),{didChanges:!1}}}(o,c.combinations,c.productsToRemove,d.giftProductPicker,s);utils.A.log("Gift with product result",l);const u=a?utils.A.getCurrentProduct(a,n):void 0;if(u){const e=l?.didChanges?await src_cartHandler.getCart():r;src_offers.getProductGwpCombinations(t,o,u,i.gwp,e.items).then((e=>{e&&e.length&&(utils.A.log("Gift with product current product combinations",e),widget_gwp.setSetup({combinations:e,widgetSetup:d,shop:s,currentProduct:u}).render())}))}const p=[...c?.combinations?.filter((e=>"fulfilled"===e.type))||[],...l?.combinations||[]],g=[...new Set(p.filter((e=>e.isCodeDiscount&&e.autoApplyCodeDiscount&&e.discountCode)).map((e=>e.discountCode)))];return src_cartHandler.setDiscountCodes("gwp",g),l?.didChanges}}catch(e){return console.error("fn.processGWP : ",e),!1}}async function y(e,r){try{const{offers:n,shop:i}=src_setupHandler.getStoreSetup();if(e&&e.items.length&&n&&n.discounts&&n.discounts.length){const a=await src_cartHandler.getCartLineItemProducts(e.items,t,r),s=n.discounts.map((e=>e.title));if(a&&a.length){const e=a?.filter((e=>!e.lineLevelDiscountsTitles?.some((e=>!s.includes(e)))&&!Object.keys(e.properties).some((e=>["__dealeasy_gift_product","__dealeasy_gwp"].includes(e))))),t=src_setupHandler.getWidgetSetupByType("widget#vdNudge");if(e&&e.length&&t){const r=src_offers.getCartLinePromotions(e,n.discounts,t.settings.displayNudgeFor);r?(utils.A.log("Cart line promotions : ",r),widget_vd.setNudgeSetup({widgetSetup:t,cartLinePromotions:r,shop:i}).renderVdNudge()):(widget_vd.disconnectListeners(),utils.A.removeWidgetOnPage("vd-nudge"))}if(!o&&n.hasCodeDiscounts){const e=n.discounts.filter((e=>e.isCodeDiscount&&e.autoApplyCodeDiscount)),t=src_offers.getDiscountCodesForCartProducts(a,e);src_cartHandler.setDiscountCodes("volumeDiscounts",t)}return!0}}return!1}catch(e){return console.error("fn.processVolumeDiscounts : ",e),!1}}async function h(r,n=void 0,o=!1){try{let o=r||await src_cartHandler.getCart();const a=await src_setupHandler.getStoreFrontAccessToken(t);if(o&&a){!o.itemCount&&utils.A.clearLocalStorage(),utils.A.log("Cart data",o);const t=await async function(t){try{const r={},n=["__dealeasy_gift_product","__dealeasy_gwp"];for(const o of n){const n=t.items.filter((e=>e.properties&&e.properties[o])).map(((e,t)=>({id:e.variantId,lineItemQuantity:e.lineItemQuantity,line:t+1,key:e.key,properties:e.properties,price:e.price}))),i=n.filter(((e,t,r)=>r.findIndex((t=>t.properties[o]===e.properties[o]))!==t));i.forEach((e=>{r[e.key]=0})),i.length&&utils.A.log("Duplicate products",i);const a=n.filter(((e,t,r)=>r.findIndex((t=>t.properties[o]===e.properties[o]))===t&&e.lineItemQuantity>1));a.forEach((e=>{r[e.key]=1})),a.length&&utils.A.log("More quantity gift products",a);const s=e.dealeasyRemoveNotEligibleGift&&"__dealeasy_gift_product"===o?n.filter((e=>utils.A.getCartGoalPrice(e.properties[o])>t.subTotal-e.price)):[];s&&s.length&&(utils.A.log("In eligible products",s),s.forEach((e=>{r[e.key]=0})),src_offers.removeRemovedProductsFromStorage(s))}const{offers:o}=src_setupHandler.getStoreSetup()??{};if(o&&o.bundles&&o.bundles.length&&!e.dealeasySnippetBCVIsActive){const e=o.bundles.map((e=>e.id)),n=t.items.filter((t=>e.includes(t.productGid)&&!t.properties.__de_bundle_id));n&&n.length&&(utils.A.log("Bundle products without property",n),n.forEach((e=>{r[e.key]=0})))}if(r&&Object.keys(r).length){utils.A.log("Immediate cart update payload",r);const e=await src_cartHandler.updateCart(r);return e.success?{cart:e,didChanges:!0}:{didChanges:!0}}return}catch(e){return void console.error("fn.immediateCartValidation : ",e)}}(o);t&&t.didChanges&&(o=t.cart?t.cart:src_cartHandler.getCart(),utils.A.log("Cart data after immediate changes",o));const[r,s,d,c]=await Promise.all([g(o,a),y(o,a),f(o,n,a),m(o,n,a)]),l=src_cartHandler.getDiscountCodes(),u=!!l.length&&await src_cartHandler.applyDiscountCodesToCart(l,"dealeasy",o.id,a);(r||c)&&(o=await src_cartHandler.getCart(),await Promise.all([y(o,a),f(o,n,a),m(o,n,a)]));return(r||c||u||t?.didChanges)&&!i&&(await src_cartHandler.refreshCart(),widget_vd.renderVdNudge()),!0}return!1}catch(e){return console.error("fn.handlePostCartOperations : ",e),!1}}async function b(t,r,o,i){try{if(e.dispatchEvent(new CustomEvent("lb-dealeasy-cart-action-request",{detail:{requestURL:t,isVariantChange:o,isCartAction:i}})),o&&(p(t),u(t)),i){const e=src_cartHandler.getCartPayloadFromRequest(t,r);n?(utils.A.log("Interupt cart action enabled"),await h(e)):h(e)}return!0}catch(e){return console.error("fn.handleCartUpdateProcess : ",e),!1}}t?(utils.A.log("Shopify domain",t),e.lbDealeasy={myShopifyDomain:t,getSetup:src_setupHandler.getSetup,getStoreSetup:src_setupHandler.getStoreSetup,applyDiscountsToCart:src_cartHandler.applyDiscountCodesToCart,vdWidgetHandler:widget_vd,mmbWidgetHandler:widget_mmb,cpbWidgetHandler:widget_cpb,bogoWidgetHandler:widget_bogo,gwpWidgetHandler:widget_gwp,isB2bCustomer:c,customer:l},utils.A.importDealeasyAssets(),utils.A.importDayJs(),config.A.LEGACY_USERS.includes(t)?utils.A.log("Legacy user"):src_setupHandler.getStoreFrontAccessToken(t).then((n=>{n&&(e.lbDealeasy.accessToken=n,async function(n){try{const[o,i,d]=await Promise.all([src_setupHandler.getStoreData(t,n,c,l),src_setupHandler.getCurrentPageProduct(t,n),src_cartHandler.getCart()]);if(utils.A.log("Store setup",{storeSetup:o,product:i,cart:d,customer:l,isB2bCustomer:c}),o){src_setupHandler.setStoreSetup({...o,product:i,myShopifyDomain:t,accessToken:n});const c=o.offers;if(c)return function(n){try{return async function(){try{async function t(t,r){const n=utils.A.isVariantChangeRequest(e.location.href,t),o=utils.A.isCartActionRequest(t);return!(!n&&!o)&&(widget_vd.dibsSellingPlanData&&widget_vd.initDibsIntegration(),s?S(t,r,n,o):await b(t,r,n,o),!0)}function r(e="",t=""){try{const r=["stream","ndjson","event-stream"],n=e?String(e).toLowerCase():"";if(n.startsWith("ws://")||n.startsWith("wss://"))return utils.A.log("Streaming response detected for",e),!0;const o=t?String(t).toLowerCase():"",i=r.some((e=>o.includes(e)));return i&&utils.A.log("Streaming response detected for",e,i),i}catch(e){return console.error("Error checking streaming response:",e),!1}}if("function"!=typeof jQuery||"function"!=typeof $||"object"!=typeof $(document)||"function"!=typeof $(document).ajaxComplete||a){utils.A.log("Registering XMLHttpRequest listener");const n=e.XMLHttpRequest.prototype.open;function o(e,o,i,a,s){return this.addEventListener("load",(async function(){try{const e=this.getResponseHeader("content-type");o&&!r(o,e)&&await t(o,this.responseText)}catch(e){console.error("fn.registerNetworkListener, XMLHttpRequest standard implementation error : ",e)}})),n.apply(this,arguments)}e.XMLHttpRequest.prototype.open=o}else{utils.A.log("Registering jQuery ajax listener");try{$(document).ajaxComplete((async function(e,n,o){try{const e=n.getResponseHeader("content-type");o&&o.url&&!r(o.url,e)&&await t(o.url,n.responseText)}catch(e){console.error("jQuery ajax listener error:",e)}}))}catch(i){}}if("function"==typeof e.fetch){utils.A.log("Registering fetch listener");const d=e.fetch;e.fetch=async function(e,n){const o=await d.apply(this,arguments);try{const n=o.headers.get("content-type");e&&!r(e,n)&&await t(e,await o.clone().text())}catch(e){console.error("fn.registerNetworkListener Fetch : ",e)}return o}}e.addEventListener("lb-dealeasy-network-request",(async e=>{utils.A.log("Custom network request event : ",e.detail),await t(e.detail.requestURL,e.detail.requestPayload)}))}catch(c){return console.error("fn.registerNetworkListener : ",c),!1}}(),(n.discounts||n.bundles)&&function(){try{const r=new MutationObserver(((t,r)=>{e.location.href!==r.previousURL&&(r.previousURL=e.location.href,u(e.location.href),p(e.location.href))}));return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),r.previousURL=e.location.href,document.addEventListener("lb-dealeasy-variant-change",(r=>{if(r.detail&&r.detail.currentVariantId){const n=`https://${t}/products/${utils.A.getProductHandle(e.location.href)}?variant=${r.detail.currentVariantId}`;u(n),p(n)}})),!0}catch(e){return console.error("fn.registerProductVariantListener : ",e),!1}}(),!r&&function(){try{const e=new MutationObserver((()=>{src_cartHandler.appendDiscountCodesOnCartForm()}));return document.querySelectorAll("form[action='/cart'][method='post']").forEach((t=>{e.observe(t,{childList:!0,subtree:!0,attributes:!0})})),!0}catch(e){return console.error("fn.registerCartFormListener : ",e),!1}}(),!0}catch(e){return console.error("fn.registerListeners",e.message),!1}}(c),c.discounts.length&&u(e.location.href),c.bundles.length&&p(e.location.href),h(d,e.location.href,!0),!0}else utils.A.clearLocalStorage();return!1}catch(e){return console.error("fn.initiateProcess : ",e),!1}}(n))}))):utils.A.log("No shop domain provided");const S=function(e,t){let r;return function(...n){clearTimeout(r),r=setTimeout((()=>{e.apply(this,n)}),t)}}(b,d)}(window)})();