!function(){"use strict";const t=t=>{const e=gfg.utility&&gfg.utility.escapeHtml;return e?e(t):String(null==t?"":t).replace(/[&<>"']/g,t=>"&"===t?"&":"<"===t?"<":">"===t?">":'"'===t?""":"'")};var e=[{module:"base",event:"gfg:module:base"}];const i={updateCartAttributesWithTotalAmountWithoutFreeGift:async function(t){try{const e=t.attributes,r=Number(i.getAmountOfGivenProductsWithoutFreeGift(t.items))/Number(gfg.utility.getActiveCurrencyRate());if(e&&e._kite_cfAdditionalData){let t=JSON.parse(e._kite_cfAdditionalData);if(r===t.totalAmountWithoutFreeGift)return}const n={totalAmountWithoutFreeGift:r},o={attributes:{_kite_cfAdditionalData:JSON.stringify(n)}};await gfg.utility.updateCart(o)}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 updateCartAttributesWithTotalAmountWithoutFreeGift fn",t)}},checkForActiveCampaign:function(t){return gfg.utility.checkForActiveCampaign(t)},checkCustomDiscountWidgetIsRelevantToCurrentPage:async function(t,e){try{let r;r=t.isUnifiedWidget?t:t?.widgetSettings;return!!await i.checkRulesToHandleWidgetVisibility(t)&&(!(t.salesChannelSettings&&!t.salesChannelSettings?.channels?.includes("ONLINE_STORE"))&&gfg.utility.isPageRelevantForWidget(r?.displaySettings,e))}catch(t){gfg.utility.debugError("Error inside checkCustomDiscountWidgetIsRelevantToCurrentPage fn",t)}},checkRulesToHandleWidgetVisibility:async function(t){let e=!0;try{let r=t?.rulesData?.rulesGlobalList?.[0];t.isUnifiedWidget?r=t.customerRulesData.rulesGlobalList[0]:("CONSOLIDATED_PROGRESS_BAR"===t?.discountFunctionType||"BUYX_GETY_DISCOUNT"===t?.discountFunctionType)&&(r=t.customerEligibilityRules);const n=r?.rulesOperator||"OR",o=r?.rulesList||[];if(0===o.length)return!0;const a=[];for(let t of o)switch(t.ruleType){case"shippingCountry":a.push(await i.validateShippingRule(null,t));break;case"customerTags":a.push(i.checkIfCustomerTagsConditionMet(null,t));break;case"isCustomerLoggedIn":a.push(i.checkIfCustomerLoggedInConditionMet(null,t));break;case"market":a.push(i.checkIfMarketConditionMet(null,t));break;default:a.push(!0)}e="AND"===n?a.every(t=>t):a.some(t=>t)}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkRulesToHandleWidgetVisibility fn",t)}finally{return e}},verifyCustomDiscountRules:async function(t,e){try{const r=t.rulesData.rulesGlobalList[0].rulesOperator,n=t.rulesData.rulesGlobalList[0].rulesList;let o=[];0===n.length&&o.push(!0);for(let r of n){t.isUnifiedWidget&&(r.isUnifiedWidget=!0,r.discountType=r.discountSettings.type),t?.discountFunctionType&&"SHIPPING_DISCOUNT"==t.discountFunctionType&&t?.advancedSettings?.onlyUseWidget&&(r.onlyUseWidget=!0),t?.advancedSettings?.useDiscountedPrice&&(r.useDiscountedPrice=!0);let n=await i.checkRuleGroup(r,e);o.push(n)}let a=!1;a="AND"===r?o.every(Boolean):o.some(Boolean);for(let e=0;e=0?n-o:0).toFixed(2);let s=(o/n*100).toFixed(2),l=!1;switch(r){case"equalTo":l=o===Number(n),s=s<=100?s:100;break;case"greaterThanOrEqualTo":l=o>=Number(n),s=s<=100?s:100;break;case"lessThanOrEqualTo":l=o<=Number(n),s=l?100:0;break;default:l=!1}return e.ruleValue.remainingSubtotalValue=a,e.ruleValue.dynamicProgressBarWidth=s,l}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfCartSubTotalConditionMet fn",t),!1}},checkIfCartQuantityConditionMet:function(t,e){try{let{operatorType:i,value:r}=e.ruleValue,n=t.item_count;e?.isUnifiedWidget&&(n=this.getQtyOfGivenProductsWithoutFreeGift(t.items));const o=r-n>=0?r-n:0;let a=100*(n/r).toFixed(2),s=!1;switch(i){case"equalTo":s=n===Number(r),a=a<=100?a:100;break;case"greaterThanOrEqualTo":s=n>=Number(r),a=a<=100?a:100;break;case"lessThanOrEqualTo":s=n<=Number(r),a=s?100:0;break;default:s=!1}return e.ruleValue.remainingQuantityValue=o,e.ruleValue.dynamicProgressBarWidth=a,s}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfCartQuantityConditionMet fn",t)}},checkIfCartCurrencyConditionMet:function(t,e){try{const{currencies:i,operatorType:r}=e.ruleValue,n=t.currency;return"is"===r&&i.includes(n)?(e.ruleValue.dynamicProgressBarWidth=100,!0):"isNot"!==r||i.includes(n)?(e.ruleValue.dynamicProgressBarWidth=0,!1):(e.ruleValue.dynamicProgressBarWidth=100,!0)}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfCartCurrencyConditionMet fn",t),!1}},checkIfAttributesConditionMet:function(t,e){try{const{attributeKey:i,attributeValue:r}=e.ruleValue;let n=r.value,o=i.value;const a=t.attributes;if(0===Object.keys(a).length)return e.ruleValue.qualifiedCartKey=o,e.ruleValue.qualifiedCartValue=n,e.ruleValue.dynamicProgressBarWidth=0,!1;if("hasAnyValue"===i.operatorType)return e.ruleValue.qualifiedCartKey=o,e.ruleValue.qualifiedCartValue=n,e.ruleValue.dynamicProgressBarWidth=100,Object.keys(a).length>0;if("is"===i.operatorType&&!a[i.value])return e.ruleValue.qualifiedCartKey=o,e.ruleValue.qualifiedCartValue=n,e.ruleValue.dynamicProgressBarWidth=0,!1;const s=a[i.value];let l=!1;switch(r.operatorType){case"is":l=s===r.value;break;case"isNot":l=s!==r.value;break;case"contains":{let t=JSON.parse(JSON.stringify(s));t=t.toLowerCase(),l=t?.includes(r.value.toLowerCase());break}case"doesNotContain":{let t=JSON.parse(JSON.stringify(s));t=t.toLowerCase(),l=!t?.includes(r.value.toLowerCase());break}default:l=!1}return e.ruleValue.qualifiedCartKey=o,e.ruleValue.qualifiedCartValue=n,e.ruleValue.dynamicProgressBarWidth=l?100:0,l}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfAttributesConditionMet fn",t),!1}},validateCartRule:function(t,e){try{switch(e.ruleType){case"cartSubtotal":return i.checkIfCartSubTotalConditionMet(t,e);case"cartQuantity":return i.checkIfCartQuantityConditionMet(t,e);case"cartCurrency":return i.checkIfCartCurrencyConditionMet(t,e);case"cartAttributes":return i.checkIfAttributesConditionMet(t,e);default:return gfg.utility.debugConsole(`Unsupported CART ruleType: ${e.ruleType}`),!1}}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 validateCartRule fn",t),!1}},checkProductCondition:function(t,e){try{let i=t.variant_id||t.id,r=!1;const n=e.ruleValue.products.filter(e=>e.productId==t.product_id);let o={title:e.ruleValue.products[0].title,handle:e.ruleValue.products[0].handle,variantTitle:e.ruleValue.products[0].variants[0].variantTitle};for(let t of n){const e=t.variants;let n=!1,a=e[0].variantTitle;for(let t of e)if(t.variantId==i){r=!0,n=!0,a=t.variantTitle;break}if(n){o={title:t.title,handle:t.handle,variantTitle:a};break}}e.ruleValue.qualifiedProductObj=o;return"include"===e.ruleValue.operatorType?r:!r}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkProductCondition fn",t),!1}},checkCollectionCondition_Old:function(t,e){try{const i=e.ruleValue.collections;let r={title:e.ruleValue.collections[0].title,handle:e.ruleValue.collections[0].handle};const n=e.ruleValue.collectionsData;let o=!1;for(let a=0;at.productId?t.productId+"":t.id+"").includes(c+""),o&&"include"===e.ruleValue.operatorType){r={title:s.title,handle:s.handle};break}}e.ruleValue.qualifiedCollectionObj=r;return"include"===e.ruleValue.operatorType?o:!o}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkCollectionCondition fn",t),!1}},checkCollectionCondition:function(t,e){try{const i=e.ruleValue.collections;let r={title:e.ruleValue.collections[0].title,handle:e.ruleValue.collections[0].handle},n=!1;for(let o=0;ot.id).includes(s),n&&"include"===e.ruleValue.operatorType){r={title:a.title,handle:a.handle};break}}e.ruleValue.qualifiedCollectionObj=r;return"include"===e.ruleValue.operatorType?n:!n}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkCollectionCondition fn",t),!1}},checkProductTypeCondition:function(t,e){try{const i=e.ruleValue.types,r=t.latestShopifyData?.productType||t.latestShopifyData?.type||"",n=i.includes(r);return e.ruleValue.productType=n?r:i[0],"include"===e.ruleValue.operatorType?n:!n}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkProductTypeCondition fn",t)}},checkTagCondition:function(t,e){try{const i=e.ruleValue.tags,r=t.latestShopifyData.tags||[];let n=i[0];const o=r.some(t=>{for(const e of i)if(t===e)return n=e,!0;return!1});return e.ruleValue.tagName=n,"include"===e.ruleValue.operatorType?o:!o}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkTagCondition fn",t)}},checkSubscriptionCondition:function(t,e){try{const i=t?.selling_plan_allocation?.selling_plan?.options?.length>0||!1,r=t?.selling_plan_allocation?.selling_plan?.name||"";let n=!1;switch(e.ruleValue.operatorType){case"include":n=Boolean(i);break;case"exclude":n=!Boolean(i);break;case"is":n=r===e.ruleValue.value;break;case"isNot":n=r!==e.ruleValue.value;break;default:gfg.utility.debugConsole("Unsupported operator type:",e.ruleValue.operatorType),n=!1}return n}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkSubscriptionCondition fn",t)}},checkLineAttributeCondition:function(t,e){try{const{attributeKey:i,attributeValue:r}=e.ruleValue;let n=r.value,o=i.value;const a=t.properties;if("hasAnyValue"===i.operatorType&&Object.keys(a).length>0)return e.ruleValue.qualifiedLineValue=n,e.ruleValue.qualifiedLineProperty=o,e.ruleValue.dynamicProgressBarWidth=100,!0;const s=a[i.value];if(!s)return e.ruleValue.qualifiedLineValue=n,e.ruleValue.qualifiedLineProperty=o,!1;let l=!1;switch(r.operatorType){case"is":l=s===r.value;break;case"isNot":l=s!==r.value;break;case"contains":l=s.toLowerCase().includes(r.value.toLowerCase());break;case"doesNotContain":l=!s.toLowerCase().includes(r.value.toLowerCase());break;default:l=!1}return e.ruleValue.qualifiedLineValue=n,e.ruleValue.qualifiedLineProperty=o,l}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkLineAttributeCondition fn",t),!1}},compareMetrics:function(t,e){try{let{qualifierOperatorType:i,qualifierValue:r}=t.ruleValue,n=100*(e/r).toFixed(2),o=!1;switch(r=Number(r),i){case"equalTo":o=e===r,n=n<=100?n:100;break;case"greaterThanOrEqualTo":o=e>=r,n=n<=100?n:100;break;case"lessThanOrEqualTo":o=e<=r,n=o?100:0;break;case"greaterThan":o=e>r,n=100*(e/(r+1)).toFixed(2),n=n<=100?n:100;break;case"lessThan":o=et+parseInt(e?.quantity||0),0);else if("distinctQuantity"===n)s=i.getQtyOfGivenDistinctProducts(t);else if("amount"===n){const i=gfg.utility.getActiveCurrencyRate();o*=i,s=e?.onlyUseWidget?t.reduce((t,e)=>t+parseFloat(e?.original_line_price/100||0),0):t.reduce((t,e)=>t+parseFloat(e?.line_price/100||0),0);Shopify.shop.includes("rothys")&&(s=Number((s/(Number(i)||1)).toFixed(2)))}return a=i.compareMetrics(e,s),a}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 evaluateProductMetrics fn",t),!1}},validateProductRule:async function(t,e){try{const r=(t,e)=>"include"===e&&t||"exclude"===e&&!t;let n=[];const o=!!gfg.settings.merchantInfo.storefrontAccessToken;switch(e.ruleType){case"products":case"productVariants":if(0===t.items.length){let t={title:e.ruleValue.products[0].title,handle:e.ruleValue.products[0].handle,variantTitle:e.ruleValue.products[0].variants[0].variantTitle};e.ruleValue.qualifiedProductObj=t,e.ruleValue.dynamicProgressBarWidth=0}t.items.forEach(t=>{const o=i.checkProductCondition(t,e);r(o,e.ruleValue.operatorType)&&n.push(t)});break;case"collections":if(0===t.items.length){let t={title:e.ruleValue.collections[0].title,handle:e.ruleValue.collections[0].handle};e.ruleValue.qualifiedCollectionObj=t,e.ruleValue.dynamicProgressBarWidth=0}o&&await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(t),t.items.forEach(t=>{const a=o?i.checkCollectionCondition(t,e):i.checkCollectionCondition_Old(t,e);r(a,e.ruleValue.operatorType)&&n.push(t)});break;case"productTypes":0===t.items.length&&(e.ruleValue.productType=e.ruleValue.types[0],e.ruleValue.dynamicProgressBarWidth=0),await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(t),t.items.forEach(t=>{const o=i.checkProductTypeCondition(t,e);r(o,e.ruleValue.operatorType)&&n.push(t)});break;case"productTags":0===t.items.length&&(e.ruleValue.tagName=e.ruleValue.tags[0],e.ruleValue.dynamicProgressBarWidth=0),await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(t),t.items.forEach(t=>{const o=i.checkTagCondition(t,e);r(o,e.ruleValue.operatorType)&&n.push(t)});break;case"productVendors":case"productHasSubscription":0===t.items.length&&(e.ruleValue.dynamicProgressBarWidth=0),t.items.forEach(t=>{const o=i.checkSubscriptionCondition(t,e);r(o,e.ruleValue.operatorType)&&n.push(t)});break;case"lineAttributes":if(0===t.items.length){let t=e.ruleValue.attributeValue.value,i=e.ruleValue.attributeKey.value;e.ruleValue.qualifiedLineValue=t,e.ruleValue.qualifiedLineProperty=i,e.ruleValue.dynamicProgressBarWidth=0}t.items.forEach(t=>{const o=i.checkLineAttributeCondition(t,e);r(o,e.ruleValue.operatorType)&&n.push(t)});break;default:return gfg.utility.debugConsole(`Unsupported PRODUCT ruleType: ${e.ruleType}`),!1}return"exclude"===e.ruleValue.operatorType&&"none"===e.ruleValue.qualifierType?0===n.length:i.evaluateProductMetrics(n,e,t)}catch(t){return gfg.utility.debugError("Error in validateProductRule",t),!1}},validateProductRuleForDiscountableItems:async function(t,e,r){try{const n=!!gfg.settings.merchantInfo.storefrontAccessToken,o=(t,e)=>t?.items.filter(t=>t.id==e)?.[0];switch(e.ruleType){case"allProducts":return!0;case"products":case"productVariants":return i.checkProductCondition(r,e);case"collections":{n&&await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(t);let a=o(t,r.id);return n?i.checkCollectionCondition(a,e):i.checkCollectionCondition_Old(a,e)}case"productTypes":{await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(t);let n=o(t,r.id);return i.checkProductTypeCondition(n,e)}case"productTags":{await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(t);let n=o(t,r.id);return i.checkTagCondition(n,e)}case"productVendors":case"productHasSubscription":return i.checkSubscriptionCondition(r,e);case"lineAttributes":return i.checkLineAttributeCondition(r,e);default:return gfg.utility.debugConsole(`Unsupported PRODUCT ruleType: ${e.ruleType}`),!1}}catch(t){return gfg.utility.debugError("Error in validateProductRuleForDiscountableItems",t),!1}},checkIfCustomerTagsConditionMet:function(t,e){try{const t=window?.shopifyLiquidValuesApp7Ext?.customer?.customerTags;let{operatorType:i}=e.ruleValue,r=e.ruleValue.tags||e.ruleValue.value,n=r[0],o=!1;if(!t&&"isNot"==i)return e.ruleValue.qualifiedTag=n,e.ruleValue.dynamicProgressBarWidth=0,!0;if(!t&&"is"==i)return e.ruleValue.qualifiedTag=n,e.ruleValue.dynamicProgressBarWidth=0,!1;if(!t)return e.ruleValue.qualifiedTag=n,e.ruleValue.dynamicProgressBarWidth=0,!1;switch(i){case"is":o=t.some(t=>r.includes(t));break;case"isNot":o=!t.some(t=>r.includes(t));break;case"contains":for(let e of t)for(let t of r)if(e.toLowerCase().includes(t.toLowerCase())){n=t,o=!0;break}o=!1;break;case"doesNotContain":for(let e of t)for(let t of r)if(e.toLowerCase().includes(t.toLowerCase())){n=t,o=!1;break}o=!0;break;default:o=!1}return e.ruleValue.qualifiedTag=n,e.ruleValue.dynamicProgressBarWidth=o?100:0,o}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfCustomerTagsConditionMet fn",t),!1}},checkIfCustomerLoggedInConditionMet:function(t,e){try{const t=!!window.shopifyLiquidValuesApp7Ext.customer.id,i=e.ruleValue.value;return"yes"===i?(e.ruleValue.dynamicProgressBarWidth=t?100:0,t):"no"===i?(e.ruleValue.dynamicProgressBarWidth=t?0:100,!t):(e.ruleValue.dynamicProgressBarWidth=0,!1)}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfCustomerLoggedInConditionMet fn",t),!1}},checkIfMarketConditionMet:function(t,e){try{const{operatorType:t}=e.ruleValue,i=e.ruleValue.markets||e.ruleValue.value,r=gfg.state.activeCustomerData?.markets?.handle;return!!r&&("is"===t?i.includes(r):"isNot"===t&&!i.includes(r))}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfMarketConditionMet fn",t),!1}},validateCustomerRule:function(t,e){try{switch(e.ruleType){case"customerTags":return i.checkIfCustomerTagsConditionMet(t,e);case"isCustomerLoggedIn":return i.checkIfCustomerLoggedInConditionMet(t,e);default:return gfg.utility.debugConsole(`Unsupported CUSTOMER ruleType: ${e.ruleType}`),!1}}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 validateCustomerRule fn",t)}},checkIfShippingCountryConditionMet:async function(t,e){try{let{operatorType:t}=e.ruleValue,i=e.ruleValue.countries||e.ruleValue.value;const r=await gfg.utility.getVisitingFromCountry();let n=i[0];if("include"===t){const t=i.includes(r&&r.toUpperCase());return t&&(n=r),e.ruleValue.qualifiedCountry=n,e.ruleValue.dynamicProgressBarWidth=t?100:0,t}return"exclude"===t&&(e.ruleValue.qualifiedCountry=n,!i.includes(r&&r.toUpperCase()))}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfShippingCountryConditionMet fn",t)}},validateShippingRule:function(t,e){try{return"shippingCountry"===e.ruleType?i.checkIfShippingCountryConditionMet(t,e):(gfg.utility.debugConsole(`Unsupported SHIPPING ruleType: ${e.ruleType}`),!1)}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 validateShippingRule fn",t)}},checkRuleGroup:async function(t,e){try{switch(t.type){case"CART":return i.validateCartRule(e,t);case"PRODUCT":return i.validateProductRule(e,t);case"CUSTOMER":return i.validateCustomerRule(e,t);case"SHIPPING":return i.validateShippingRule(e,t);default:return gfg.utility.debugConsole(`Unsupported rule type: ${t.type}`),!1}}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkRuleGroup fn",t)}},verifyIndividualRule:async function(t,e){try{t.ruleType,t.ruleValue,t.type}catch(t){gfg.utility.debugConsole("Error inside gfgShippingDiscountV2 verifyIndividualRule fn",t)}},getProductsDataByProductIds:async function(t){try{let e=window.Shopify.shop;const i=!!gfg.settings.merchantInfo.storefrontAccessToken,r=JSON.parse(sessionStorage.getItem(`customFunctionProductData-${e}`))||{},n=t.map((t,e)=>{let n=`gid://shopify/Product/${t}`;if(r[n])return Promise.resolve(r[n]);return i?gfg.customDiscountStorefrontApis.getProductsDataById([n]):gfg.utility.getProductDataV2(productHandles[e])}),o=await Promise.all(n);return o.forEach(t=>{const e=t?.id;r[e]||(r[e]=t)}),sessionStorage.setItem(`customFunctionProductData-${e}`,JSON.stringify(r)),o}catch(t){gfg.utility.debugError("Error inside getProductsDataByProductIds fn",t)}},getProductsDataFromCollectionIds:async function(t){try{let e=window.Shopify.shop;gfg.settings.merchantInfo.storefrontAccessToken;const i=JSON.parse(sessionStorage.getItem(`customFunctionProductData-${e}`))||{};let r=[];for(let e=0;e=10);e++){const n=t[e];let o=i[n];o&&0!==o.length||(o=await gfg.customDiscountStorefrontApis.getCollectionsDataById([n]),i[n]=o),r=[...r,...o?.[0]?.products]}return r?.forEach(t=>{const e=t?.id;i[e]||(i[e]=t)}),sessionStorage.setItem(`customFunctionProductData-${e}`,JSON.stringify(i)),r}catch(t){gfg.utility.debugError("Error inside getProductsDataFromCollectionIds fn",t)}},getProductsDataByProductTags:async function(t){try{let e=[],i=window.Shopify.shop;const r=JSON.parse(sessionStorage.getItem(`customFunctionProductData-${i}`))||{};for(let i=0;i=10);i++){const r=t[i],n=await gfg.customDiscountStorefrontApis.getProductsDataByTagName(r),o=n?.products.filter(t=>t.tags.includes(r));e=[...e,...o]}return e?.forEach(t=>{const e=t?.id;r[e]||(r[e]=t)}),sessionStorage.setItem(`customFunctionProductData-${i}`,JSON.stringify(r)),e}catch(t){gfg.utility.debugError("Error inside getProductsDataByProductTags fn",t)}},getProductsDataByProductTypes:async function(t){try{let e=[],i=window.Shopify.shop;const r=JSON.parse(sessionStorage.getItem(`customFunctionProductData-${i}`))||{};for(let i=0;i=10);i++){const r=t[i],n=await gfg.customDiscountStorefrontApis.getProductsDataByProductType(r),o=n?.products.filter(t=>t.productType===r);e=[...e,...o]}return e?.forEach(t=>{const e=t?.id;r[e]||(r[e]=t)}),sessionStorage.setItem(`customFunctionProductData-${i}`,JSON.stringify(r)),e}catch(t){gfg.utility.debugError("Error inside getProductsDataByProductTypes fn",t)}}};let r={state:{isFirstRenderForcustomDiscount:!0,productFound:{},productVariantFrount:{},collectionFound:{},customDiscountEligibilityResult:{}},init:function(){try{let t=gfg.settings.customDiscount;r.initialize(t),r.gfgShippingDiscountV2.init()}catch(t){gfg.utility.debugConsole("Error inside gfgCustomDiscount init fn",t)}},productPage:{init:function(t){try{r.initialize(t,"PRODUCT_PAGE")}catch(t){gfg.utility.debugConsole("Error inside productPage.init fn",t)}}},cartPage:{init:function(t){try{r.initialize(t,"CART_PAGE")}catch(t){gfg.utility.debugConsole("Error inside cartPage.init fn",t)}}},sideCart:{init:function(t){try{r.initialize(t,"SIDE_CART")}catch(t){gfg.utility.debugConsole("Error inside cartPage.init fn",t)}}},initialize:async function(t,e){try{const e=t?.filter(t=>t.isEnabled)||[];if(0===e.length)return;for(const t of e)try{if("BUYX_GETY_DISCOUNT"===t?.discountFunctionType&&t?.widgetSettings){const e=await gfg.utility.getCartV2();await r.gfgBXGY.computeWidgetState(t,e),r.gfgBXGY.init(t?.title)}}catch(t){gfg.utility.debugError("Error in gfgCustomDiscount initialize",t)}}catch(t){gfg.utility.debugError("Error inside gfgCustomDiscount initialize fn",t)}},f:{clearExistingContent:function(t){try{t.forEach(t=>{t.innerHTML=""})}catch(t){gfg.utility.debugConsole("Error inside gfgCustomDiscount clearExistingContent fn",t)}},appendNewUI:function(t,e,i){try{t.forEach(t=>{e.forEach(r=>{if(i.length>0){const i=t.id;if(!(r.offer._id==i)&&e.length>1)return}const n=r.generatedUI.cloneNode(!0);t.appendChild(n)})})}catch(t){gfg.utility.debugError("Error inside gfgCustomDiscount appendNewUI fn",t)}},insertIntoPageWrapper:function(t,e,i){try{if(0===t.length)return;const n=gfg.utility.findWrapperElement(i,e,null,"JS");let o=[];if("SIDE_CART"!=e){let t="CONSOLIDATED_PROGRESS_BAR"===i?".gfgConsolidatedProgressBarWrapperV2":".gfgCustomDiscountWrapperV2";o=document.querySelectorAll(t)}r.f.clearExistingContent(n),r.f.appendNewUI(n,t,o)}catch(t){gfg.utility.debugConsole("Error inside gfgCustomDiscount insertIntoPageWrapper fn",t)}}},utility:{createElementWithAttributes:function(t,e){try{const i=document.createElement(t);for(let t in e)"innerText"===t||"innerHTML"===t?i[t]=e[t]:i.setAttribute(t,e[t]);return i}catch(t){gfg.utility.debugError("error in createElementWithAttributes",t)}},checkMultipleLanguagePresent:function(t){try{let e=t?Object.keys(t):[];const i=["conditionMetIconUrl","conditionNotMetIconUrl","conditionMet","showOnWidget"];return e=e.filter(t=>!i.includes(t)),e.length>1}catch(t){gfg.utility.debugError("Error inside gfgCustomDiscount utility checkMultipleLanguagePresent fn",t)}}},gfgCustomDiscountFunctionLogicHandlers:{init:async function(){return""},getExistingCartAttributes:function(t,e="_kite_cfData"){try{let i=t.attributes[e];return i?JSON.parse(i):{}}catch(t){gfg.utility.debugError("err inside getExistingCartAttributes",t)}}},gfgBXGY:{state:{isFirstRenderForCustomBXGY:!0,productsDataForBuyXGetY:{},BuyXConditionFulfilled:{},allowedGetYQuantity:{},accordionOpenState:{},addedVariantsInCart:{},animatingDiscounts:new Set,containerRefs:{},isBuyXGetX:{},buyXGetXCartProductIds:{},buyXVariantData:{},debugTrace:[]},_trace:function(t,e){gfg.utility.debugTrace("BXGY-TRACE",r.gfgBXGY.state.debugTrace,t,e)},BXGY_DEFAULT_STYLE_SETTINGS:{productsListLayout:"horizontal",widgetPadding:"10px",cornerRadius:"6px",buttonStyle:"solid",keepOpenByDefault:!1,hyperLinkYProduct:!1,titleBarTextColor:"#0F0F0F",titleBarIconColor:"#000000",highlightColor:"#199800",productNameColor:"#0F0F0F",priceColor:"#000000",strikeThroughPriceColor:"#868686",widgetBackgroundColor:"#ffffff",widgetBorderColor:"#E5E5E5",widgetButtonColor:"#199800",widgetButtonTextColor:"#ffffff",widgetDropdownColor:"#ECECEC",titleBarFontWeight:"bold",titleBarFontSize:"16px",productNameFontSize:"14px",productNameFontWeight:"medium",priceFontSize:"12px",priceFontWeight:"bold",strikeThroughPriceFontSize:"14px",strikeThroughPriceFontWeight:"medium",buttonLabelFontSize:"14px",buttonLabelFontWeight:"medium"},computeWidgetState:async function(t,e){try{const n=t.discountSettings.rulesData.rulesGlobalList[0].rulesList;for(let o=0;o0?Math.min(Math.floor(r/e),n):0,s=a*m;i+=s,n-=a,o[String(t)]={qtyInCart:r,allowed:s,setSize:e,buyXItemCount:h,getYItemCount:m,maxDiscountableSets:C}}r.gfgBXGY.state.allowedGetYQuantity[t.title]=i,r.gfgBXGY.state.buyXVariantData[t.title]=o;continue}for(const t of e.items){await i.validateProductRuleForDiscountableItems(e,l,t)&&(g+=t.quantity,f.set(t.variant_id,(f.get(t.variant_id)||0)+t.quantity))}const B=new Map([...d].filter(([t])=>f.has(t)&&f.get(t)===d.get(t))),T=Array.from(B.values()).reduce((t,e)=>t+e,0);if(T>0){const e=u-T,i=g-T,n=Math.floor(Math.min(e/h,i/m)),o=e-n*h,a=Math.floor(Math.min(o/h,T/m)),s=T-a*m,l=i-n*m,c=Math.floor(Math.min(s/h,l/m)),d=s-c*h,f=Math.floor(d/(h+m));let p=n+a+c+f;if(p=Math.min(p,C),p=h&&p++}if(0===e&&0===i){const e=Math.floor(T/(h+m)),i=T-e*(h+m),n=Math.floor(i/h),o=Math.min(e+n,C);r.gfgBXGY.state.allowedGetYQuantity[t.title]=o*m}else r.gfgBXGY.state.allowedGetYQuantity[t.title]=Math.min(Math.floor(u/h),C)*m}else r.gfgBXGY.state.allowedGetYQuantity[t.title]=S*m}}catch(t){gfg.utility.debugError("Error in computeWidgetState:",t)}},init:async function(t){try{if(r.gfgBXGY.state.animatingDiscounts.has(t))return void gfg.utility.debugConsole(`[BXGY] SKIP init for "${t}": animation in progress`);for(const[t,e]of Object.entries(r.gfgBXGY.state.containerRefs))e.isConnected||delete r.gfgBXGY.state.containerRefs[t];const e=gfg.settings.customDiscount.find(e=>e.title===t),i=gfg.f.getPageType();"product"===i&&r.gfgBXGY.initialize(e,"PRODUCT_PAGE"),"cart"===i&&r.gfgBXGY.initialize(e,"CART_PAGE"),"cart"!==i&&r.gfgBXGY.initialize(e,"SIDE_CART")}catch(t){gfg.utility.debugConsole("Error inside gfgCustomDiscount gfgBXGY init fn",t)}},initialize:async function(t,e){try{if(t?.widgetSettings&&(t.widgetSettings.styleSettings=r.gfgBXGY.f.resolveStyleSettings(t.widgetSettings.styleSettings)),r.gfgBXGY.state.animatingDiscounts.has(t?.title))return void gfg.utility.debugConsole(`[BXGY] SKIP initialize for "${t?.title}": animation in progress`);const i=`${t.title}_${e}`,n=r.gfgBXGY.state.containerRefs[i];if(n&&n.isConnected){await(r?.gfgBXGY?.f?.getDiscountEligibleProducts(t));return await r.gfgBXGY.f.checkIfWidgetShouldBeVisible(t,e)?void await r.gfgBXGY.f.updateBXGYWidgetState(t._id):(n.remove(),void delete r.gfgBXGY.state.containerRefs[i])}await(r?.gfgBXGY?.f?.getDiscountEligibleProducts(t));if(!await r.gfgBXGY.f.checkIfWidgetShouldBeVisible(t,e))return void r.gfgBXGY.f.removeWidgetIfAlreadyExists(t,e);const o=await gfg.utility.getCartV2();t.cartDataForGating=o;const a=!r.gfgBXGY.state.isBuyXGetX[t?.title]&&await r.gfgBXGY.f.checkIfGetYProductsCanBeAddedToCart(t,o);t.isBuyXGetYWidgetDisabled=a,await r.gfgBXGY.f.getWidgetAddedVariantsFromCart(t?.title,o);const s=[{generatedUI:r.gfgBXGY.f.prepareUI(t,e),offer:t}];r.f.insertIntoPageWrapper(s,e,"CUSTOM_DISCOUNT"),r.gfgBXGY.actions.registerActions(e);const l=document.getElementById(`${t.title}_${e}`)||(gfg.state.shadowRoot.isDetected?gfg.state.shadowRoot.reference.querySelector(`[id="${t.title}_${e}"]`):null);l&&(r.gfgBXGY.state.containerRefs[i]=l)}catch(t){gfg.utility.debugError("Error inside gfgCustomDiscount gfgBXGY initialize fn",t)}},f:{resolveStyleSettings:function(t){const e=t||{},i=r.gfgBXGY.BXGY_DEFAULT_STYLE_SETTINGS,n={...i},o=["keepOpenByDefault","titleBarIconColor","widgetBackgroundColor","widgetBorderColor","widgetButtonColor","widgetButtonTextColor","widgetDropdownColor","productsListLayout"];for(const t of o)void 0!==e[t]&&(n[t]=e[t]);const a=["widgetPadding","cornerRadius","buttonStyle","hyperLinkYProduct","titleBarFontWeight","titleBarFontSize","productNameFontSize","productNameFontWeight","priceFontSize","priceFontWeight","strikeThroughPriceFontSize","strikeThroughPriceFontWeight","buttonLabelFontSize","buttonLabelFontWeight"];for(const t of a)void 0!==e[t]&&(n[t]=e[t]);return n.titleBarTextColor=e.titleBarTextColor||e.widgetTextColor||i.titleBarTextColor,n.highlightColor=e.highlightColor||e.widgetTextColor||i.highlightColor,n.productNameColor=e.productNameColor||e.widgetTextColor||i.productNameColor,n.priceColor=e.priceColor||e.widgetTextColor||i.priceColor,n.strikeThroughPriceColor=e.strikeThroughPriceColor||e.widgetTextColor||i.strikeThroughPriceColor,n},getWidgetAddedVariantsFromCart:async function(t,e){try{const i=e||await gfg.utility.getCartV2(),n={};return i?.items&&i.items.forEach(e=>{if(e.properties?._kite_promo_name===t){const t=String(e.variant_id);n[t]=e.key}}),r.gfgBXGY.state.addedVariantsInCart[t]=n,n}catch(t){return gfg.utility.debugError("error in gfgBXGY getWidgetAddedVariantsFromCart",t),{}}},isProductLockedForBuyXGetX:function(t,e){if(!r.gfgBXGY.state.isBuyXGetX[t])return!1;const i=e?.id?.split?.("/")?.pop?.(),n=r.gfgBXGY.state.buyXGetXCartProductIds[t];return!n?.has(i)},isVariantSaturatedForBuyXGetX:function(t,e,i){if(!r.gfgBXGY.state.isBuyXGetX[t])return!1;const n=r.gfgBXGY.state.buyXVariantData?.[t],o=n?.[String(e)];if(!o)return!0;let a=0;const s=i?.items||[];for(const i of s)i.properties?._kite_promo_name===t&&String(i.variant_id)===String(e)&&(a+=i.quantity);const l=a,c=Math.max(0,o.qtyInCart-a),u=o.buyXItemCount>0?o.buyXItemCount:1,g=o.getYItemCount>0?o.getYItemCount:1,d=Number.isFinite(o.maxDiscountableSets)&&o.maxDiscountableSets>=0?o.maxDiscountableSets:Number.POSITIVE_INFINITY,f=Math.min(d,Math.floor(c/u),Math.floor(l/g));return Math.min(d,Math.floor(c/u),Math.floor((l+1)/g))<=f},applyButtonState:function(t,e,i,n,o){if(t.className="gfgBuyXGetYProductBtn gfgBuyXGetYProductAddToCartBtn","locked"===e)t.classList.add("gfgBXGY-btn-locked","disabled"),t.innerHTML=SVG_ICONS.LOCK_ICON,t.disabled=!0;else if("added"===e){const e=r.gfgBXGY.state.addedVariantsInCart[n]?.[o];t.classList.add("gfgBXGY-btn-remove"),t.innerText=i.remove,t.dataset.cartitemkey=e||"",t.disabled=!1}else"out_of_stock"===e?(t.classList.add("disabled"),t.innerText=i.outOfStock,t.disabled=!0):(t.innerText=i.addToCart,t.disabled=!1)},buildButtonAttrs:function(t,e,i,n){const o={class:"gfgBuyXGetYProductBtn gfgBuyXGetYProductAddToCartBtn"};if("locked"===t)o.class+=" gfgBXGY-btn-locked disabled",o.innerHTML=SVG_ICONS.LOCK_ICON;else if("added"===t){const t=r.gfgBXGY.state.addedVariantsInCart[i]?.[n];o.class+=" gfgBXGY-btn-remove",o.innerText=e.remove,o["data-cartitemkey"]=t||""}else"out_of_stock"===t?(o.class+=" disabled",o.innerText=e.outOfStock):o.innerText=e.addToCart;return o},getButtonState:function(t,e,i,n){if(i)return"out_of_stock";const o=(r.gfgBXGY.state.addedVariantsInCart[e]||{})[String(t)];return n?o?"added":"locked":"add_to_cart"},updateBXGYWidgetState:async function(t){try{let e=[...gfg.settings.customDiscount,...gfg.settings.consolidatedCustomDiscount].find(e=>e._id===t);if("CONSOLIDATED_BXGY_DISCOUNT"==e.discountFunctionType&&(e=n.gfgDynamicBogo.f.convertCCDSchemaToDynamicBogoSchema(e)),!e)return;const i=r.gfgBXGY.state.isBuyXGetX[e.title],o=await gfg.utility.getCartV2(),a=!i&&await r.gfgBXGY.f.checkIfGetYProductsCanBeAddedToCart(e);await r.gfgBXGY.f.getWidgetAddedVariantsFromCart(e.title,o);let s=document.querySelectorAll(`[id*="${e.title}_"]`);if(gfg.state.shadowRoot.isDetected){const t=gfg.state.shadowRoot.reference.querySelectorAll(`[id*="${e.title}_"]`);s=[...s,...t]}if(0===s.length)return;const l=e?.widgetSettings;l&&(l.styleSettings=r.gfgBXGY.f.resolveStyleSettings(l.styleSettings));const c=l?.styleSettings;let u=r.utility.checkMultipleLanguagePresent(l?.widgetBodyTextContent)?gfg.utility.getLocale():"en";const g=l?.widgetBodyTextContent?.[u]?.addToCartButtonText||"Add to Cart",d=l?.widgetBodyTextContent?.[u]?.removeButtonText||l?.widgetBodyTextContent?.en?.removeButtonText||"Remove",f=l?.widgetBodyTextContent?.[u]?.outOfStockButtonText||"Out of Stock",p=r.gfgBXGY.state.productsDataForBuyXGetY[e.title]||[],y=r.gfgBXGY.state.BuyXConditionFulfilled[e.title];let h=r.utility.checkMultipleLanguagePresent(l?.titleBar)?gfg.utility.getLocale():"en",m=y?"conditionMetHeadingText":"conditionNotMetHeadingText";y||"{{DISCOUNT_VALUE}}% off on shipping"!==(l?.titleBar?.[h]?.conditionNotMetHeadingText||l?.titleBar?.en?.conditionNotMetHeadingText||"")||(m="conditionMetHeadingText"),l?.titleBar?.[h]?.[m]||(h="en");const C=l?.titleBar?.[h]?.[m]||"",b=r.gfgBXGY.text.resolve(C,e),S=y?"conditionMetIconUrl":"conditionNotMetIconUrl";s.forEach(t=>{const n=t.querySelector(".gfgBXGY-badge");if(n){const t=r.gfgBXGY.state.allowedGetYQuantity[e.title]||0;y&&t>0?(n.textContent=String(t),n.style.display=""):n.style.display="none"}const s=t.querySelector(".gfgBuyXGetYAccordionTitle");s&&(s.innerHTML=b,s.style.fontSize=c?.titleBarFontSize,s.style.fontWeight=c?.titleBarFontWeight,s.style.color=c?.titleBarTextColor);const u=t.querySelector(".gfgBuyXGetYAccordionIcon");if(u){const t=l?.titleBar?.[S];if(t&&SVG_ICONS[t]){u.innerHTML=SVG_ICONS[t];const e=u.firstChild;e?.setAttribute&&e.setAttribute("fill",c?.titleBarIconColor)}else if(t){u.innerHTML="";const e=r.utility.createElementWithAttributes("img",{src:t,alt:"icon",class:"gfgBuyXGetYAccordionIconImg"});u.appendChild(e)}else u.innerHTML=""}t.querySelectorAll(".gfgBuyXGetYProductAddToCartBtn").forEach(t=>{const n=Number(t.dataset.productindex),s=p[n];if(!s)return;const l=t.closest(".gfgBuyXGetYProductCardWrapper")?.querySelector(".gfgBuyXGetYVariantSelectorSelectInput")||t.closest(".gfgBuyXGetYVariantSelector")?.querySelector(".gfgBuyXGetYVariantSelectorSelectInput"),c=l?l.value.split("/")[4]:s?.variants?.[0]?.id?.split("/")[4],u=s?.variants?.find(t=>String(t.id).includes(c))||s?.variants?.[0],y=!s.availableForSale||!u?.availableForSale,h=i?r.gfgBXGY.f.isVariantSaturatedForBuyXGetX(e.title,c,o):a||r.gfgBXGY.f.isProductLockedForBuyXGetX(e.title,s),m=r.gfgBXGY.f.getButtonState(c,e.title,y,h),C={addToCart:g,remove:d,outOfStock:f};r.gfgBXGY.f.applyButtonState(t,m,C,e.title,c)})})}catch(t){gfg.utility.debugError("Error inside gfgBXGY updateBXGYWidgetState",t)}},_ensureContainerRefs:function(t){const e=r.gfgBXGY.state.containerRefs,i=["PRODUCT_PAGE","SIDE_CART","CART_PAGE"];for(const r of i){const i=`${t}_${r}`;if(e[i]&&e[i].isConnected)continue;e[i]&&delete e[i];const n=document.getElementById(`${t}_${r}`)||(gfg.state.shadowRoot.isDetected?gfg.state.shadowRoot.reference.querySelector(`[id="${t}_${r}"]`):null);n&&(e[i]=n)}},_getContainersForDiscount:function(t){r.gfgBXGY.f._ensureContainerRefs(t);const e=[];for(const[i,n]of Object.entries(r.gfgBXGY.state.containerRefs))i.startsWith(`${t}_`)&&n.isConnected&&e.push(n);return e},_renderAfterCartOp:async function(t,e,i){try{const o=await gfg.utility.getCartV2({forceRefresh:!0});if(!o?.items)return;const a=r.gfgBXGY.f._getContainersForDiscount(e);if("add"===i){for(const t of a){const e=t.querySelectorAll(".gfgBXGY-btn-loading");for(const t of e)t.disabled=!0,t.className="gfgBuyXGetYProductBtn gfgBuyXGetYProductAddToCartBtn gfgBXGY-btn-success",t.innerHTML=SVG_ICONS.CHECK_ICON}await new Promise(t=>setTimeout(t,1200));for(const t of a){const e=t.querySelectorAll(".gfgBXGY-btn-success");for(const t of e)t.classList.add("gfgBXGY-btn-exit")}await new Promise(t=>setTimeout(t,300))}let s=[...gfg.settings.customDiscount,...gfg.settings.consolidatedCustomDiscount].find(e=>e._id===t);if(s){const t="CONSOLIDATED_BXGY_DISCOUNT"===s.discountFunctionType?n.gfgDynamicBogo.f.convertCCDSchemaToDynamicBogoSchema(s):s;await r.gfgBXGY.computeWidgetState(t,o)}if(await r.gfgBXGY.f.updateBXGYWidgetState(t),"add"===i){for(const t of a){const e=t.querySelectorAll(".gfgBXGY-btn-remove");for(const t of e)t.classList.add("gfgBXGY-btn-enter"),t.addEventListener("animationend",()=>t.classList.remove("gfgBXGY-btn-enter"),{once:!0})}gfg.f.updateCartState(null,null,null,o)}}catch(t){gfg.utility.debugError("Error inside gfgBXGY _renderAfterCartOp",t)}finally{r.gfgBXGY.state.animatingDiscounts.delete(e)}},getDiscountEligibleProducts:async function(t){try{if("BUYX_GETY_DISCOUNT"==t.discountFunctionType){const e=t?.discountSettings?.rulesData?.rulesGlobalList?.[0]?.rulesList?.[0]?.getYRule;let{ruleType:n,ruleValue:o}=e;if("buyXGetX"===n){const e=t?.discountSettings?.rulesData?.rulesGlobalList?.[0]?.rulesList?.[0]?.buyXRule;n=e?.ruleType,o=e?.ruleValue}if(!["products","collections","productVariants","productTags","productTypes"].includes(n)||"include"!=o?.operatorType)return;let a;if("products"===n||"productVariants"===n){const t=o?.products?.map(t=>t.productId);if(a=await i.getProductsDataByProductIds(t,5),"productVariants"===n)for(let t=0;tt?.variantGraphqlId);i.variants=i.variants.filter(t=>r.includes(t.id)),a[t]=i}gfg.utility.debugConsole("all products data for BuyXGetY",a)}if("collections"===n){const t=o?.collections?.map(t=>t.id);a=await i.getProductsDataFromCollectionIds(t,5),gfg.utility.debugConsole("all products data from collection for BuyXGetY",a)}if("productTags"===n){const t=o?.tags;a=await i.getProductsDataByProductTags(t,5),gfg.utility.debugConsole("all products data from productTags for BuyXGetY",a)}if("productTypes"===n){const t=o?.types;a=await i.getProductsDataByProductTypes(t,5),gfg.utility.debugConsole("all products data from productTypes for BuyXGetY",a)}a=a.filter(t=>t),r.gfgBXGY.state.productsDataForBuyXGetY[t?.title]=a}}catch(t){gfg.utility.debugError("error inside gfgBXGY getDiscountEligibleProducts",t)}},getVariantPrices:function(t,e,i){try{const{discountType:r,discountValue:n}=e,o=t?.variants?.find(t=>t.id===i);let a,s=o?.price?.amount;return"PERCENTAGE"==r&&(a=(Number(s)-Number(s)*Number(n)/100).toFixed(2)),"FIXED"==r&&(a=Math.max((Number(s)-Number(n)).toFixed(2),0)),"FIXED_PRICE"==r&&(a=Math.min(Number(s),Number(n)).toFixed(2)),{variantPrice:s,variantDiscountedPrice:a}}catch(t){gfg.utility.debugError("error inside gfgBXGY getVariantPrices",t)}},getProductDataFromIndex:function(t,e,i){try{const n=t?.target?.closest?.(".gfgBuyXGetYCustomDiscountParentContainer")?.id.replace(`_${i}`,""),o=r?.gfgBXGY?.state?.productsDataForBuyXGetY[n];return o[e]}catch(t){gfg.utility.debugError("error inside gfgBXGY getProductDataFromIndex",t)}},removeWidgetIfAlreadyExists:(t,e)=>{try{const i=`${t?.title}_${e}`,n="undefined"!=typeof CSS&&CSS.escape?CSS.escape(i):i,o=t=>{t&&t.querySelectorAll&&t.querySelectorAll(`#${n}`).forEach(t=>t.remove())};if(o(document),gfg.state.shadowRoot.isDetected&&gfg.state.shadowRoot.reference&&o(gfg.state.shadowRoot.reference),"SIDE_CART"===e&&gfg.utility.findWrapperElement){const t=gfg.utility.findWrapperElement("CUSTOM_DISCOUNT","SIDE_CART",null,"JS");(Array.isArray(t)?t:[t]).forEach(o)}delete r.gfgBXGY.state.containerRefs[i]}catch(t){gfg.utility.debugError("Error inside gfgBXGY removeWidgetIfAlreadyExists",t)}},addGetYEligibleItemToCart:async function(t,e){try{const i=[],n={_rule_id:e.discountFunctionType,_kite_promo_name:e?.discountTitle,_kite_bxgy_item:"true"};i.push({id:t,quantity:1,properties:n});return!!await gfg.utility.addToCartV2({items:i})&&(gfg.utility.BXGYActionsAfterAddToCart(),r.gfgBXGY.f.updateBXGYWidgetState(e?.discountId),!0)}catch(t){gfg.utility.debugError("Error inside gfgBXGY addGetYEligibleItemToCart",t)}},checkIfGetYProductsCanBeAddedToCart:async function(t,e){try{let i=e||await gfg.utility.getCartV2();const n=i?.items||[];if(0==n.length)return!0;const o=r.gfgBXGY.state.allowedGetYQuantity[t?.title]||0,a=r.gfgBXGY.state.isBuyXGetX[t?.title];if(a&&o<=0)return!1;if(a){let e=0;return n.forEach(i=>{i.properties?._kite_promo_name===t?.title&&(e+=i.quantity)}),e>=o}let s=0;return n.forEach(e=>{e.discounts.forEach(i=>{const r=t?.discountSettings.rulesData?.rulesGlobalList?.[0]?.rulesList?.[0]?.message;i.title!==t?.title&&i?.title!==r||(s+=e.quantity)})}),s>=o}catch(t){gfg.utility.debugError("Error inside gfgBXGY checkIfGetYProductsCanBeAddedToCart",t)}},checkIfWidgetShouldBeVisible:async function(t,e){try{const n=t?.discountSettings?.rulesData?.rulesGlobalList?.[0]?.rulesList?.[0]?.getYRule;if(!t)return r.gfgBXGY._trace("visibility:customDiscountPresent",{pageType:e,passed:!1}),!1;const o=r.gfgBXGY.state.BuyXConditionFulfilled[t?.title],a=t?.widgetSettings?.displaySettings?.alwaysKeepVisible;if(!a&&!o&&"BUYX_GETY_DISCOUNT"===t?.discountFunctionType)return r.gfgBXGY._trace("visibility:buyXConditionFulfilled",{title:t?.title,pageType:e,passed:!1,isBuyXConditionFulfilled:o,alwaysKeepVisible:a,allowedGetYQuantity:r.gfgBXGY.state.allowedGetYQuantity[t?.title]}),r.gfgBXGY.f.removeWidgetIfAlreadyExists(t,e),!1;if(!t?.widgetSettings)return r.gfgBXGY._trace("visibility:widgetSettingsPresent",{title:t?.title,pageType:e,passed:!1}),!1;let s=n?.ruleType,l=n?.ruleValue;if("buyXGetX"===s){const e=t?.discountSettings?.rulesData?.rulesGlobalList?.[0]?.rulesList?.[0]?.buyXRule;s=e?.ruleType,l=e?.ruleValue}if("exclude"===l?.operatorType)return r.gfgBXGY._trace("visibility:getYOperatorTypeNotExclude",{title:t?.title,pageType:e,passed:!1,operatorType:l?.operatorType}),!1;if(!["products","collections","productVariants","productTags","productTypes"].includes(s))return r.gfgBXGY._trace("visibility:getYRuleTypeCompatible",{title:t?.title,pageType:e,passed:!1,effectiveGetYRuleType:s}),!1;if(!i.checkForActiveCampaign(t))return r.gfgBXGY._trace("visibility:activeCampaign",{title:t?.title,pageType:e,passed:!1}),!1;const c=r?.gfgBXGY?.state?.productsDataForBuyXGetY[t?.title];if(!c||0==c.length)return r.gfgBXGY._trace("visibility:getYProductsAvailable",{title:t?.title,pageType:e,passed:!1,count:c?c.length:null}),!1;if(!await i.checkCustomDiscountWidgetIsRelevantToCurrentPage(t,e))return r.gfgBXGY._trace("visibility:relevantToCurrentPage",{title:t?.title,pageType:e,passed:!1}),!1;return await r.gfgBXGY.f.checkDiscountTriggerRules(t)?(r.gfgBXGY._trace("visibility:ALL_PASSED",{title:t?.title,pageType:e,passed:!0}),!0):(r.gfgBXGY._trace("visibility:discountTriggerRules",{title:t?.title,pageType:e,passed:!1}),!1)}catch(i){gfg.utility.debugError("Error inside gfgCustomDiscount gfgBXGY checkIfWidgetShouldBeVisible fn",i),r.gfgBXGY._trace("visibility:error",{title:t?.title,pageType:e,passed:!1,error:i?.message})}},buildRuleContext:async function(t){return{product:gfg.ruleEngine.getPdpProductContext(null,null),cart:await gfg.utility.getCartV2()}},checkDiscountTriggerRules:async function(t){try{if(!gfg.ruleEngine)return r.gfgBXGY._trace("triggerRules:noEngine",{title:t?.title,result:!0}),!0;const e=t?.discountTriggeredRulesData;if(!e?.rulesGlobalList?.length)return r.gfgBXGY._trace("triggerRules:noRules",{title:t?.title,result:!0}),!0;const i=await r.gfgBXGY.f.buildRuleContext(t),n=["collections","productTags","productTypes"],o=(e.rulesGlobalList||[]).some(t=>(t?.rulesList||[]).some(t=>n.includes(t?.ruleType)));i.cart?.items?.length&&o&&gfg.customDiscountValidationFunctions?.getLatestCartItemsProductData&&await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(i.cart);const a=gfg.utility.isDebugEnabled&&gfg.utility.isDebugEnabled(),s=a?[]:void 0,l=gfg.ruleEngine.evaluateNestedRuleGroups(e,i,a?{mode:"qualifier",trace:s}:{mode:"qualifier"});return r.gfgBXGY._trace("triggerRules:eval",()=>{const r=gfg.state&&gfg.state.cartCache;return{title:t?.title,result:l,cartToken:i.cart?.token?String(i.cart.token).slice(-8):null,cartItemCount:i.cart?.item_count,cartSubtotal:Number(i.cart?.items_subtotal_price||0)/100,cartCacheAgeMs:r&&r.timestamp?Date.now()-r.timestamp:null,items:(i.cart?.items||[]).map(t=>({v:t.variant_id,q:t.quantity,line:t.original_line_price,free:t.properties?._free_product,promo:t.properties?._kite_promo_name})),rulesGlobalOperator:e.rulesGlobalOperator,rules:s}}),l}catch(e){return gfg.utility.debugError("Error inside gfgCustomDiscount gfgBXGY checkDiscountTriggerRules fn",e),r.gfgBXGY._trace("triggerRules:error",{title:t?.title,error:e?.message,result:!1}),!1}},prepareSingleProductCard:function(t,e,i){try{const n=r.gfgBXGY.f.createProductCardElements(t,e,i);if(!n)return null;const{productImage:o,productTitle:a,productPriceContainer:s,productAddToCartButton:l,variantSelectorContainer:c}=n,u=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYVariantSelector gfgBuyXGetYSingleProductCard","data-productindex":i}),g=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYSingleProductDetailsColumn"});return g.append(a,s),c&&g.append(c),g.append(l),u.append(o,g),u}catch(t){gfg.utility.debugError("error in gfgBXGY prepareSingleProductCard",t)}},createProductCardElements:function(e,i,n){try{const{widgetSettings:o,discountSettings:a}=i,s={discountType:a?.type,discountValue:a?.rulesData?.rulesGlobalList?.[0]?.rulesList?.[0]?.discountValue},l=e?.variants?.[0],{variantPrice:c,variantDiscountedPrice:u}=r?.gfgBXGY?.f?.getVariantPrices(e,s,l?.id),g=gfg.utility.getCurrencySymbol(),d=`${g}${c}`,f=`${g}${u}`;let p=r.utility.checkMultipleLanguagePresent(o?.widgetBodyTextContent)?gfg.utility.getLocale():"en";o?.widgetBodyTextContent?.[p]?.addToCartButtonText||(p="en");const y=o?.widgetBodyTextContent?.[p]?.addToCartButtonText||"Add to Cart",h=o?.widgetBodyTextContent?.[p]?.outOfStockButtonText||"Out of Stock",m=!e.availableForSale||!l?.availableForSale,C=o?.widgetBodyTextContent?.[p]?.removeButtonText||o?.widgetBodyTextContent?.en?.removeButtonText||"Remove",b=i?.title,S=l?.id?.split("/")[4],B=r.gfgBXGY.state.isBuyXGetX[b]?r.gfgBXGY.f.isVariantSaturatedForBuyXGetX(b,S,i.cartDataForGating):i.isBuyXGetYWidgetDisabled||r.gfgBXGY.f.isProductLockedForBuyXGetX(b,e),T=r.gfgBXGY.f.getButtonState(S,b,m,B),D=o?.styleSettings,E=l?.image?.originalSrc||e?.featuredImage?.originalSrc,V=r.utility.createElementWithAttributes("img",{class:"gfgBuyXGetYProductImage",src:E,"data-default-src":e?.featuredImage?.originalSrc});let P=e.title;if(D?.hyperLinkYProduct&&e?.handle){const i=gfg.utility.getHrefForProductCollectionHandle?.("product",e.handle)||`/products/${e.handle}`;P=`${t(e.title)}`}const v=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYProductTitle",innerHTML:P,style:`color:${D?.productNameColor}; font-size:${D?.productNameFontSize}; font-weight:${D?.productNameFontWeight};`}),I=r.utility.createElementWithAttributes("div",{class:"gfgRowFlexContainer gfgProductCardPriceContainer"}),_=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYProductDiscountedPrice",innerHTML:f,style:`color:${D?.priceColor}; font-size:${D?.priceFontSize}; font-weight:${D?.priceFontWeight};`}),G=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYProductOriginalPrice",innerHTML:d,style:`color:${D?.strikeThroughPriceColor}; font-size:${D?.strikeThroughPriceFontSize}; font-weight:${D?.strikeThroughPriceFontWeight};`});I.append(G,_);const A="outline"===D?.buttonStyle?`background:transparent; color:${D?.widgetButtonColor}; border:1px solid ${D?.widgetButtonColor}; font-size:${D?.buttonLabelFontSize}; font-weight:${D?.buttonLabelFontWeight};`:`background:${D?.widgetButtonColor}; color:${D?.widgetButtonTextColor}; font-size:${D?.buttonLabelFontSize}; font-weight:${D?.buttonLabelFontWeight};`,w={addToCart:y,remove:C,outOfStock:h},X=r.gfgBXGY.f.buildButtonAttrs(T,w,b,S);X.style=A,X["data-productindex"]=n;const F=r.utility.createElementWithAttributes("button",X);let x=null;if(e?.variants?.length>1){const t=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYVariantSelectorSelectInputContainer"}),i=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYVariantSelectorSelectInputWrapper"}),n=r.utility.createElementWithAttributes("select",{class:"gfgBuyXGetYVariantSelectorSelectInput"}),a=r.utility.createElementWithAttributes("img",{class:"gfgBuyXGetYVariantSelectorSelectInputIcon",src:"https://d1cjetlwgplgi5.cloudfront.net/public/CaretDown.svg"}),s=r.gfgBXGY.state.addedVariantsInCart[b]||{},l=e.variants.find(t=>s[String(t.id).split("/")[4]])?.id,c=o?.widgetBodyTextContent?.[p]?.selectButtonText||"Select";if(!l){const t=r.utility.createElementWithAttributes("option",{class:"variantSelectorOption",innerText:c,value:"",disabled:!0,selected:!0});n.append(t)}for(const t of e?.variants){const e={class:"variantSelectorOption",innerText:t?.title,value:t?.id};l&&t.id===l&&(e.selected=!0),t?.availableForSale||(e.disabled=!0,e.innerText=`${t?.title} (Out of Stock)`);const i=r.utility.createElementWithAttributes("option",e);n.append(i)}i.append(n,a),t.append(i),x=t}return{productImage:V,productTitle:v,productPriceContainer:I,productAddToCartButton:F,variantSelectorContainer:x}}catch(t){gfg.utility.debugError("error in gfgBXGY createProductCardElements",t)}},prepareHorizontalProductCard:function(t){try{const{productImage:e,productTitle:i,productPriceContainer:n,productAddToCartButton:o,variantSelectorContainer:a}=t,s=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYProductCardWrapper"}),l=r.utility.createElementWithAttributes("div",{class:"gfgColFlexContainer gfgTitleAndPriceContainer"});l.append(i,n);const c=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCardTopGroup"});c.append(e,l);const u=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCardBottomGroup"});return a?u.append(a,o):u.append(o),s.append(c,u),s}catch(t){gfg.utility.debugError("error in gfgBXGY prepareHorizontalProductCard",t)}},prepareVerticalProductCard:function(t){try{const{productImage:e,productTitle:i,productPriceContainer:n,productAddToCartButton:o,variantSelectorContainer:a}=t,s=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYProductCardWrapper gfgBuyXGetYProductCardVertical"}),l=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCardVerticalImageContainer"});l.append(e);const c=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCardVerticalDetails"});c.append(i,n),a&&c.append(a);const u=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCardVerticalAction"});return u.append(o),s.append(l,c,u),s}catch(t){gfg.utility.debugError("error in gfgBXGY prepareVerticalProductCard",t)}},prepareProductCard:function(t,e,i){try{const n=e?.widgetSettings?.styleSettings?.productsListLayout,o=r.gfgBXGY.f.createProductCardElements(t,e,i);return o?"vertical"===n?r.gfgBXGY.f.prepareVerticalProductCard(o):r.gfgBXGY.f.prepareHorizontalProductCard(o):null}catch(t){gfg.utility.debugError("error in gfgBXGY prepareProductCard",t)}},prepareProductsList:function(t){try{const e=r?.gfgBXGY?.state?.productsDataForBuyXGetY[t?.title],{discountSettings:i,widgetSettings:n}=t,o=n?.styleSettings?.productsListLayout;if(1==e.length)return r.gfgBXGY.f.prepareSingleProductCard(e[0],t,0);const a="vertical"===o?"gfgBuyXGetYProductListVertical":"",s="vertical"!==o?2==e.length?"gfgTwoColumnGrid":3==e.length?"gfgThreeColumnGrid":"":"",l=r.utility.createElementWithAttributes("div",{class:`gfgBuyXGetYProductListWrapper ${a} ${s}`.trim()});return e.forEach((e,i)=>{const n=r.gfgBXGY.f.prepareProductCard(e,t,i);n&&l.append(n)}),l}catch(t){gfg.utility.debugError("error in gfgBXGY prepareProductsList",t)}},prepareAccordionAction:function(t,e){try{const{widgetSettings:i,discountSettings:n}=t,o=i?.styleSettings;let a=r.utility.checkMultipleLanguagePresent(i?.titleBar)?gfg.utility.getLocale():"en";const s=e?"accordion-state-open":"",l=r.utility.createElementWithAttributes("div",{class:`gfgBuyXGetYCustomDiscountAccordionAction gfgRowFlexContainer ${s}`,style:`background:${o?.widgetBackgroundColor||"#ffffff"};\n --outline-color: ${o?.widgetBorderColor||"#E5E5E5"};\n color: ${o?.titleBarTextColor||"#0F0F0F"};\n padding: ${o?.widgetPadding||"8px"};\n margin-bottom: 12px;\n `}),c=r.utility.createElementWithAttributes("div",{class:"gfgRowFlexContainer gfgBuyXGetYAccordionTitleContainer"}),u=r.utility.createElementWithAttributes("div",{class:`gfgAccordionChild gfgAccordionControl ${s}`}),g=t?.title,d=r.gfgBXGY.state.allowedGetYQuantity[g]||0,f=r.gfgBXGY.state.BuyXConditionFulfilled[g],p=f?"conditionMetIconUrl":"conditionNotMetIconUrl";let y=f?"conditionMetHeadingText":"conditionNotMetHeadingText";f||"{{DISCOUNT_VALUE}}% off on shipping"!==(i?.titleBar?.[a]?.conditionNotMetHeadingText||i?.titleBar?.en?.conditionNotMetHeadingText||"")||(y="conditionMetHeadingText"),i?.titleBar?.[a]?.[y]||(a="en");const h=i?.titleBar?.[a]?.[y]||i?.titleBar?.en?.[y]||"",m=r.gfgBXGY.text.resolve(h,t),C=i?.titleBar?.[p],b=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYAccordionIcon"});if(C&&SVG_ICONS[C]){b.innerHTML=SVG_ICONS[C];const t=b.firstChild;t?.setAttribute&&t.setAttribute("fill",o?.titleBarIconColor)}else if(C){const t=r.utility.createElementWithAttributes("img",{src:C,alt:"icon",class:"gfgBuyXGetYAccordionIconImg"});b.appendChild(t)}const S=r.utility.createElementWithAttributes("div",{class:"gfgAccordionChild gfgBuyXGetYAccordionTitle",innerHTML:m,style:`font-size:${o?.titleBarFontSize}; font-weight:${o?.titleBarFontWeight}; color:${o?.titleBarTextColor}`}),B=r.utility.createElementWithAttributes("span",{class:"gfgBXGY-badge",innerText:String(d)});return f&&d>0||(B.style.display="none"),c.append(b,S),u.innerHTML=SVG_ICONS.ARROW_ICON,l.append(c,B,u),l}catch(t){gfg.utility.debugError("error in gfgBXGY prepareAccordionAction",t)}},prepareAccordionBody:function(t,e){try{const{widgetSettings:i,discountSettings:n}=t,o=i?.styleSettings,a=o?.productsListLayout,s=r?.gfgBXGY?.state?.productsDataForBuyXGetY[t?.title],l="vertical"!==a,c=l&&s?.length>3,u=r.gfgBXGY.f.prepareProductsList(t),g=l?"":"gfgBuyXGetYAccordionBodyVertical",d=e?"accordion-state-open":"",f=r.utility.createElementWithAttributes("div",{class:`gfgBuyXGetYCustomDiscountAccordionBodyContainer ${d} ${g}`.trim(),style:`background:${o?.widgetBackgroundColor};\n color: ${o?.productNameColor};\n --outline-color: ${o?.widgetBorderColor||"#E5E5E5"};\n --widget-padding: ${o?.widgetPadding||"8px"};\n `}),p=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCustomDiscountAccordionBody"}),y=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCustomDiscountScrollButton left",innerHTML:SVG_ICONS.ARROW_ICON}),h=r.utility.createElementWithAttributes("div",{class:"gfgBuyXGetYCustomDiscountScrollButton right",innerHTML:SVG_ICONS.ARROW_ICON});return p.append(u,c?y:"",c?h:""),c&&(y.style.opacity="0.3",h.style.opacity="1",u.addEventListener("scroll",()=>{const{scrollLeft:t,scrollWidth:e,clientWidth:i}=u,r=e-i;y.style.opacity=t<=5?"0.3":"1",h.style.opacity=t>=r-5?"0.3":"1"},{passive:!0})),f.append(p),f}catch(t){gfg.utility.debugError("error in gfgBXGY prepareAccordionBody",t)}},prepareUI:function(t,e){try{const{widgetSettings:i,discountSettings:n}=t,o=i?.styleSettings,a={discountId:t?._id,discountType:n?.type,discountValue:n?.rulesData?.rulesGlobalList?.[0]?.rulesList?.[0]?.discountValue,discountFunctionType:t?.discountFunctionType,discountTitle:t?.title},s=`${t?.title}_${e}`,l=r.gfgBXGY.state.accordionOpenState[s],c=void 0!==l?l:!!o?.keepOpenByDefault,u=r.utility.createElementWithAttributes("div",{id:s,class:`gfgBuyXGetYCustomDiscountParentContainer_${e} gfgBuyXGetYCustomDiscountParentContainer`,style:`border-radius:${o?.cornerRadius||"6px"}; --corner-radius:${o?.cornerRadius||"6px"}; --fg-highlight:${o?.highlightColor||"#199800"};`,"data-discountsettings":JSON.stringify(a),"data-widgetsettings":JSON.stringify(i)}),g=r.gfgBXGY.f.prepareAccordionAction(t,c),d=r.gfgBXGY.f.prepareAccordionBody(t,c);return u.append(d),u.append(g),u}catch(t){gfg.utility.debugError("Error inside gfgCustomDiscount gfgBXGY prepareUI fn",t)}}},actions:{widgetClickFunction:async function(t,e){try{if(t.target.closest(".gfgBuyXGetYCustomDiscountAccordionAction"))return void r.gfgBXGY.actions.toggleAccordion(t,e);if(t.target.closest(".gfgBXGY-btn-remove")){t.preventDefault(),t.stopPropagation();const i=t.target.closest(".gfgBXGY-btn-remove");if(i.disabled)return;const n=i.closest(`.gfgBuyXGetYCustomDiscountParentContainer_${e}`),o=JSON.parse(n?.dataset?.discountsettings||"{}"),a=o?.discountTitle;let s=i.dataset.cartitemkey;if(!s){const n=i.closest(".gfgBuyXGetYProductCardWrapper")||i.closest(".gfgBuyXGetYVariantSelector"),o=n?.querySelector(".gfgBuyXGetYVariantSelectorSelectInput");let l;if(o)l=o.value.split("/")[4];else{const n=Number(i.dataset.productindex),o=r.gfgBXGY.f.getProductDataFromIndex(t,n,e);l=o?.variants?.[0]?.id?.split("/")[4]}s=r.gfgBXGY.state.addedVariantsInCart[a]?.[l]}if(!s)return;r.gfgBXGY.state.animatingDiscounts.add(a),i.style.height=`${i.offsetHeight}px`,i.disabled=!0,i.className="gfgBuyXGetYProductBtn gfgBuyXGetYProductAddToCartBtn gfgBXGY-btn-loading",i.innerHTML='';const l=r.gfgBXGY.f._getContainersForDiscount(a);for(const t of l)for(const e of t.querySelectorAll(".gfgBuyXGetYProductAddToCartBtn"))e.disabled=!0;return await gfg.utility.changeCart({id:s,quantity:0}),await r.gfgBXGY.f._renderAfterCartOp(o?.discountId,a,"remove"),void gfg.utility.BXGYActionsAfterAddToCart()}if(t.target.classList.contains("gfgBuyXGetYProductAddToCartBtn")){if(t.preventDefault(),t.stopPropagation(),t.target.classList.contains("disabled"))return;if(t.target.classList.contains("gfgBXGY-btn-loading"))return;if(t.target.classList.contains("gfgBXGY-btn-success"))return;let i;const n=t.target.closest(".gfgBuyXGetYProductCardWrapper"),o=t.target.closest(".gfgBuyXGetYVariantSelector"),a=(n||o)?.querySelector(".gfgBuyXGetYVariantSelectorSelectInput");if(a&&!a.value)return a.classList.remove("gfg-variant-select-error"),a.offsetWidth,void a.classList.add("gfg-variant-select-error");if(a)i=a.value;else{const n=Number(t?.target?.dataset?.productindex),o=r.gfgBXGY.f.getProductDataFromIndex(t,n,e);i=o?.variants?.[0]?.id}i=i.split("/")[4];const s=t.target.closest(`.gfgBuyXGetYCustomDiscountParentContainer_${e}`),l=JSON.parse(s?.dataset?.discountsettings||""),c=l?.discountTitle;r.gfgBXGY.state.animatingDiscounts.add(c);const u=t.target;u.style.height=`${u.offsetHeight}px`,u.disabled=!0,u.className="gfgBuyXGetYProductBtn gfgBuyXGetYProductAddToCartBtn gfgBXGY-btn-loading",u.innerHTML='';const g=r.gfgBXGY.f._getContainersForDiscount(c);for(const t of g)for(const e of t.querySelectorAll(".gfgBuyXGetYProductAddToCartBtn:not(.gfgBXGY-btn-loading):not(.gfgBXGY-btn-remove)"))e.disabled=!0,e.classList.add("disabled");const d=[{id:i,quantity:1,properties:{_rule_id:l.discountFunctionType,_kite_promo_name:c,_kite_bxgy_item:"true"}}];return void(await gfg.utility.addToCartV2({items:d})?(await r.gfgBXGY.f._renderAfterCartOp(l.discountId,c,"add"),gfg.utility.BXGYActionsAfterAddToCart()):(r.gfgBXGY.state.animatingDiscounts.delete(c),await r.gfgBXGY.f.updateBXGYWidgetState(l.discountId)))}if(t.target.closest(".gfgBuyXGetYCustomDiscountScrollButton"))return t.preventDefault(),t.stopPropagation(),void r.gfgBXGY.actions.handleScrollButtonClick(t,e)}catch(t){gfg.utility.debugError("Error inside gfgBXGY widgetClickFunction",t)}},registerActions:function(t){try{let e=document.querySelectorAll(`.gfgBuyXGetYCustomDiscountParentContainer_${t}`);if(gfg.state.shadowRoot.isDetected){const i=gfg.state.shadowRoot.reference.querySelectorAll(`.gfgBuyXGetYCustomDiscountParentContainer_${t}`);e=[...e,...i]}e.forEach(e=>{if(!e)throw new Error("customDiscountBuyXGetYAccordionRef was not found");e.dataset.actionRegistered||(e.addEventListener("click",async e=>r.gfgBXGY.actions.widgetClickFunction(e,t)),e.dataset.actionRegistered=!0,r.gfgBXGY.actions.registerChangeEventForVariantSelectorInput(t))})}catch(t){gfg.utility.debugError("error in customDiscountLogic gfgBXGY registerActions",t)}},registerChangeEventForVariantSelectorInput:function(t){try{document.querySelectorAll(".gfgBuyXGetYVariantSelectorSelectInput").forEach(e=>{e.dataset.changeRegistered||(e.dataset.changeRegistered="true",e.addEventListener("change",e=>{e.stopPropagation(),r.gfgBXGY.actions.handleVariantChangeForVariantSelector(e,t)}))})}catch(t){gfg.utility.debugError("error in customDiscountLogic gfgBXGY registerChangeEventForVariantSelectorInput",t)}},registerGlobalClickListener:function(){try{if(window._gfgBXGYDocumentClickRegistered||(window._gfgBXGYDocumentClickRegistered=!0,document.addEventListener("click",async function(t){const e=t.target.closest('[class*="gfgBuyXGetYCustomDiscountParentContainer_"]');if(!e)return;if(e.dataset.actionRegistered)return;const i=e.className.match(/gfgBuyXGetYCustomDiscountParentContainer_(\w+)/);if(!i)return;const n=i[1];await r.gfgBXGY.actions.widgetClickFunction(t,n)}),document.addEventListener("change",function(t){if(!t.target.classList.contains("gfgBuyXGetYVariantSelectorSelectInput"))return;t.stopPropagation();const e=t.target.closest('[class*="gfgBuyXGetYCustomDiscountParentContainer_"]');if(!e)return;if(e.dataset.actionRegistered)return;const i=e.className.match(/gfgBuyXGetYCustomDiscountParentContainer_(\w+)/);if(!i)return;const n=i[1];r.gfgBXGY.actions.handleVariantChangeForVariantSelector(t,n)}),gfg.utility.debugConsole("gfgBXGY: Global click listener registered on document")),gfg.state.shadowRoot.isDetected&&gfg.state.shadowRoot.reference&&!window._gfgBXGYShadowRootClickRegistered){window._gfgBXGYShadowRootClickRegistered=!0;const t=gfg.state.shadowRoot.reference;t.addEventListener("click",async function(t){const e=t.target.closest('[class*="gfgBuyXGetYCustomDiscountParentContainer_"]');if(!e)return;if(e.dataset.actionRegistered)return;const i=e.className.match(/gfgBuyXGetYCustomDiscountParentContainer_(\w+)/);if(!i)return;const n=i[1];await r.gfgBXGY.actions.widgetClickFunction(t,n)}),t.addEventListener("change",function(t){if(!t.target.classList.contains("gfgBuyXGetYVariantSelectorSelectInput"))return;t.stopPropagation();const e=t.target.closest('[class*="gfgBuyXGetYCustomDiscountParentContainer_"]');if(!e)return;if(e.dataset.actionRegistered)return;const i=e.className.match(/gfgBuyXGetYCustomDiscountParentContainer_(\w+)/);if(!i)return;const n=i[1];r.gfgBXGY.actions.handleVariantChangeForVariantSelector(t,n)}),gfg.utility.debugConsole("gfgBXGY: Global click listener registered on shadow root")}}catch(t){gfg.utility.debugError("error in gfgBXGY registerGlobalClickListener",t)}},toggleAccordion:function(t){try{const e=t.target.closest(".gfgBuyXGetYCustomDiscountAccordionAction"),i=e.querySelector(".gfgAccordionControl"),n=e.previousElementSibling;i.classList.toggle("accordion-state-open"),n.classList.toggle("accordion-state-open"),e.classList.toggle("accordion-state-open");const o=e.closest(".gfgBuyXGetYCustomDiscountParentContainer");if(o?.id){const t=i.classList.contains("accordion-state-open");r.gfgBXGY.state.accordionOpenState[o.id]=t}}catch(t){gfg.utility.debugError("error in gfgBXGY toggleAccordion",t)}},handleVariantChangeForVariantSelector:async function(t,e){try{t.target.classList.remove("gfg-variant-select-error");const i=t.target.value,o=t?.target?.closest?.(`.gfgBuyXGetYCustomDiscountParentContainer_${e}`),a=JSON.parse(o?.dataset?.discountsettings||""),s=JSON.parse(o?.dataset?.widgetsettings||""),l=t.target.closest(".gfgBuyXGetYProductCardWrapper"),c=t.target.closest(".gfgBuyXGetYVariantSelector");let u;if(l){const t=l.querySelector(".gfgBuyXGetYProductAddToCartBtn");u=Number(t?.dataset?.productindex)}else u=Number(c?.dataset?.productindex);const g=r.gfgBXGY.f.getProductDataFromIndex(t,u,e),d=g?.variants?.find(t=>t?.id===i),f=l||c;if(f){const t=f.querySelector(".gfgBuyXGetYProductImage");if(t){const e=d?.image?.originalSrc;t.src=e||t.dataset.defaultSrc||g?.featuredImage?.originalSrc}const e=gfg.utility.getCurrencySymbol(),{variantPrice:n,variantDiscountedPrice:o}=r.gfgBXGY.f.getVariantPrices(g,a,i),s=f.querySelector(".gfgBuyXGetYProductDiscountedPrice"),l=f.querySelector(".gfgBuyXGetYProductOriginalPrice");s&&(s.innerHTML=`${e}${o}`),l&&(l.innerHTML=`${e}${n}`)}const p=!d?.availableForSale,y=f?.querySelector?.(".gfgBuyXGetYProductAddToCartBtn");if(y){let t=r.utility.checkMultipleLanguagePresent(s?.widgetBodyTextContent)?gfg.utility.getLocale():"en";s?.widgetBodyTextContent?.[t]?.addToCartButtonText||(t="en");const e=s?.widgetBodyTextContent?.[t]?.addToCartButtonText||"Add to Cart",o=s?.widgetBodyTextContent?.[t]?.outOfStockButtonText||"Out of Stock",l=s?.widgetBodyTextContent?.[t]?.removeButtonText||s?.widgetBodyTextContent?.en?.removeButtonText||"Remove",c=a?.discountTitle,u=i?.split("/")[4];let d=[...gfg.settings.customDiscount,...gfg.settings.consolidatedCustomDiscount].find(t=>t.title===c);"CONSOLIDATED_BXGY_DISCOUNT"===d?.discountFunctionType&&(d=n.gfgDynamicBogo.f.convertCCDSchemaToDynamicBogoSchema(d));const f=r.gfgBXGY.state.isBuyXGetX[c],h=f?await gfg.utility.getCartV2():null,m=!f&&(d?await r.gfgBXGY.f.checkIfGetYProductsCanBeAddedToCart(d):!r.gfgBXGY.state.BuyXConditionFulfilled[c]),C=f?r.gfgBXGY.f.isVariantSaturatedForBuyXGetX(c,u,h):m||r.gfgBXGY.f.isProductLockedForBuyXGetX(c,g),b=r.gfgBXGY.f.getButtonState(u,c,p,C),S={addToCart:e,remove:l,outOfStock:o};r.gfgBXGY.f.applyButtonState(y,b,S,c,u)}}catch(t){gfg.utility.debugError("error in gfgBXGY handleVariantChangeForVariantSelector",t)}},handleScrollButtonClick:function(t,e){try{const i=t.target.closest(".gfgBuyXGetYCustomDiscountAccordionBody"),r=i.closest(`.gfgBuyXGetYCustomDiscountParentContainer_${e}`).querySelector(".gfgBuyXGetYProductListWrapper"),n=t.target.closest(".gfgBuyXGetYCustomDiscountScrollButton"),o=200;n.classList.contains("left")?r.scrollLeft-=o:r.scrollLeft+=o;const a=i.querySelector(".gfgBuyXGetYCustomDiscountScrollButton.left"),s=i.querySelector(".gfgBuyXGetYCustomDiscountScrollButton.right");a&&s&&setTimeout(()=>{const{scrollLeft:t,scrollWidth:e,clientWidth:i}=r,n=e-i;a.style.opacity=t<=5?"0.3":"1",s.style.opacity=t>=n-5?"0.3":"1"},100)}catch(t){gfg.utility.debugError("error in gfgBXGY handleScrollButtonClick",t)}}},text:{resolve(t,e){try{if(!t)return"";const i=e?.discountSettings,r=i?.rulesData?.rulesGlobalList||[];if(!r[0]?.rulesList?.[0])return t;const n=gfg.utility.getCurrencySymbol?gfg.utility.getCurrencySymbol():"$",o=t=>""!==t?`${t}`:t,a=t=>r[t-1]?.rulesList?.[0],s=(t,e)=>{switch(t){case"X_QTY":return e&&e.buyXRule?.itemCount||"";case"Y_QTY":return e&&e.getYRule?.itemCount||"";case"PRODUCT_NAME":return e?this._resolveProductName(e.buyXRule):"";case"COLLECTION_NAME":return e?this._resolveCollectionName(e.buyXRule):"";case"DISCOUNT_VALUE":return e?this._resolveDiscountValue(i,e,n):"";case"SELLING_PRICE":return e&&"FIXED_PRICE"===i?.type?`${n}${parseFloat(e.discountValue||0)}`:"";default:return null}};return t.replace(/\{\{([A-Z_]+?)(?:_(\d+))?\}\}/g,(t,e,i)=>{const r=null==i?1:parseInt(i,10),n=s(e,r<1?void 0:a(r));return null===n?t:o(n)})}catch(e){return gfg.utility.debugError("error in gfgBXGY text.resolve",e),t||""}},_link:(e,i)=>`${e}`,_resolveProductName(e){if(!e)return"";const i=e.ruleType;if("products"!==i&&"productVariants"!==i)return"";const r=e.ruleValue?.products||[];if(0===r.length)return"";const n=gfg.utility.getHrefForProductCollectionHandle,o=new Set,a=[];for(const t of r){const e=t.productId||t.title;o.has(e)||(o.add(e),a.push(t))}const s=e=>{const i=t(e.title||"");return e.handle?this._link(i,n("product",e.handle)):i};return 1===a.length?s(a[0]):2===a.length?`${s(a[0])} or ${s(a[1])}`:"qualifying products"},_resolveCollectionName(e){if(!e||"collections"!==e.ruleType)return"";const i=e.ruleValue?.collections||[];if(0===i.length)return"";const r=gfg.utility.getHrefForProductCollectionHandle,n=e=>{const i=t(e.title||"");return e.handle?this._link(i,r("collection",e.handle)):i};return 1===i.length?n(i[0]):2===i.length?`${n(i[0])} or ${n(i[1])}`:"qualifying collections"},_resolveDiscountValue(t,e,i){const r=t?.type,n=e?.discountValue;return r&&null!=n?"PERCENTAGE"===r?`${n}%`:"FIXED"===r?`${i}${parseFloat(n)}`:"":""}}},gfgShippingDiscountV2:{state:{isFirstRenderForShippingDiscount:!0,productFound:{},productVariantFrount:{},collectionFound:{},appBlockKeyMap:{tBarHeadingFontSize:"titleBarHeadingFontSize",tBarHeadingFontWt:"titleBarHeadingFontWeight",tBarSubHeadingFontSize:"titleBarSubHeadingFontSize",tBarSubHeadingFontWt:"titleBarSubHeadingFontWeight",tBarTextColor:"titleBarTextColor",tBarBackgroundColor:"titleBarBackgroundColor",widgetBodyFontSize:"widgetBodyFontSize",widgetBodyFontWt:"widgetBodyFontWeight",widgetBodyBackgroundColor:"widgetBodyBackgroundColor",widgetBodyBorderColor:"widgetBodyBorderColor"}},init:function(){try{let t=gfg.settings.shippingDiscount;const e=gfg.f.getPageType();"product"===e&&r.gfgShippingDiscountV2.productPage.init(t),"cart"===e&&r.gfgShippingDiscountV2.cartPage.init(t),"cart"!==e&&r.gfgShippingDiscountV2.sideCart.init(t)}catch(t){gfg.utility.debugConsole("Error inside gfgShippingDiscountV2 init fn",t)}},productPage:{init:function(t){try{r.gfgShippingDiscountV2.initialize(t,"PRODUCT_PAGE")}catch(t){gfg.utility.debugConsole("Error inside productPage.init fn",t)}}},cartPage:{init:function(t){try{r.gfgShippingDiscountV2.initialize(t,"CART_PAGE")}catch(t){gfg.utility.debugConsole("Error inside cartPage.init fn",t)}}},sideCart:{init:function(t){try{r.gfgShippingDiscountV2.initialize(t,"SIDE_CART")}catch(t){gfg.utility.debugConsole("Error inside cartPage.init fn",t)}}},initialize:async function(t,e){try{const n=t.filter(t=>t.isEnabled);let o=[],a=await gfg.utility.getCartV2();for(let t of n)try{if(!t)continue;if(!i.checkForActiveCampaign(t))continue;if(!await i.checkCustomDiscountWidgetIsRelevantToCurrentPage(t,e))continue;await i.verifyCustomDiscountRules(t,a),r.gfgShippingDiscountV2.f.checkIfShippingDiscountAppBlockIsAdded(t,e);const n=r.gfgShippingDiscountV2.f.prepareShippingDiscountUI(t);o.push({generatedUI:n,offer:t})}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 initialize fn",t)}r.gfgShippingDiscountV2.f.insertIntoPageWrapper(o,e)}catch(t){gfg.utility.debugConsole("Error inside gfgShippingDiscountV2 initialize fn",t)}},f:{cutOffshouldInitAgainConditionsForUnifiedAndShipping:function(){try{const t=new Date("2024-11-27");return new Date(gfg.settings.merchantInfo.createdAt)>t}catch(t){return gfg.utility.debugConsole("error in cutOffshouldInitAgainConditionsForUnifiedAndShipping:",t),!1}},verifyIndividualRule:async function(t,e){try{t.ruleType,t.ruleValue,t.type}catch(t){gfg.utility.debugConsole("Error inside gfgShippingDiscountV2 verifyIndividualRule fn",t)}},renderTitleBarUI:function(e,i,r,n){try{const{titleBarHeadingFontSize:o,titleBarSubHeadingFontSize:a,titleBarHeadingFontWeight:s,titleBarSubHeadingFontWeight:l,titleBarTextColor:c}=n,u=gfg.utility.getFontWeightValue(s),g=gfg.utility.getFontWeightValue(l);return e?`\n
\n icon-img\n
\n
\n
\n ${i}\n
\n
\n ${r}\n
\n
\n `:`\n
\n
\n ${i}\n
\n
\n ${r}\n
\n
\n `}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 renderTitleBarUI fn",t)}},replaceTextDynamicVariables:function(e,i,r){try{const{ruleType:n}=i,o=gfg.utility.getCurrencySymbol();if(e=(e=e.replace("{{CURRENCY}}",o)).replace("{{DISCOUNT_VALUE}}",r),!n)return e;let a="";switch(n){case"cartSubtotal":a=(i.ruleValue.remainingSubtotalValue||i.ruleValue.value).toString(),a=a.replace(/\.0+$/,""),e=(e=e.replace("{{AMOUNT}}",i.ruleValue.value+"")).replace("{{REMAINING_AMOUNT}}",a+"");break;case"cartQuantity":a=i.ruleValue.remainingQuantityValue||i.ruleValue.value,e=(e=e.replace("{{QUANTITY}}",i.ruleValue.value+"")).replace("{{REMAINING_QUANTITY}}",a+"");break;case"products":case"productVariants":const r=t(i.ruleValue.qualifiedProductObj.title),n=i.ruleValue.qualifiedProductObj.handle,o=t(i.ruleValue.qualifiedProductObj.variantTitle),s=i.ruleValue.qualifierValue,l=`${r}`;e=(e=(e=(e=(e=(e=(e=e.replace("{{PRODUCT}}",r)).replace("{{PRODUCT_VARIANT}}",o)).replace("{{QUANTITY}}",s)).replace("{{REMAINING_QUANTITY}}",i.ruleValue.remainingValue)).replace("{{AMOUNT}}",s)).replace("{{REMAINING_AMOUNT}}",i.ruleValue.remainingValue)).replace("{{PRODUCT_LINK}}",l);break;case"collections":const c=t(i.ruleValue.qualifiedCollectionObj.title),u=i.ruleValue.qualifiedCollectionObj.handle,g=i.ruleValue.qualifierValue,d=`${c}`;e=(e=(e=(e=(e=(e=e.replace("{{COLLECTION}}",c)).replace("{{QUANTITY}}",g)).replace("{{REMAINING_QUANTITY}}",i.ruleValue.remainingValue)).replace("{{AMOUNT}}",g)).replace("{{REMAINING_AMOUNT}}",i.ruleValue.remainingValue)).replace("{{COLLECTION_LINK}}",d);break;case"shippingCountry":const f=i.ruleValue.qualifiedCountry;e=e.replace("{{COUNTRY}}",f);break;case"customerTags":const p=i.ruleValue.qualifiedTag;e=e.replace("{{CUSTOMER_TAG}}",p);break;case"productHasSubscription":const y=i.ruleValue.qualifierValue;e=(e=(e=(e=e.replace("{{QUANTITY}}",y)).replace("{{REMAINING_QUANTITY}}",i.ruleValue.remainingValue)).replace("{{AMOUNT}}",y)).replace("{{REMAINING_AMOUNT}}",i.ruleValue.remainingValue);break;case"lineAttributes":const h=i.ruleValue.qualifiedLineValue,m=i.ruleValue.qualifiedLineProperty,C=i.ruleValue.qualifierValue;e=(e=(e=(e=(e=(e=e.replace("{{LINE_VALUE}}",h)).replace("{{LINE_PROPERTY}}",m)).replace("{{QUANTITY}}",C)).replace("{{REMAINING_QUANTITY}}",i.ruleValue.remainingValue)).replace("{{AMOUNT}}",C)).replace("{{REMAINING_AMOUNT}}",i.ruleValue.remainingValue);break;case"cartAttributes":const b=i.ruleValue.qualifiedCartValue,S=i.ruleValue.qualifiedCartKey;e=(e=e.replace("{{CART_VALUE}}",b)).replace("{{CART_PROPERTY}}",S);break;case"productTags":const B=i.ruleValue.tagName,T=i.ruleValue.remainingValue,D=i.ruleValue.qualifierValue;e=(e=(e=(e=(e=e.replace("{{PRODUCT_TAG}}",B)).replace("{{QUANTITY}}",D)).replace("{{REMAINING_QUANTITY}}",T)).replace("{{AMOUNT}}",D)).replace("{{REMAINING_AMOUNT}}",T);break;case"productTypes":const E=i.ruleValue.productType,V=i.ruleValue.remainingValue,P=i.ruleValue.qualifierValue;e=(e=(e=(e=(e=e.replace("{{PRODUCT_TYPE}}",E)).replace("{{QUANTITY}}",P)).replace("{{REMAINING_QUANTITY}}",V)).replace("{{AMOUNT}}",P)).replace("{{REMAINING_AMOUNT}}",V)}return e}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 replaceTextDynamicVariables fn",t)}},renderVerticalStepperProgressBarUI:function(e){try{const i=r.utility.checkMultipleLanguagePresent(e.widgetSettings.rulesData.rulesGlobalList[0].rulesList[0].ruleText)?gfg.utility.getLocale():"en",n=e.widgetSettings.styleSettings,{widgetBodyFontSize:o,widgetBodyFontWeight:a,widgetBodyTextColor:s}=n,l=gfg.utility.getFontWeightValue(a),c=r.gfgShippingDiscountV2.f.getDiscountValue(e),u=e.widgetSettings.rulesData.rulesGlobalList[0].rulesList.filter(t=>t.showOnWidget),g=e.widgetSettings.rulesData.rulesGlobalList[0].finalCheckBox,d=[...u,g].filter(t=>t.showOnWidget),f=d.map((t,e)=>{const n=t.conditionMet||!1,o=n?"conditionMetText":"conditionNotMetText",a=t[n?"conditionMetIconUrl":"conditionNotMetIconUrl"];let s=e\n icon-img\n \n
\n ${e.text}\n
\n `,p.appendChild(i)}return p}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 renderStepperProgressBarUI fn",t)}},renderHorizontalStepperProgressBarUI:function(e){try{const i=r.utility.checkMultipleLanguagePresent(e.widgetSettings.rulesData.rulesGlobalList[0].rulesList[0].ruleText)?gfg.utility.getLocale():"en",n=e.widgetSettings.styleSettings,{widgetBodyFontSize:o,widgetBodyFontWeight:a,widgetBodyTextColor:s}=n,l=gfg.utility.getFontWeightValue(a),c=r.gfgShippingDiscountV2.f.getDiscountValue(e),u=e.widgetSettings.rulesData.rulesGlobalList[0].rulesList.filter(t=>t.showOnWidget),g=e.widgetSettings.rulesData.rulesGlobalList[0].finalCheckBox,d=[...u,g].filter(t=>t.showOnWidget),f=d.map((t,e)=>{const n=t.conditionMet||!1,o=n?"conditionMetText":"conditionNotMetText",a=t[n?"conditionMetIconUrl":"conditionNotMetIconUrl"];let s=e\n icon-img\n \n
${e.text}
\n `,p.appendChild(i)}return p}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 renderHorizontalStepperProgressBarUI fn",t)}},renderSingleRuleProgressBarUI:function(t){try{const e=r.utility.checkMultipleLanguagePresent(t.widgetSettings.rulesData.rulesGlobalList[0].rulesList[0].ruleText)?gfg.utility.getLocale():"en",i=t.widgetSettings.styleSettings,{widgetBodyFontSize:n,widgetBodyFontWeight:o,widgetBodyTextColor:a}=i,s=gfg.utility.getFontWeightValue(o),l=r.gfgShippingDiscountV2.f.getDiscountValue(t),c=t.widgetSettings.rulesData.rulesGlobalList[0].rulesList.filter(t=>t.showOnWidget),u=t.widgetSettings.rulesData.rulesGlobalList[0].finalCheckBox,g=[...c,u].filter(t=>t.showOnWidget),d=g.map((t,i)=>{const n=t.conditionMet||!1,o=n?"conditionMetText":"conditionNotMetText",a=t[n?"conditionMetIconUrl":"conditionNotMetIconUrl"];let s=i0?`calc(${c[0].ruleValue.dynamicProgressBarWidth}% - 16px)`:"0px",m.style.backgroundColor=T,y.style.backgroundColor=T,p.style.backgroundColor=D,S.appendChild(B),C.appendChild(S),C.appendChild(b),f.appendChild(p),f.appendChild(C),f}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 renderSingleRuleProgressBarUI fn",t)}},getDiscountValue:function(t){try{const e=gfg.utility.getActiveCurrencyRate(),i=t.discountSettings.value;let r="PERCENTAGE"===t.discountSettings.type?i:(i*e).toFixed(2);return`${r}`.endsWith(".00")?r.slice(0,-3):r}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 getDiscountValue fn",t)}},prepareShippingDiscountUI:function(t){try{const e=document.createElement("div"),i=document.createElement("div"),n=document.createElement("div");e.classList.add("gfgShippingDiscountParentContainer"),i.classList.add("gfgShippingDiscountTopSectionContainer"),n.classList.add("gfgShippingDiscountBottomSectionContainer");const{widgetSettings:o}=t,a=o.styleSettings;e.style.backgroundColor=a.widgetBodyBackgroundColor,e.style.border=` 1.8px solid ${a.widgetBodyBorderColor}`,n.style.backgroundColor=a.widgetBodyBackgroundColor;const s=r.utility.checkMultipleLanguagePresent(o.titleBar)?gfg.utility.getLocale():"en",l=o.titleBar.conditionMet||!1,c=l?"conditionMetIconUrl":"conditionNotMetIconUrl",u=l?"conditionMetHeadingText":"conditionNotMetHeadingText",g=l?"conditionMetSubheadingText":"conditionNotMetSubheadingText",d=o.titleBar[c];let f=o.titleBar?.[s]?.[u]||o.titleBar.en[u],p=o.titleBar?.[s]?.[g]||o.titleBar.en[g];const y=r.gfgShippingDiscountV2.f.getDiscountValue(t),h=gfg.utility.getCurrencySymbol();f=f.replace("{{CURRENCY}}",h),p=p.replace("{{CURRENCY}}",h),f=f.replace("{{DISCOUNT_VALUE}}",y),p=p.replace("{{DISCOUNT_VALUE}}",y);const m=r.gfgShippingDiscountV2.f.renderTitleBarUI(d,f,p,a);i.style.backgroundColor=a.titleBarBackgroundColor,i.style.display=o.titleBar.showOnWidget?"flex":"none",i.innerHTML=m;let C=a.templateType,b=null;switch(C){case"SINGLE_RULE_LAYOUT":b=r.gfgShippingDiscountV2.f.renderSingleRuleProgressBarUI(t);break;case"VERTICAL_CHECKPOINT":b=r.gfgShippingDiscountV2.f.renderVerticalStepperProgressBarUI(t);break;case"HORIZONTAL_CHECKPOINT":b=r.gfgShippingDiscountV2.f.renderHorizontalStepperProgressBarUI(t)}return n.appendChild(b),e.appendChild(i),e.appendChild(n),e}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 prepareShippingDiscountUI fn",t)}},clearExistingContent:function(t){try{t.forEach(t=>{t.innerHTML=""})}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 clearExistingContent fn",t)}},appendNewUI:function(t,e,i){try{if(0===t?.length&&!r.gfgShippingDiscountV2.f.cutOffshouldInitAgainConditionsForUnifiedAndShipping())return void(gfg.state.shouldInitShippingDiscountAgain=!0);t.forEach(t=>{e.forEach(r=>{if(i.length>0){const i=t.id;if(!(r.offer._id==i)&&e.length>1)return}const n=r.generatedUI.cloneNode(!0);t.appendChild(n)})})}catch(t){gfg.utility.debugError("Error inside gfgShippingDiscountV2 appendNewUI fn",t)}},insertIntoPageWrapper:function(t,e){try{if(0===t.length)return;const i=gfg.utility.findWrapperElement("SHIPPING_DISCOUNT",e,null,"JS");let n=document.querySelectorAll(".gfgShippingDiscountWrapperV2");r.gfgShippingDiscountV2.f.clearExistingContent(i),r.gfgShippingDiscountV2.f.appendNewUI(i,t,n)}catch(t){gfg.utility.debugConsole("Error inside gfgShippingDiscountV2 insertIntoPageWrapper fn",t)}},checkIfShippingDiscountAppBlockIsAdded:function(t,e){try{const i=document.querySelectorAll(".gfgShippingDiscountWrapperV2");for(const n of i)if(n.id===t._id){t.widgetSettings.styleSettings.isThemeEditorSettings=!0;const i=n.getAttribute("data-setting")||{},o=JSON.parse(i);for(const[i,n]of Object.entries(o)){["blockId","sideCartEnabled"].includes(i)||("SIDE_CART"!==e||o.sideCartEnabled)&&(t.widgetSettings.styleSettings[r.gfgShippingDiscountV2.state.appBlockKeyMap[i]]=n)}}}catch(t){return gfg.utility.debugError("Error inside gfgShippingDiscountV2 checkIfShippingDiscountAppBlockIsAdded fn",t),!1}}}}},n={state:{},f:{getDiscountAllocations:function(t,e){try{let i={},r={},n={};for(let n of t.items)n.discounts.forEach(t=>{let o=t.amount/(100*Number(gfg.utility.getActiveCurrencyRate()));e.cartDiscounts&&(i[t.title]=i[t.title]?i[t.title]+o:o),e.productDiscounts&&(!r[n.variant_id]&&(r[n.variant_id]={}),r[n.variant_id][t.title]=r[n.variant_id][t.title]?r[n.variant_id][t.title]+o:o)});return e.cartDiscounts&&(t.cart_level_discount_applications||[]).forEach(t=>{let e=(Number(t.total_allocated_amount)||0)/(100*Number(gfg.utility.getActiveCurrencyRate()));e>0&&(n[t.title]=n[t.title]?n[t.title]+e:e)}),{cartDiscountAllocations:i,productDiscountAllocations:r,orderDiscountAllocations:n}}catch(t){gfg.utility.debugError("error in getDiscountAllocations",t)}},getDiscountedCartSubtotalExcludingCurrentDiscount:function(t){try{const e=t.original_total_price/100,i=n.f.getDiscountAllocations(t);let r=0;const o=t.discountMessages;return Object.keys(i).forEach(t=>{o.includes(t)||(r+=i[t])}),e-r}catch(t){gfg.utility.debugError("error in getDiscountedCartSubtotalExcludingCurrentDiscount",t)}},checkIfWidgetShouldBeVisible:async function(t,e){try{if(!t.isEnabled)return!1;if(!i.checkForActiveCampaign(t))return!1;if(!await i.checkCustomDiscountWidgetIsRelevantToCurrentPage(t,e))return!1;const r=t.segmentsData?.segmentsList;return!(!r||0===r.length)}catch(t){return gfg.utility.debugError("Error in checkIfWidgetShouldBeVisible",t),!1}}},init:function(){try{const t=gfg.f.getPageType();"product"===t&&n.initialize("PRODUCT_PAGE"),"cart"===t&&n.initialize("CART_PAGE"),"cart"!==t&&n.initialize("SIDE_CART")}catch(t){gfg.utility.debugConsole("Error inside gfgConsolidatedCustomDiscount init fn",t)}},initialize:async function(t){try{let e=gfg.settings.consolidatedCombinedDiscount,i=gfg.settings.consolidatedCustomDiscount;const a=[...i,...e];a.length>0&&void 0!==o&&!o._state.isInitialized&&o.configure(a);const s=e.filter(t=>"CONSOLIDATED_PROGRESS_BAR"===t.discountFunctionType&&t.isEnabled);s&&s.length>0&&n.gfgProgressBar.init(s,t);const l=i.filter(t=>"CONSOLIDATED_BXGY_DISCOUNT"===t.discountFunctionType&&t.isEnabled&&"DYNAMIC_BOGO"===t.templateType);r.gfgBXGY._trace("consolidated:dispatch",()=>{const e=i.filter(t=>"CONSOLIDATED_BXGY_DISCOUNT"===t.discountFunctionType);return{pageType:t,consolidatedBXGYTotal:e.length,dynamicBogoMatched:l.length,candidates:e.map(t=>({title:t.title,isEnabled:t.isEnabled,templateType:t.templateType}))}}),l&&l.length>0&&n.gfgDynamicBogo.init(l,t)}catch(t){gfg.utility.debugConsole("Error inside gfgConsolidatedCustomDiscount initialize fn",t)}},gfgProgressBar:{state:{isFirstRenderForProgressBar:!0,currentProgress:{},achievedSegments:{},cartData:null},components:{createProgressBarContainer:function(t,e,i){try{return r.utility.createElementWithAttributes("div",{id:`${t._id}_${e}`,class:`gfgCCDProgressBarWidget gfgCCDProgressBarWidget_${e}`,style:`\n background: ${i.backgroundColor||"transparent"};\n border: 1px solid ${i.borderColor||"#3c3c3c"};\n border-radius: ${i.borderRadius||"10px"};\n padding: ${i.blockPadding} ${i.inLinePadding} ${i.blockPadding} ${i.inLinePadding};\n color: ${i.textColor||"#3c3c3c"};\n `})}catch(t){gfg.utility.debugError("Error in createProgressBarContainer",t)}},createProgressBar:function(t,e,i,n){try{const o=r.utility.createElementWithAttributes("div",{class:`gfgCCDProgressBarWrapper ${i}`,style:`\n background: ${e.barEmptyColor||"#e0e0e0"};\n `}),a=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarFill",style:`\n background: ${e.barFillColor||"#d91717"};\n width: ${n?`${t}%`:"0%"};\n `});return o.appendChild(a),o}catch(t){gfg.utility.debugError("Error in createProgressBar",t)}},createSegmentText:function(t,e,i){try{const o=gfg.utility.getLocale()||"en",a=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarSegmentHeader",style:"display: flex; align-items: center; gap: 8px;"}),s=t.widgetSettings?.ruleText,l=s?.[o]?.conditionMetText||s?.en?.conditionMetText;if(l){const o=r.utility.createElementWithAttributes("span",{class:"gfgCCDProgressBarSegmentTitle",innerHTML:n.gfgProgressBar.f.replaceTextVariables(l,e,t,gfg.utility.getCurrencySymbol()),style:`font-size: ${i.textSize||"12px"};`});a.appendChild(o)}return a}catch(t){gfg.utility.debugError("Error in createSegmentText",t)}}},init:async function(t,e){try{if(!t||0===t.length)return;let i=[];for(let r of t)try{let t=await n.gfgProgressBar.initialize(r,e);t&&i.push(t)}catch(t){gfg.utility.debugError("Error inside gfgProgressBar init fn",t)}i.length>0&&r.f.insertIntoPageWrapper(i,e,"CONSOLIDATED_PROGRESS_BAR")}catch(t){gfg.utility.debugConsole("Error inside gfgProgressBar init fn",t)}},initialize:async function(t,e){try{let i=await gfg.utility.getCartV2();n.gfgProgressBar.state.cartData=i,await gfg.customDiscountValidationFunctions.getLatestCartItemsProductData(i);if(!await n.f.checkIfWidgetShouldBeVisible(t,e))return void n.gfgProgressBar.f.removeWidgetIfAlreadyExists(t,e);const r=`${t._id}_${e}`;if(document.getElementById(r))return void await n.gfgProgressBar.handleWidgetChanges(t,e);const o=n.gfgProgressBar.f.calculateProgress(t,i);return{generatedUI:n.gfgProgressBar.f.prepareProgressBarUI(t,e,o),offer:t}}catch(t){throw gfg.utility.debugConsole("Error inside gfgProgressBar initialize fn",t),t}},handleWidgetChanges:async function(t,e){try{const i=`${t._id}_${e}`,r=document.getElementById(i);if(!r)return await n.gfgProgressBar.initialize(t,e);const o=await gfg.utility.getCartV2();n.gfgProgressBar.state.cartData=o;const a=n.gfgProgressBar.f.calculateProgress(t,o),s=t.segmentsData?.segmentsList||[];return 1===s.length?this.updateSingleSegmentWidget(r,t,a,s[0]):s.length>1&&this.updateMultipleSegmentsWidget(r,t,a,s),this.updateWidgetHeading(r,t,a,s),{generatedUI:r,offer:t}}catch(i){return gfg.utility.debugError("Error in handleWidgetChanges",i),await n.gfgProgressBar.initialize(t,e)}},updateSingleSegmentWidget:function(t,e,i,r){try{const e="quantity"!==i.progressType,o=n.gfgProgressBar.f.resolveQualifierValue(r.buyXRulesData?.rulesList?.[0]?.ruleValue,e),a=i.currentValue,s=Math.min(a/o*100,100),l=t.querySelector(".gfgDynamicProgressBar");l&&(l.style.width=`${s}%`);const c=t.querySelector(".gfgCCDSingleProgressBarIndicator"),u=t.querySelector(".gfgCCDProgressBarFill");if(c&&u){const t=0===s?"0px":`calc(${s}% - 9px)`;c.style.left=t,u.style.width=`${s}%`}}catch(t){gfg.utility.debugError("Error in updateSingleSegmentWidget",t)}},updateMultipleSegmentsWidget:function(t,e,i,r){try{const o=+t.querySelector(".gfgProgressBarSegmentsContainer").dataset.totalprogress;let a=0;const s=[],l=n.gfgProgressBar.f.checkSegmentAchievement(r,i);let c=0;const u=t.querySelectorAll(".gfgCCDProgressBarFill"),g=t.querySelectorAll(".gfgCCDProgressBarCheckmark");l.achievedSegments.forEach(t=>{const e=u[c];e&&(a+=100,s.push({progressFill:e,progress:100,progressCheckmark:g[c]})),c++}),l.nextSegment&&(a+=l.nextSegment.progress,s.push({progressFill:u[c],progress:l.nextSegment.progress,progressCheckmark:g[c]}),c++);for(let t=c;t{setTimeout(()=>{t.progressFill&&(t.progressFill.style.width=`${t.progress}%`),t.progressCheckmark&&(t.progressCheckmark.innerHTML=100===t.progress?SVG_ICONS.CHECK_MARK_ICON:"",t.progressCheckmark.style.border=100===t.progress?`2px solid ${d.barFillColor||"#000000"}`:`2px solid ${d.barEmptyColor||"#CCCCCC"}`)},100*e)}),t.querySelector(".gfgProgressBarSegmentsContainer").dataset.totalprogress=a}catch(t){gfg.utility.debugError("Error in updateMultipleSegmentsWidget",t)}},updateWidgetHeading:function(t,e,i,r){try{const o=t.querySelector(".gfgCCDProgressBarHeadingText");if(!o)return;const a=n.gfgProgressBar.f.checkSegmentAchievement(r,i),s=a.nextSegment,l=gfg.utility.getLocale()||"en";let c,u=e.widgetSettings.heading.title;if(a.allSegmentsAchieved)c=u?.[l]?.conditionMetText||u?.en?.conditionMetText;else{c=u?.[l]?.conditionNotMetText||u?.en?.conditionNotMetText,c&&s&&(c=n.gfgProgressBar.f.replaceTextVariables(c,i,s,gfg.utility.getCurrencySymbol(),e._id));const t="quantity"!==i.progressType,r=n.gfgProgressBar.f.resolveQualifierValue(s.buyXRulesData?.rulesList?.[0]?.ruleValue,t),o=i.currentValue,a=gfg.utility.getActiveCurrencyRate();let g=Math.max(0,r-o)*(t?a:1);g=parseFloat(g.toFixed(t&&g%1!=0?2:0)),n.utility.changeNumber(g,`animatedNumber-${e._id}`)}c&&setTimeout(()=>{o.innerHTML=c},300)}catch(t){gfg.utility.debugError("Error in updateWidgetHeading",t)}},f:{resolveMarketValue:function(t,e,i=!0){try{const r=gfg.utility.getActiveCurrencyRate(),n=gfg.state.activeCustomerData?.markets?.handle;if(!e||0===e.length)return i?t*r:t;for(const t of e)if(t.handle===n){const e=parseFloat(t.value);if(!e||!Number.isFinite(e))continue;return!0===t.multiCurrency&&i?e*r:e}for(const t of e)if(!0===t.primary){const e=parseFloat(t.value);if(!e||!Number.isFinite(e))continue;return!0===t.multiCurrency&&i?e*r:e}return i?t*r:t}catch(e){gfg.utility.debugError("Error in resolveMarketValue",e);const r=gfg.utility.getActiveCurrencyRate();return i?t*r:t}},getQualifierValue:function(t,e){try{const i=t.ruleValue?.qualifierType;let r=0,o="amount";const a=e.items.filter(e=>n.gfgProgressBar.f.isItemMatchingRule(e,t)),s=gfg.utility.getActiveCurrencyRate();return"overallQty"===i?(o="quantity",r=a.reduce((t,e)=>t+e.quantity,0)):"overallSubtotal"===i?r=a.reduce((t,e)=>t+e.price*e.quantity,0)/(100*s):"overallDiscountedSubtotal"===i&&(r=a.reduce((t,e)=>t+e.discounted_price*e.quantity,0)/(100*s)),{currentValue:r,progressType:o}}catch(t){return gfg.utility.debugError("Error in getQualifierValue",t),0}},calculateProgress:function(t,e){try{const i=t.segmentsData?.segmentsList?.[0];if(!i?.buyXRulesData?.rulesList?.[0])return{currentValue:0,ruleType:"cartSubtotal",cartData:e};const r=i.buyXRulesData.rulesList[0];let o="amount",a=0;const s=gfg.utility.getActiveCurrencyRate(),l=JSON.parse(JSON.stringify(e)),c=l.items.filter(t=>t.properties?._free_product);switch(l.items=l.items.filter(t=>!t.properties?._free_product),c.length>0&&(l.original_total_price-=c.reduce((t,e)=>t+(e.original_line_price||0),0),l.item_count-=c.reduce((t,e)=>t+(e.quantity||0),0)),r?.ruleType){case"cartSubtotal":a=l.original_total_price/(100*s);break;case"discountedCartSubtotal":if(a=l?.items?.reduce((t,e)=>t+(e?.final_line_price||0),0)/(100*s),l?.cart_level_discount_applications?.length>0){a-=l.cart_level_discount_applications.reduce((t,e)=>t+(e?.discount_application?.total_allocated_amount||0),0)/(100*s)}break;case"cartQuantity":a=l.item_count,o="quantity";break;case"products":case"collections":case"productVariants":const t=n.gfgProgressBar.f.getQualifierValue(r,l);a=t.currentValue,o=t.progressType;break;default:a=0}return{currentValue:a,ruleType:r.ruleType,progressType:o,cartData:l}}catch(t){return gfg.utility.debugError("Error in calculateProgress",t),{currentValue:0,progressType:"cartSubtotal",cartData:e}}},isItemMatchingRule:function(t,e){try{let i=!1;const r=e.ruleType,n=e.ruleValue?.value||[],o=t.properties;if(o._free_product)return!1;if("products"===r)i=n.some(e=>t.product_id===e.productId||t.handle===e.handle||t.product_id.toString()===e.productId?.toString());else if("collections"===r){const e=window.Shopify.shop,r=JSON.parse(sessionStorage.getItem(`customFunctionProductData-${e}`));i=n.some(e=>r[t.product_id]?.collections&&r[t.product_id].collections.some(t=>t.id===e.id))}else if("productVariants"===r){i=n.map(t=>t.variants.map(t=>t.variantId)).flat().some(e=>t.variant_id===e||t.variant_id.toString()===e?.toString())}return i}catch(t){return gfg.utility.debugError("Error in isItemMatchingRule",t),!1}},resolveQualifierValue:function(t,e=!0){try{const i=parseFloat(t?.qualifierValue||0),r=t?.marketValues,o=n.gfgProgressBar.f.resolveMarketValue(i,r,e);if(e){return o/gfg.utility.getActiveCurrencyRate()}return o}catch(e){return gfg.utility.debugError("Error in resolveQualifierValue",e),parseFloat(t?.qualifierValue||0)}},checkSegmentAchievement:function(t,e){try{const i=[];let r=null;const o="quantity"!==e.progressType,a=[...t].sort((t,e)=>n.gfgProgressBar.f.resolveQualifierValue(t.buyXRulesData?.rulesList?.[0]?.ruleValue,o)-n.gfgProgressBar.f.resolveQualifierValue(e.buyXRulesData?.rulesList?.[0]?.ruleValue,o));for(let t=0;t=l)i.push({...s,index:t,isAchieved:!0,segmentQualifyValue:l});else if(!r&&i.length!==a.length){const i=t>0?n.gfgProgressBar.f.resolveQualifierValue(a[t-1]?.buyXRulesData?.rulesList?.[0]?.ruleValue,o):0,c=Math.min((e.currentValue-i)/(l-i)*100,100);r={...s,index:t,isAchieved:!1,segmentQualifyValue:l,progress:c};break}}return{achievedSegments:i,nextSegment:r,allSegmentsAchieved:i.length===a.length}}catch(t){return gfg.utility.debugError("Error in checkSegmentAchievement",t),{achievedSegments:[],nextSegment:null,allSegmentsAchieved:!1}}},checkIfFreeGiftIsUnlocked:async function(t,e,r){try{const o=gfg.settings.consolidatedCombinedDiscount.find(e=>e._id===t);if(!o)return!1;if(!await i.checkRulesToHandleWidgetVisibility(o))return!1;const a=o.segmentsData?.segmentsList||[],s=n.gfgProgressBar.f.calculateProgress(o,r),l=n.gfgProgressBar.f.checkSegmentAchievement(a,s);if(o?.advancedSettings?.addHighestTierGift){let t=null;const e=l.achievedSegments.filter(t=>"FREE_GIFT"===t.goalType);e.length>0&&(t=e.reduce((t,e)=>null===t||(e.priority||0)>(t.priority||0)?e:t,null)),t&&(l.achievedSegments=[t])}for(let t of l.achievedSegments)if(t.goalId===e)return!0;return!1}catch(t){return gfg.utility.debugError("Error in checkIfFreeGiftIsUnlocked",t),!1}},prepareProgressBarUI:function(t,e,i){try{const{widgetSettings:r}=t,o=t.segmentsData?.segmentsList||[],a=n.gfgProgressBar.components.createProgressBarContainer(t,e,r.styles);if(r.heading.isEnabled||1===o.length){const e=n.gfgProgressBar.f.prepareHeading(t,i);a.appendChild(e)}if(1===o.length){const e=n.render.prepareSingleSegmentProgressBar(t,i);a.appendChild(e)}else{const e=n.render.prepareMultipleSegmentsProgressBar(t,i);a.appendChild(e)}return a}catch(t){gfg.utility.debugError("Error in prepareProgressBarUI",t)}},prepareHeading:function(t,e){try{const i=t.widgetSettings.heading,o=t.widgetSettings.styles,a=gfg.utility.getCurrencySymbol(),s=gfg.utility.getLocale()||"en",l=t.segmentsData?.segmentsList||[],c=n.gfgProgressBar.f.checkSegmentAchievement(l,e);let u;c.allSegmentsAchieved?u=i.title[s]?.conditionMetText||i.title.en.conditionMetText:(u=i.title[s]?.conditionNotMetText||i.title.en.conditionNotMetText,u=n.gfgProgressBar.f.replaceTextVariables(u,e,c.nextSegment,a,t._id));const g=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarHeadingText",innerHTML:u,style:`\n font-size: ${o.headingSize||"14px"};\n `}),d=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarHeadingContainer"});let f=t.widgetSettings.heading.iconUrl,p=null;const y={UNIFIED_WIDGET_DISCOUNT_ICON:SVG_ICONS.DISCOUNT_ICON,UNIFIED_WIDGET_FREE_GIFT_ICON:SVG_ICONS.GIFT_ICON,UNIFIED_WIDGET_SHIPPING_DISCOUNT_ICON:SVG_ICONS.SHIPPING_ICON};if(y[f]){p=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarHeadingIcon",innerHTML:y[f],style:`\n --icon-color: ${o.iconColor||"#000000"};\n display: flex;\n align-items: center;\n justify-content: center;\n --icon-size: ${o.iconSize||"16px"};\n `})}else f&&(p=r.utility.createElementWithAttributes("img",{src:f,class:"gfgCCDProgressBarHeadingIcon",alt:"heading icon",style:`\n --icon-size: ${o.iconSize||"16px"};\n `}));return p&&d.appendChild(p),d.appendChild(g),d}catch(t){gfg.utility.debugError("Error in prepareHeading",t)}},replaceTextVariables:function(t,e,i,r,o){try{if(!t||!i)return t;const a=gfg.utility.getLocale()||"en",s=gfg.utility.getActiveCurrencyRate(),l="quantity"!==e.progressType,c=i.buyXRulesData?.rulesList?.[0]?.ruleValue,u=n.gfgProgressBar.f.resolveQualifierValue(c,l),g=e.currentValue;let d=Math.max(0,u-g)*(l?s:1);d=d.toFixed(l&&d%1!=0?2:0);const f=parseFloat(i.discountValue||0),p=i.discountMarketValues,y="FIXED"===i.discountType||"FIXED_PRICE"===i.discountType;let h=n.gfgProgressBar.f.resolveMarketValue(f,p,y);h=parseFloat(parseFloat(h).toFixed(h%1==0?0:2));const m=parseFloat(c?.qualifierValue||0);let C=l?n.gfgProgressBar.f.resolveMarketValue(m,c?.marketValues,!0):m;C=parseFloat(C).toFixed(C%1==0?0:2);let b=t;if(b=b.replace(/{{CURRENCY}}/g,r),b=b.replace(/{{DISCOUNT_VALUE}}/g,h),b=b.replace(/{{MIN_AMOUNT}}/g,C),o){let t=i.widgetSettings?.ruleText,s=t?.[a]?.conditionMetText||t?.en?.conditionMetText||"next goal";s=n.gfgProgressBar.f.replaceTextVariables(s,e,i,r),b=b.replace(/{{NEXT_TIER_TITLE}}/g,s),b=b.replace(/{{REMAINING_AMOUNT}}/g,`${d}`)}return b}catch(e){return gfg.utility.debugError("Error in replaceTextVariables",e),t}},removeWidgetIfAlreadyExists:function(t,e){try{const i=document.getElementById(`${t.title}_${e}`);i&&i.remove()}catch(t){gfg.utility.debugError("Error in removeWidgetIfAlreadyExists",t)}},prepareSegmentItem:function(t,e,i,o){try{const a=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarSegmentItem"}),s=n.gfgProgressBar.components.createProgressBar(t,e,i,o),l=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarCheckmark",innerHTML:100===t?SVG_ICONS.CHECK_MARK_ICON:"",style:`\n --bar-fill-color: ${e.barFillColor||"#000000"};\n border: 2px solid ${100===t?e.barFillColor||"#000000":e.barEmptyColor||"#CCCCCC"};\n `});return a.appendChild(s),a.appendChild(l),a}catch(t){gfg.utility.debugError("Error in prepareSegmentItem",t)}}}},gfgDynamicBogo:{init:async function(t,e){try{const i=r.gfgBXGY.state.animatingDiscounts,o=t.every(t=>i.has(t.title));if(r.gfgBXGY._trace("dynamicBogo:init",{pageType:e,titles:t.map(t=>t.title),allAnimating:o}),o&&t.length>0)return gfg.utility.debugConsole("[DynamicBogo] SKIP init: all discounts animating"),void r.gfgBXGY._trace("dynamicBogo:skip:allAnimating",{pageType:e});const a=t.filter(t=>!i.has(t.title));let s=!0;const l=[];for(const t of a){const i=`${t.title}_${e}`,n=r.gfgBXGY.state.containerRefs[i];if(n&&n.isConnected)l.push({title:t.title,source:"containerRef",refConnected:!0});else{const n=document.getElementById(`${t.title}_${e}`)||(gfg.state.shadowRoot.isDetected?gfg.state.shadowRoot.reference.querySelector(`[id="${t.title}_${e}"]`):null);if(!n){l.push({title:t.title,source:"missing",refConnected:!1}),s=!1;break}r.gfgBXGY.state.containerRefs[i]=n,l.push({title:t.title,source:"domLookup",refConnected:!1})}}if(s&&a.length>0){const t=await gfg.utility.getCartV2(),i=a.map(t=>n.gfgDynamicBogo.f.convertCCDSchemaToDynamicBogoSchema(t));r.gfgBXGY._trace("dynamicBogo:branch:inPlaceUpdate",{pageType:e,existence:l,titles:i.map(t=>t.title)});for(const n of i){await r.gfgBXGY.computeWidgetState(n,t);await r.gfgBXGY.f.checkIfWidgetShouldBeVisible(n,e)?await r.gfgBXGY.f.updateBXGYWidgetState(n._id):r.gfgBXGY.f.removeWidgetIfAlreadyExists(n,e)}return}r.gfgBXGY._trace("dynamicBogo:branch:prepareAndInsert",{pageType:e,existence:l});const c=await n.gfgDynamicBogo.f.preapreUIFromConsolidatedDynamicBogoUI(t,e);r.f.insertIntoPageWrapper(c,e,"CUSTOM_DISCOUNT");for(const i of t){const t=`${i.title}_${e}`,n=document.getElementById(`${i.title}_${e}`)||(gfg.state.shadowRoot.isDetected?gfg.state.shadowRoot.reference.querySelector(`[id="${i.title}_${e}"]`):null);n&&(r.gfgBXGY.state.containerRefs[t]=n)}}catch(t){gfg.utility.debugConsole("Error inside gfgConsolidatedCustomDiscount gfgDynamicBogo init fn",t)}},f:{preapreUIFromConsolidatedDynamicBogoUI:async function(t,e){try{const i=[],o=t.map(t=>n.gfgDynamicBogo.f.convertCCDSchemaToDynamicBogoSchema(t));let a=await gfg.utility.getCartV2();for(let t of o){await r.gfgBXGY.computeWidgetState(t,a),await(r?.gfgBXGY?.f?.getDiscountEligibleProducts(t));const n=await r.gfgBXGY.f.checkIfWidgetShouldBeVisible(t,e);if(r.gfgBXGY._trace("dynamicBogo:prepare:visibility",{title:t.title,pageType:e,shouldRenderWidget:n}),!n){r.gfgBXGY.f.removeWidgetIfAlreadyExists(t,e);continue}const o=await r.gfgBXGY.f.checkIfGetYProductsCanBeAddedToCart(t);t.isBuyXGetYWidgetDisabled=o,await r.gfgBXGY.f.getWidgetAddedVariantsFromCart(t.title,a);let s=r.gfgBXGY.f.prepareUI(t,e);i.push({generatedUI:s,offer:t})}return r.gfgBXGY._trace("dynamicBogo:prepare:done",{pageType:e,preparedCount:i.length}),i}catch(t){gfg.utility.debugError("Error inside gfgConsolidatedCustomDiscount preapreUIFromConsolidatedDynamicBogoUI fn",t)}},convertCCDSchemaToDynamicBogoSchema:function(t){try{return{_id:t._id,title:t.title,discountFunctionType:"BUYX_GETY_DISCOUNT",rulesData:t.discountTriggeredRulesData,discountTriggeredRulesData:t.discountTriggeredRulesData,customerEligibilityRules:t.customerEligibilityRules,discountSettings:{discountId:t.discountId,type:t.segmentsData.segmentsList[0].discountType,value:t.segmentsData.segmentsList[0].discountValue,mode:t.mode,combinesWithOrderDiscounts:t.combinesWithOrderDiscounts,combinesWithProductDiscounts:t.combinesWithProductDiscounts,combinesWithShippingDiscounts:t.combinesWithShippingDiscounts,rulesData:{rulesGlobalOperator:"OR",rulesGlobalList:t.segmentsData.segmentsList.map(t=>{const e=t.buyXRulesData.rulesList.find(t=>"productHasSubscription"===t.ruleType),i=t.buyXRulesData.rulesList.find(t=>"productHasSubscription"!==t.ruleType)||t.buyXRulesData.rulesList[0],r=e?"exclude"===e.ruleValue.operatorType?"EXCLUDE_SUBSCRIPTION_PRODUCTS":"INCLUDE_ONLY_SUBSCRIPTION_PRODUCTS":"ALL_PRODUCTS";return{rulesOperator:"OR",discountApplicationStrategy:t.discountApplicationStrategy,rulesList:[{purchaseTypeEligibility:r,buyXRule:{type:"DISCOUNT_BXGY",ruleType:i.ruleType,ruleValue:n.gfgDynamicBogo.f.getRuleValueWithSpecificKey(i.ruleValue,i.ruleType),itemCount:t.buyXRulesData.itemCount,ruleId:"selectRule-0-forY-0-buyXRule"},getYRule:{type:"DISCOUNT_BXGY",ruleType:t.getYRulesData.rulesList[0].ruleType,ruleValue:n.gfgDynamicBogo.f.getRuleValueWithSpecificKey(t.getYRulesData.rulesList[0].ruleValue,t.getYRulesData.rulesList[0].ruleType),itemCount:t.getYRulesData.itemCount,ruleId:"selectRule-0-forY-0-getYRule"},discountValue:t.discountValue,message:t.message,maxDiscountableSets:t.discountableSetLimit,appliesToEachItem:t.appliesToEachItem,sortBasedOn:t.sortBasedOn,sortByOrder:t.sortByOrder}]}})}},isCampaignUrlEnabled:t.isCampaignUrlEnabled,isTestMode:t.isTestMode,urlBasedCampaign:t.urlBasedCampaign,isEnabled:t.isEnabled,campaignScheduleData:t.campaignScheduleData,widgetSettings:t.widgetSettings}}catch(t){gfg.utility.debugError("Error inside gfgConsolidatedCustomDiscount convertCCDSchemaToDynamicBogoSchema fn",t)}},getRuleValueWithSpecificKey:function(t,e){let i;switch(e){case"products":case"productVariants":i="products";break;case"collections":i="collections";break;case"productTags":i="tags";break;case"productTypes":i="types"}return i&&(t[i]=t.value),t}}},utility:{changeNumber:function(t,e){const i=document.getElementById(e);if(!i)return;const r=parseFloat(i.textContent),n=parseFloat(t);if(r===n)return;const o=performance.now(),a=t=>{const e=t-o,s=Math.min(e/300,1),l=r+(n-r)*s;i.textContent=l.toFixed(2),s<1&&requestAnimationFrame(a)};requestAnimationFrame(a)}},render:{prepareMultipleSegmentsProgressBar:function(t){try{const{widgetSettings:e}=t,i=e.styles,o=t.segmentsData?.segmentsList||[];let a=0;const s=n.gfgProgressBar.state.cartData;if(!s)return null;const l=n.gfgProgressBar.f.calculateProgress(t,s),c=n.gfgProgressBar.f.checkSegmentAchievement(o,l),u=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarContainer",style:`\n display: grid;\n grid-template-columns: 1fr ${Array(o.length-1).fill("2fr").join(" ")} 1fr;\n `}),g=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarSegmentTextContainer",style:`\n display: grid;\n grid-template-columns: repeat(${o.length}, 1fr);\n gap: 5px;\n `}),d="quantity"!==l.progressType,f=[...o].sort((t,e)=>n.gfgProgressBar.f.resolveQualifierValue(t.buyXRulesData?.rulesList?.[0]?.ruleValue,d)-n.gfgProgressBar.f.resolveQualifierValue(e.buyXRulesData?.rulesList?.[0]?.ruleValue,d));let p=!0;f.forEach((t,e)=>{const r=n.gfgProgressBar.f.resolveQualifierValue(t.buyXRulesData?.rulesList?.[0]?.ruleValue,d),o=c.achievedSegments.some(t=>n.gfgProgressBar.f.resolveQualifierValue(t.buyXRulesData?.rulesList?.[0]?.ruleValue,d)===r),s=e>0?n.gfgProgressBar.f.resolveQualifierValue(f[e-1]?.buyXRulesData?.rulesList?.[0]?.ruleValue,d):0,y=Math.min((l.currentValue-s)/(r-s)*100,100);let h=0===e?"first":"middle";const m=n.gfgProgressBar.f.prepareSegmentItem(y,i,h,p);u.appendChild(m),a+=y;const C=n.gfgProgressBar.components.createSegmentText(t,l,i);g.appendChild(C),o||(p=!1)});const y=n.gfgProgressBar.components.createProgressBar(100,i,"last",p);u.appendChild(y);const h=r.utility.createElementWithAttributes("div",{class:"gfgProgressBarSegmentsContainer","data-totalprogress":a});return h.appendChild(u),h.appendChild(g),h}catch(t){gfg.utility.debugError("Error inside gfgConsolidatedCustomDiscount render prepareProgressBar fn",t)}},prepareSingleSegmentProgressBar:function(t){try{const{widgetSettings:e}=t,i=e.styles,o=(t.segmentsData?.segmentsList||[])[0],a=n.gfgProgressBar.state.cartData;if(!a)return null;const s=n.gfgProgressBar.f.calculateProgress(t,a),l="quantity"!==s.progressType,c=n.gfgProgressBar.f.resolveQualifierValue(o.buyXRulesData?.rulesList?.[0]?.ruleValue,l),u=s.currentValue,g=Math.min(u/c*100,100),d=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarSingleSegmentContainer"}),f=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarSegmentItem"}),p=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarWrapper",style:`\n border-radius: ${i.borderRadius||"10px"};\n background: ${i.barEmptyColor||"#e0e0e0"};\n `}),y=r.utility.createElementWithAttributes("div",{class:"gfgCCDProgressBarFill",style:`\n background: ${i.barFillColor||"#d91717"};\n width: ${g}%;\n `}),h=0===g?"0px":`calc(${g}% - 9px)`,m=r.utility.createElementWithAttributes("div",{class:"gfgCCDSingleProgressBarIndicator",style:`\n left: ${h};\n background-color: ${i.barFillColor||"#d91717"};\n `});if(p.appendChild(y),p.appendChild(m),f.appendChild(p),d.appendChild(f),o.widgetSettings?.segmentLink&&o.widgetSettings?.segmentLinkText){const t=r.utility.createElementWithAttributes("a",{class:"gfgCCDProgressBarSegmentLink",href:o.widgetSettings.segmentLink,innerText:o.widgetSettings.segmentLinkText,target:"_blank",style:`\n color: ${i.textColor||"#3c3c3c"};\n `});d.appendChild(t)}return d}catch(t){gfg.utility.debugError("Error inside gfgConsolidatedCustomDiscount render prepareSingleCheckpointProgressBar fn",t)}}},action:{},event:{}};const o={_config:{DEBOUNCE_MS:150,MAX_CONVERGENCE_RETRIES:2,CART_ATTRIBUTE_KEY:"_kite_ccdData"},_state:{isRunning:!1,hasPendingSignal:!1,isInitialized:!1,debounceTimer:null,discountedSubtotalResults:null},_checkIfDiscountedSubtotalRulesIsPresent(t){try{const e={cartDiscounts:!1,productDiscounts:!1};for(const i of t){const t=gfg.utility.getCampaignScheduleStatus(i.campaignScheduleData).expired,r=i.advancedSettings?.onlyUseWidget;if(!t&&!r){if(e.cartDiscounts&&e.productDiscounts)break;i.discountTriggeredRulesData.rulesGlobalList[0].rulesList.forEach(t=>{"discountedCartSubtotal"===t.ruleType&&(e.cartDiscounts=!0),"products"!==t.ruleType&&"productsVariant"!==t.ruleType&&"collections"!==t.ruleType||"overallDiscountedSubtotal"!==t.ruleValue.qualifierType||(e.productDiscounts=!0)}),i.segmentsData.segmentsList.forEach(t=>{t.buyXRulesData?.rulesList&&t.buyXRulesData.rulesList.forEach(t=>{"discountedCartSubtotal"===t.ruleType&&(e.cartDiscounts=!0),"products"!==t.ruleType&&"productsVariant"!==t.ruleType&&"collections"!==t.ruleType||"overallDiscountedSubtotal"!==t.ruleValue.qualifierType||(e.productDiscounts=!0)})})}}return e}catch(t){gfg.utility.debugError("[AllocSync] Error in _checkIfDiscountedSubtotalRulesIsPresent",t)}},_areAllocationsEqual(t,e){try{const i=t=>{if(null==t)return"null";if("object"!=typeof t)return String(t);const e={};for(const r of Object.keys(t).sort())e[r]="object"==typeof t[r]&&null!==t[r]?JSON.parse(i(t[r])):t[r];return JSON.stringify(e)};return i(t)===i(e)}catch(t){return gfg.utility.debugError("[AllocSync] Error in _areAllocationsEqual",t),!1}},configure(t){try{if(this._state.isInitialized)return;const e=this._checkIfDiscountedSubtotalRulesIsPresent(t);if(!e||Object.values(e).every(t=>!1===t))return void gfg.utility.debugConsole("[AllocSync] No discountedSubtotal rules found, module not needed");this._state.discountedSubtotalResults=e,this._state.isInitialized=!0,gfg.utility.debugConsole("[AllocSync] Module configured",e),this._processSync()}catch(t){gfg.utility.debugError("[AllocSync] Error in configure",t)}},onCartChange(){this._state.isInitialized&&(clearTimeout(this._state.debounceTimer),this._state.debounceTimer=setTimeout(()=>{this._processSync()},this._config.DEBOUNCE_MS))},async _processSync(){try{if(this._state.isRunning)return this._state.hasPendingSignal=!0,void gfg.utility.debugConsole("[AllocSync] Sync already running, queued pending signal");this._state.isRunning=!0,this._state.hasPendingSignal=!1,await this._runSyncCycle(),this._state.isRunning=!1,this._state.hasPendingSignal&&(this._state.hasPendingSignal=!1,gfg.utility.debugConsole("[AllocSync] Processing pending signal"),this._processSync())}catch(t){this._state.isRunning=!1,gfg.utility.debugError("[AllocSync] Error in _processSync",t)}},async _runSyncCycle(){try{const{MAX_CONVERGENCE_RETRIES:t,CART_ATTRIBUTE_KEY:e}=this._config,i=this._state.discountedSubtotalResults;let o=0,a=await gfg.utility.getCartV2({forceRefresh:!0});for(;o<=t;){const s=r.gfgCustomDiscountFunctionLogicHandlers.getExistingCartAttributes(a,e),l=n.f.getDiscountAllocations(a,i),c=s?.discountAllocations||{};if(this._areAllocationsEqual(c,l)){gfg.utility.debugConsole("[AllocSync] Allocations match, converged after",o,"update(s)");break}gfg.utility.debugConsole("[AllocSync] Allocations differ, updating attribute (attempt "+(o+1)+")");const u={...s,discountAllocations:l},g=Object.keys(u).length>0?JSON.stringify(u):"";if(await gfg.utility.updateCart({attributes:{[e]:g||""}}),o++,o>t){gfg.utility.debugConsole("[AllocSync] Max convergence retries reached, stopping");break}a=await gfg.utility.getCartV2({forceRefresh:!0})}}catch(t){gfg.utility.debugError("[AllocSync] Error in _runSyncCycle",t)}}},a={state:{selectedTierIdx:0,discount:null,storefrontConfig:null,productData:null,currentVariantId:null,cartData:null,debugTrace:[],_variantPoll:null,isAddToCartButtonOverwrite:!1,addToCartClicked:!1,_hiddenQtyNodes:[],_origQtyValues:[],_atcHandler:null,_atcBtn:null,_atcOrigType:null},_trace:function(t,e){gfg.utility.debugTrace("VolV2-TRACE",a.state.debugTrace,t,e)},constants:{PREFIX:"gfgVDv2",CSS_VAR_PREFIX:"--gfg-vd",RADIUS_PRESETS:{sharp:"0px",soft:"6px",round:"16px"},VOLUME_DEFAULTS:{radioButton:{activeTierBg:"#FFFFFF",activeTierBorder:"#0F0F0F",defaultTierBg:"#FFFFFF",defaultTierBorder:"#D0D0D0",activeColor:"#0F0F0F",pillBg:"#199800",pillText:"#FFFFFF",tierLabelColor:"#0F0F0F",priceColor:"#0F0F0F",strikeThroughPriceColor:"#868686",tierLabelFontSize:"15px",tierLabelFontWeight:"medium",priceFontSize:"15px",priceFontWeight:"bold",strikeThroughPriceFontSize:"15px",strikeThroughPriceFontWeight:"medium",pillTextFontSize:"12px",pillTextFontWeight:"bold"},table:{tierLabelColor:"#0F0F0F",discountColor:"#199800",tableBg:"#FFFFFF",tableBorder:"#D0D0D0",tierLabelFontSize:"15px",tierLabelFontWeight:"medium",discountFontSize:"15px",discountFontWeight:"bold"}},FONT_WEIGHT_MAP:{thin:100,light:300,regular:400,normal:400,medium:500,semibold:600,bold:700,extrabold:800,black:900}},init:async function(t,e){try{if(e&&"PRODUCT_PAGE"!==e)return;if(gfg?.f?.getPageType&&"product"!==gfg.f.getPageType())return;a._trace("init:start",{pageType:e});const i=t&&t.consolidatedCustomDiscount||gfg?.settings?.consolidatedCustomDiscount||[],r=i.filter(t=>t?.isEnabled&&"CONSOLIDATED_TIERED_DISCOUNT_V2"===t?.discountFunctionType&&gfg.utility.checkForActiveCampaign(t));if(0===r.length)return void a._trace("init:skip",{reason:"no-active-volume-discount",sourceCount:i.length});a.f.injectCss(),a.actions.registerGlobalListener();const n=window?.shopifyLiquidValuesApp7Ext?.product?.handle;n&&gfg?.utility?.getProductDataV2&&(a.state.productData=await gfg.utility.getProductDataV2(n)),a.state.currentVariantId=a.f.getSelectedVariant();try{a.state.cartData=gfg.state&&gfg.state.cartData||(gfg.utility.getCartV2?await gfg.utility.getCartV2():null)}catch(t){a.state.cartData=gfg.state&&gfg.state.cartData||null}const o=r.find(a.f.discountNeedsCartProductData);o&&await a.f.enrichCartIfNeeded(o);const s=r.map(t=>({discount:t,widget:(t.widgets||[]).find(a.f.isProductPageWidget)})).filter(t=>t.widget);if(0===s.length)return void a._trace("init:skip",{reason:"no-widget"});const l=a.f.buildRuleContext(),c=(s.find(t=>gfg.ruleEngine.evaluateWidgetVisibility(t.discount,t.widget,l).shouldRender)||s[0]).discount;a.state.discount=c,a.state.storefrontConfig=c.storefrontConfig||{},a.state.selectedTierIdx=-1,a.f.rerender(),a.f.attachVariantListener()}catch(t){gfg.utility.debugError("error inside gfgVolumeDiscountV2 init",t)}},productPage:{init:function(t){return a.init(t,"PRODUCT_PAGE")}},onCartChange:async function(t){try{if(gfg?.f?.getPageType&&"product"!==gfg.f.getPageType())return;if(a._trace("onCartChange",{cartItemCount:t&&t.item_count,initialized:!!a.state.discount}),!a.state.discount)return a.init(gfg.settings,"PRODUCT_PAGE");a.state.cartData=t||gfg.state&&gfg.state.cartData||a.state.cartData,await a.f.enrichCartIfNeeded(a.state.discount),a.f.rerender(),a.state.selectedTierIdx>=0&&document.querySelector(`.${a.constants.PREFIX}-root`)&&a.f.syncQuantitySelector(a.f.getCurrentQuantitySelection())}catch(t){gfg.utility.debugError("error in gfgVolumeDiscountV2 onCartChange",t)}},f:{isProductPageWidget:function(t){return!(!t||"PRODUCT_PAGE"!==t.placement||!1===t.enabled||t.type&&"volumeTiers"!==t.type||t.scope&&"native"!==t.scope)},discountNeedsCartProductData:function(t){try{const e=t&&t.discountTriggeredRulesData&&t.discountTriggeredRulesData.rulesGlobalList||[],i=["collections","productTags","productTypes"];return e.some(function(t){return(t&&t.rulesList||[]).some(function(t){return i.indexOf(t&&t.ruleType)>=0})})}catch(t){return!1}},enrichCartIfNeeded:async function(t){try{const e=a.state.cartData;if(!e||!e.items||!e.items.length)return;if(!a.f.discountNeedsCartProductData(t))return;const i=gfg.customDiscountValidationFunctions;i&&i.getLatestCartItemsProductData&&await i.getLatestCartItemsProductData(e)}catch(t){gfg.utility.debugError("error in gfgVolumeDiscountV2 enrichCartIfNeeded",t)}},buildRuleContext:function(){return{product:gfg.ruleEngine.getPdpProductContext(a.state.productData,a.state.currentVariantId),cart:a.state.cartData}},shouldRenderWidget:function(t,e){try{if(!gfg.ruleEngine)return!0;const i=a.f.buildRuleContext(),r=gfg.ruleEngine.evaluateWidgetVisibility(t,e,i);return a._trace(r.shouldRender?"visibility:PASS":"visibility:FAIL",{shouldRender:r.shouldRender,failedAt:r.reason,checkpoints:r.checkpoints,context:{productId:i.product&&i.product.id,variantId:i.product&&i.product.selected_variant&&i.product.selected_variant.id,collections:(i.product&&i.product.collections||[]).map(function(t){return t.id}),tags:i.product&&i.product.tags,type:i.product&&i.product.type,cartItemCount:i.cart&&i.cart.item_count,cartSubtotal:i.cart&&i.cart.items_subtotal_price}}),r.shouldRender}catch(t){return gfg.utility.debugError("error in gfgVolumeDiscountV2 shouldRenderWidget",t),!0}},getSelectedVariant:function(){try{if("product"!==gfg?.state?.page_type)return;const t=gfg?.settings?.app?.activeVariantCodes||"";if(t.indexOf("1")>=0){const t=Object.fromEntries(new URLSearchParams(location.search));if(t&&t.variant)return t.variant}if(t.indexOf("2")>=0){const t=window?.ShopifyAnalytics?.meta;if(t?.selectedVariantId){const e=t?.product?.variants||[];for(let i=0;i=0&&window?.shopifyLiquidValuesApp7Ext?.selected_or_first_available_variant)return shopifyLiquidValuesApp7Ext.selected_or_first_available_variant.id;if(t.indexOf("3")>=0){const t=document.querySelector('[name="id"]');if(t?.value)return t.value}return}catch(t){return void gfg.utility.debugError("error in gfgVolumeDiscountV2 getSelectedVariant",t)}},getCurrentVariantPrice:function(){const t=a.state.productData;if(!t||!t.variants||!t.variants.length)return 0;const e=a.state.currentVariantId;let i=null;if(null!=e){const r=String(e).split("/").pop();i=t.variants.find(t=>String(t.id)===String(e)||String(t.id)===r)}return i||(i=t.variants[0]),i?Number(i.price)/100:0},syncQuantitySelector:function(t){try{const e=Math.max(1,Math.round(Number(t)||0)),i=gfg.elements&&gfg.elements.quantityBtn,r="undefined"!=typeof DEFAULT_sideCartSelectorsApp7Ext?DEFAULT_sideCartSelectorsApp7Ext:"#CartDrawer, .drawer, .cart-drawer, .cart-notification, .Drawer",n=function(t){return t&&(t.closest(r)||t.closest(".gfgCartPageWrapperV2"))};a.f.restoreQuantitySelector();let o=!1;i&&document.querySelectorAll(i).forEach(function(t){if(n(t))return;const i=t.tagName&&"input"===t.tagName.toLowerCase()?t:t.querySelector('input[name="quantity"]')||t.querySelector('input[type="number"]')||t.querySelector("input");if(!i||"input"!==i.tagName.toLowerCase()||n(i))return;const r=(i.getAttribute("name")||"").toLowerCase();""!==r&&"quantity"!==r||(t.classList.contains("gfgHide")||(t.classList.add("gfgHide"),a.state._hiddenQtyNodes.push(t)),a.state._origQtyValues.some(function(t){return t.input===i})||a.state._origQtyValues.push({input:i,value:i.value,hadAttr:i.hasAttribute("value"),attr:i.getAttribute("value")}),i.value=String(e),i.setAttribute("value",String(e)),o=!0)}),o?a.state.isAddToCartButtonOverwrite&&a.f.restoreAddToCartButton():a.f.addToCartButtonOverwrite()}catch(t){gfg.utility.debugError("error in gfgVolumeDiscountV2 syncQuantitySelector",t)}},getCurrentQuantitySelection:function(){const t=a.state.selectedTierIdx,e=(a.state.discount?.segmentsData?.segmentsList||[])[t];return e?a.f.getTierQuantity(e):1},readQuantityInput:function(){try{const t=gfg.elements&&gfg.elements.quantityBtn;if(!t)return null;const e="undefined"!=typeof DEFAULT_sideCartSelectorsApp7Ext?DEFAULT_sideCartSelectorsApp7Ext:"#CartDrawer, .drawer, .cart-drawer, .cart-notification, .Drawer",i=function(t){return t&&(t.closest(e)||t.closest(".gfgCartPageWrapperV2"))},r=document.querySelectorAll(t);for(let t=0;tNumber(e.discountValue))&&(e=i)}return e?a.f.formatDiscountValueToken(e):""},getTierQuantity:function(t){const e=a.state.discount?.segmentsData?.tiersAreBasedOn||"cartQuantity";if("cartSubtotal"===e||"subtotalOfEachSelectedProduct"===e||"subtotalOfAllSelectedProducts"===e)return 1;const i="cartQuantity"===e||"cartSubtotal"===e,r=((i?t?.buyXRulesData:t?.getYRulesData)?.rulesList?.[0]||{}).ruleValue||{},n=Math.round(Number(gfg.ruleEngine._resolveMarketValue(r,!1))||0);return n>0?n:1},computeTierPricing:function(t,e){const i=t?.discountType,r=a.f.resolveDiscountValue(t),n=a.f.getTierQuantity(t),o=Math.round(100*(Number(e)||0)),s=o*n,l={PERCENTAGE:function(t){return t-Math.floor(t*Math.max(0,Math.min(100,r))/100)},FIXED:function(t){return t-Math.min(t,Math.round(100*r))},FIXED_PRICE:function(t){return Math.min(t,Math.max(0,Math.round(100*r)))}}[i];let c=s;return l&&(c="PERCENTAGE"===i||!0===t?.appliesToEachItem?l(o)*n:l(s)),c=Math.max(0,Math.min(c,s)),{qty:n,originalTotal:s/100,discountedTotal:c/100,offAmount:(s-c)/100}},resolveStyle:function(t,e){const i=e?.widgetTypeDesign?.[t.type]?.style||{},r=e?.theme||{},n=a.constants.VOLUME_DEFAULTS[t.subtype]||{},o=e=>Object.assign({},r.typography?.[e]||{},i.typography?.[e]||{},t.style?.typography?.[e]||{});return{colors:(s="colors",Object.assign({},n[s]||{},r[s]||{},i[s]||{},t.style?.[s]||{})),typography:{heading:o("heading"),body:o("body")},spacing:Object.assign({},r.spacing||{},i.spacing||{},t.style?.spacing||{}),typeSpecific:Object.assign({},n,i.typeSpecific||{},t.style?.typeSpecific||{})};var s},resolveRadiusPx:function(t){const e=a.constants.RADIUS_PRESETS;return e[t]||e.soft},fontWeightValue:function(t){return"number"==typeof t?t:a.constants.FONT_WEIGHT_MAP[String(t||"").toLowerCase()]||400},computePillText:function(t,e){if(e&&String(e).trim())return a.f.resolveText(String(e),t);const i=t.discountType;if("PERCENTAGE"===i)return`${t.discountValue}% Off`;const r=gfg.utility.getCurrencySymbol&&gfg.utility.getCurrencySymbol()||"",n=a.f.formatNumber(a.f.resolveDiscountValue(t));return"FIXED"===i?`${r}${n} Off`:"FIXED_PRICE"===i?`${r}${n}`:`${t.discountValue} Off`},buildSegmentVariableValues:function(t){const e=gfg.utility.getCurrencySymbol&&gfg.utility.getCurrencySymbol()||"",i=a.state.discount?.segmentsData?.tiersAreBasedOn||"cartQuantity",r="cartQuantity"===i||"cartSubtotal"===i,n=(r?t?.buyXRulesData:t?.getYRulesData)?.rulesList?.[0]||{},o=n.ruleValue||{},s=null!=o.qualifierValue||null!=n.qualifierValue,l="overallSubtotal"===o.qualifierType||"individualSubtotal"===o.qualifierType||"cartSubtotal"===i||"subtotalOfEachSelectedProduct"===i||"subtotalOfAllSelectedProducts"===i,c=a.f.formatNumber,u=s?c(gfg.ruleEngine._resolveMarketValue(o,l)):"";return{DISCOUNT_VALUE:a.f.formatDiscountValueToken(t),CURRENCY:e,PRODUCT_QUANTITY:l?"":u,MIN_AMOUNT:l?u:""}},escapeHtml:function(e){return gfg.utility&&gfg.utility.escapeHtml?t(e):String(null==e?"":e).replace(/[&<>"']/g,function(t){return"&"===t?"&":"<"===t?"<":">"===t?">":'"'===t?""":"'"})},normalizeUrl:function(t){const e=String(null==t?"":t).trim();if(!e)return"";const i=e.match(/^([a-z][a-z0-9+.-]*):/i);if(i)return/^(https?|mailto|tel)$/i.test(i[1])?e:"";if(0===e.indexOf("//"))return"https:"+e;if("#"===e.charAt(0)||"?"===e.charAt(0))return e;if("/"===e.charAt(0)){let t="/";try{t=window.Shopify&&window.Shopify.routes&&window.Shopify.routes.root||"/"}catch(t){}return"/"===t||0===e.indexOf(t)?e:t.replace(/\/$/,"")+e}return"https://"+e},resolveText:function(t,e){if(!t)return"";const i=a.constants.PREFIX,r=a.state.discount?.segmentsData?.segmentsList||[],n={DISCOUNT_VALUE:!0,PRODUCT_QUANTITY:!0,MIN_AMOUNT:!0};let o;const s={};let l=String(t).replace(/\{\{([A-Z_]+?)(?:_(\d+))?\}\}/g,(t,i,l)=>{if("MAX_DISCOUNT"===i&&null==l)return a.f.maxDiscountToken(r.length?r:e?[e]:[]);if(null==l){const n=(()=>{if(void 0===o){const t=e||r[0];o=t?a.f.buildSegmentVariableValues(t):null}return o})();return n&&Object.prototype.hasOwnProperty.call(n,i)?n[i]:t}if(!n[i])return t;const c=parseInt(l,10);return c<1||c>r.length?"":(t=>(t in s||(s[t]=a.f.buildSegmentVariableValues(r[t-1])),s[t]))(c)[i]});return l=l.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(t,e,r)=>{const n=a.f.escapeHtml(e),o=a.f.normalizeUrl(r);return o?`${n}`:n}),l},getTierWidgetSettings:function(t,e){const i=Array.isArray(e?.tierSettings)?e.tierSettings:null;if(i&&t?.tierId){const e=i.find(function(e){return e&&e.tierId===t.tierId});if(e)return e}return t?.widgetSettings||{}},getLocaleContent:function(t){if(!t)return{};try{const e=String(gfg.utility.getLocale&&gfg.utility.getLocale()||"en").toLowerCase(),i=e.split("-")[0];return t[e]||t[i]||t.en||t[Object.keys(t)[0]]||{}}catch(e){return gfg.utility.debugError("error in gfgVolumeDiscountV2 getLocaleContent",e),t.en||{}}},createEl:function(t,e={},i=[]){const r=document.createElement(t);for(const[t,i]of Object.entries(e))null!=i&&("class"===t?r.className=i:"style"===t?r.setAttribute("style",i):"innerHTML"===t?r.innerHTML=i:"text"===t?r.textContent=i:"value"===t?r.value=i:"checked"===t?r.checked=!!i:"disabled"===t?i&&(r.disabled=!0):t.startsWith("on")&&"function"==typeof i?r.addEventListener(t.slice(2).toLowerCase(),i):r.setAttribute(t,i));const n=Array.isArray(i)?i:[i];for(const t of n)null!=t&&!1!==t&&("string"==typeof t?r.appendChild(document.createTextNode(t)):r.appendChild(t));return r},applyStyleVars:function(t,e,i){const r=a.constants.CSS_VAR_PREFIX,n=a.f.fontWeightValue,o=(e,i)=>{null!=i&&""!==i&&t.style.setProperty(`${r}-${e}`,i)};o("color-background",e.colors.background),o("color-border",e.colors.border),o("color-text",e.colors.text),o("color-link",e.colors.link),o("font-heading-size",e.typography.heading?.size),o("font-heading-weight",n(e.typography.heading?.weight)),o("font-body-size",e.typography.body?.size),o("font-body-weight",n(e.typography.body?.weight)),o("padding",e.spacing.padding),o("radius",a.f.resolveRadiusPx(e.spacing.radius));const s=e.typeSpecific;"radioButton"===i.subtype?(o("active-tier-bg",s.activeTierBg),o("active-tier-border",s.activeTierBorder),o("default-tier-bg",s.defaultTierBg),o("default-tier-border",s.defaultTierBorder),o("active-color",s.activeColor),o("pill-bg",s.pillBg),o("pill-text",s.pillText),o("tier-label-color",s.tierLabelColor),o("price-color",s.priceColor),o("strike-color",s.strikeThroughPriceColor),o("tier-label-size",s.tierLabelFontSize),o("tier-label-weight",n(s.tierLabelFontWeight)),o("price-size",s.priceFontSize),o("price-weight",n(s.priceFontWeight)),o("strike-size",s.strikeThroughPriceFontSize),o("strike-weight",n(s.strikeThroughPriceFontWeight)),o("pill-text-size",s.pillTextFontSize),o("pill-text-weight",n(s.pillTextFontWeight))):"table"===i.subtype&&(o("tier-label-color",s.tierLabelColor),o("discount-color",s.discountColor),o("table-bg",s.tableBg),o("table-border",s.tableBorder),o("tier-label-size",s.tierLabelFontSize),o("tier-label-weight",n(s.tierLabelFontWeight)),o("discount-size",s.discountFontSize),o("discount-weight",n(s.discountFontWeight)))},getWidgetCss:function(){const t=a.constants.PREFIX,e=a.constants.CSS_VAR_PREFIX;return`\n .${t}-root {\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;\n background: var(${e}-color-background, transparent);\n border: 1px solid var(${e}-color-border, transparent);\n border-radius: var(${e}-radius, 6px);\n padding: var(${e}-padding, 12px);\n color: var(${e}-color-text, #0F0F0F);\n box-sizing: border-box;\n max-width: 560px;\n margin: 0 auto 12px; /* bottom gap so stacked widgets don't touch */\n }\n .${t}-root *, .${t}-root *::before, .${t}-root *::after { box-sizing: border-box; }\n .${t}-root a { color: var(${e}-color-link, #005BD3); text-decoration: none; }\n .${t}-root .${t}-text-link { color: var(${e}-color-link, #005BD3); text-decoration: none; }\n\n .${t}-root .${t}-title-wrapper {\n display: flex; align-items: center; justify-content: center; gap: 16px;\n margin-bottom: 14px;\n }\n .${t}-root .${t}-title-divider {\n display: block;\n flex: 1 1 0%;\n height: 1px;\n background: #E5E5E5;\n }\n .${t}-root .${t}-title {\n font-size: var(${e}-font-heading-size, 14px);\n font-weight: var(${e}-font-heading-weight, 700);\n color: var(${e}-color-text, #0F0F0F);\n white-space: nowrap;\n text-align: center;\n }\n\n .${t}-tier-list { display: flex; flex-direction: column; gap: 12px; }\n\n .${t}-subtype-radioButton .${t}-radio-card {\n display: flex; align-items: center; justify-content: space-between;\n padding: 12px;\n background: var(${e}-default-tier-bg, #FFFFFF);\n border: 1px solid var(${e}-default-tier-border, #D0D0D0);\n border-radius: var(${e}-radius, 6px);\n cursor: pointer;\n /* Active emphasis uses outline (not a thicker border) so the box size\n never changes between states — no layout shift. outline-offset keeps\n the ring flush with the card edge. */\n outline: 0 solid var(${e}-active-tier-border, #0F0F0F);\n outline-offset: -1px;\n }\n .${t}-subtype-radioButton .${t}-radio-card:focus-visible {\n box-shadow: 0 0 0 2px rgba(0,0,0,0.15);\n }\n .${t}-subtype-radioButton .${t}-radio-card.is-active {\n background: var(${e}-active-tier-bg, #FFFFFF);\n border-color: var(${e}-active-tier-border, #0F0F0F);\n outline-width: 2px;\n }\n .${t}-radio-left {\n display: flex; align-items: center; gap: 12px;\n flex: 1; min-width: 0;\n }\n .${t}-radio-input {\n width: 18px; height: 18px; border-radius: 50%;\n border: 2px solid #BFBFBF;\n background: #FFFFFF;\n flex-shrink: 0;\n display: flex; align-items: center; justify-content: center;\n }\n .${t}-radio-card.is-active .${t}-radio-input {\n border-color: var(${e}-active-tier-border, #0F0F0F);\n }\n .${t}-root .${t}-radio-inner {\n display: block;\n width: 10px;\n height: 10px;\n border-radius: 50%;\n background: transparent;\n }\n .${t}-root .${t}-radio-card.is-active .${t}-radio-inner {\n background: var(${e}-active-tier-border, #0F0F0F);\n }\n .${t}-radio-label-wrap {\n display: flex; align-items: center; gap: 10px; flex-wrap: wrap; min-width: 0;\n }\n .${t}-radio-label {\n color: var(${e}-tier-label-color, #0F0F0F);\n font-size: var(${e}-tier-label-size, 15px);\n font-weight: var(${e}-tier-label-weight, 500);\n }\n /* Selected tier uses the typeSpecific.activeColor for its label text. */\n .${t}-radio-card.is-active .${t}-radio-label {\n color: var(${e}-active-color, #0F0F0F);\n }\n .${t}-pill {\n background: var(${e}-pill-bg, #199800);\n color: var(${e}-pill-text, #FFFFFF);\n font-size: var(${e}-pill-text-size, 12px);\n font-weight: var(${e}-pill-text-weight, 700);\n padding: 3px 10px;\n border-radius: 999px;\n white-space: nowrap;\n }\n .${t}-radio-prices { text-align: right; flex-shrink: 0; padding-left: 10px; }\n .${t}-price {\n color: var(${e}-price-color, #0F0F0F);\n font-size: var(${e}-price-size, 15px);\n font-weight: var(${e}-price-weight, 700);\n }\n .${t}-strike-price {\n color: var(${e}-strike-color, #868686);\n font-size: var(${e}-strike-size, 15px);\n font-weight: var(${e}-strike-weight, 500);\n text-decoration: line-through;\n }\n\n /* Table is one continuous bordered box: outer border + radius on the list, rows joined by\n internal dividers (no per-row border/radius and no inter-row gap). */\n .${t}-subtype-table .${t}-tier-list {\n gap: 0;\n border: 1px solid var(${e}-table-border, #D0D0D0);\n border-radius: var(${e}-radius, 6px);\n overflow: hidden;\n background: var(${e}-table-bg, #FFFFFF);\n }\n .${t}-subtype-table .${t}-table-row {\n display: grid;\n grid-template-columns: 3fr 1.2fr;\n border-bottom: 1px solid var(${e}-table-border, #D0D0D0);\n }\n .${t}-subtype-table .${t}-table-row:last-child { border-bottom: none; }\n .${t}-table-label, .${t}-table-discount { padding: 12px; min-width: 0; }\n .${t}-table-label {\n color: var(${e}-tier-label-color, #0F0F0F);\n font-size: var(${e}-tier-label-size, 15px);\n font-weight: var(${e}-tier-label-weight, 500);\n border-right: 1px solid var(${e}-table-border, #D0D0D0);\n display: flex;\n align-items: center;\n }\n .${t}-table-discount {\n color: var(${e}-discount-color, #199800);\n font-size: var(${e}-discount-size, 15px);\n font-weight: var(${e}-discount-weight, 700);\n display: flex;\n align-items: center;\n justify-content: center;\n text-align: center;\n }\n `},injectCss:function(){const t=a.constants.PREFIX;if(document.getElementById(`${t}-style`))return;const e=document.createElement("style");e.id=`${t}-style`,e.textContent=a.f.getWidgetCss(),document.head.appendChild(e)},rerender:function(){try{const t=a.state.discount;if(!t)return;const e=(t.widgets||[]).find(a.f.isProductPageWidget)||t.widgets?.[0];if(!e)return;if(!a.f.shouldRenderWidget(t,e))return a.f.clearWidget(),void a._trace("rerender:hidden",{discountTitle:t.title});const i=a.render.widget(t,e,a.state.storefrontConfig);a.f.insertIntoPageWrapper([{generatedUI:i,offer:t}]),a._trace("rerender:rendered",{discountTitle:t.title,selectedTierIdx:a.state.selectedTierIdx})}catch(t){gfg.utility.debugError("error in gfgVolumeDiscountV2 rerender",t)}},clearWidget:function(){try{const t=a.constants.PREFIX;document.querySelectorAll(`.${t}-root`).forEach(function(t){t.remove()}),a.f.restoreQuantitySelector(),a.f.restoreAddToCartButton()}catch(t){gfg.utility.debugError("error in gfgVolumeDiscountV2 clearWidget",t)}},findPdpAnchor:function(){const t=gfg.settings&&gfg.settings.app&&gfg.settings.app.addToCartBtnSelectors||"",e="undefined"!=typeof DEFAULT_PDP_SELECTORS_NOV25?DEFAULT_PDP_SELECTORS_NOV25:".product-form__buttons, .product-form-buttons, .payment-buttons, .product__submit__buttons",i=t?`${t}, ${e}`:e,r="undefined"!=typeof DEFAULT_sideCartSelectorsApp7Ext?DEFAULT_sideCartSelectorsApp7Ext:"#CartDrawer, .drawer, .cart-drawer, .cart-notification, .Drawer",n=i.split(",").map(function(t){return t.trim()}).filter(Boolean);for(const t of n)try{const e=document.querySelector(t);if(e&&!e.closest(r))return e}catch(t){}return null},findVolumeBlock:function(){const t="undefined"!=typeof VOLUME_DISCOUNT_APP_BLOCK_SELECTOR?VOLUME_DISCOUNT_APP_BLOCK_SELECTOR:".gfgVolDiscountWrapperV3",e="undefined"!=typeof DEFAULT_sideCartSelectorsApp7Ext?DEFAULT_sideCartSelectorsApp7Ext:"#CartDrawer, .drawer, .cart-drawer, .cart-notification, .Drawer",i=Array.from(document.querySelectorAll(t));for(const t of i)if(document.body.contains(t)&&!t.closest(e)&&!t.closest(".gfgCartPageWrapperV2"))return t;return null},resolvePdpWrapper:function(){try{const t=a.f.findVolumeBlock();if(t)return t;const e=`${a.constants.PREFIX}-wrapper`,i="undefined"!=typeof DEFAULT_sideCartSelectorsApp7Ext?DEFAULT_sideCartSelectorsApp7Ext:"#CartDrawer, .drawer, .cart-drawer, .cart-notification, .Drawer",r=Array.from(document.querySelectorAll(`.${e}`)).filter(function(t){return document.body.contains(t)&&!t.closest(i)&&!t.closest(".gfgCartPageWrapperV2")});if(r.length){for(let t=1;t=0&&document.querySelector(`.${a.constants.PREFIX}-root`)&&a.f.syncQuantitySelector(a.f.getCurrentQuantitySelection())),a.f.reconcileSelectionWithQuantity()}catch(t){}},1e3))}},render:{offerTitle:function(t){const e=a.constants.PREFIX,i=a.f.createEl,r=a.f.getLocaleContent(t.content),n=r.heading?.title||"";if(!n)return null;const o=i("div",{class:`${e}-title-wrapper`}),s=i("div",{class:`${e}-title-divider`}),l=i("div",{class:`${e}-title-divider`}),c=i("div",{class:`${e}-title`,text:n});return o.append(s,c,l),o},radioTierCard:function(t,e,i,r){const n=a.constants.PREFIX,o=a.f.createEl,s=a.f.getTierWidgetSettings(t,e),l=a.f.getLocaleContent(s.ruleText),c=l.conditionMetText||l.conditionNotMetText||`Tier ${i+1}`,u=a.f.resolveText(c,t),g=a.f.computePillText(t,l.discountText||l.pillText),d=gfg.utility.getCurrencySymbol&&gfg.utility.getCurrencySymbol()||"",f=a.f.computeTierPricing(t,a.f.getCurrentVariantPrice()),p=f.discountedTotal({seg:t,origIdx:e})).sort((t,e)=>(t.seg.priority||0)-(e.seg.priority||0)),g=a.state.selectedTierIdx;return u.forEach(t=>{const i="radioButton"===e.subtype?a.render.radioTierCard(t.seg,e,t.origIdx,t.origIdx===g):a.render.tableTierRow(t.seg,e,t.origIdx);c.appendChild(i)}),o.appendChild(c),o}},actions:{handleTierSelect:function(t){a.state.selectedTierIdx=t,a.f.rerender();const e=(a.state.discount?.segmentsData?.segmentsList||[])[t];e&&a.f.syncQuantitySelector(a.f.getTierQuantity(e))},registerGlobalListener:function(){if(window._gfgVolV2ClickRegistered)return;window._gfgVolV2ClickRegistered=!0;const t=`.${a.constants.PREFIX}-radio-card`,e=e=>{const i=e&&e.closest&&e.closest(t);if(!i)return null;const r=parseInt(i.getAttribute("data-segment-idx"),10);return Number.isNaN(r)?null:r};document.addEventListener("click",t=>{const i=e(t.target);null!==i&&a.actions.handleTierSelect(i)}),document.addEventListener("keydown",t=>{if("Enter"!==t.key&&" "!==t.key)return;const i=e(t.target);null!==i&&(t.preventDefault(),a.actions.handleTierSelect(i))})}}};var s=!1;function l(){if(!s){s=!0;try{if(window.gfgCustomDiscount=r,window.gfgConsolidatedCustomDiscount=n,window.gfgDiscountAllocationSync=o,window.gfgVolumeDiscountV2=a,gfg.gfgVolumeDiscountV2=a,gfg.customDiscountValidationFunctions)for(const t of Object.keys(gfg.customDiscountValidationFunctions))t in i||(i[t]=gfg.customDiscountValidationFunctions[t]);gfg.customDiscountValidationFunctions=i,r.gfgBXGY.actions.registerGlobalClickListener(),window.gfgFileStatus&&(window.gfgFileStatus.customDiscountLogic="LOADED"),document.dispatchEvent(new CustomEvent("gfg:module:loaded",{detail:{moduleName:"customDiscountLogic"}})),gfg.utility.debugConsole("customDiscountLogic: Module registered successfully")}catch(t){console.error("customDiscountLogic: Error initializing module",t)}}}function c(t,e){s||function(t,e){for(var i=0;i