console.log('widebundle loaded');
if(typeof wideBundle == 'undefined' && Shopify && Shopify.shop == 'dexter-et-mango.myshopify.com'){
var wideBundle = wideBundle || {};
wideBundle.settings = {"id":"89047","shop":"dexter-et-mango.myshopify.com","charge_id":"83201917313","status":"active","price":"14.99","currency":"\u20ac{{amount}}","currency_format":"mix","option1_title":"Select your offer:","atc_background":"#fde799","hover_color":"#f9d44e","atc_color":"#ffffff","atc_text":"Ajouter au panier","atc_font_size":"1.2em","atc_font":"auto","atc_radius":"0px","atc_size":"small","atc_animation":"no","border_color":"#fde799","border_size":"2px","unselected_border_size":"2px","border_radius":"10px","unselected_border_radius":"10px","option_select_color":"#000000","option_select_background":"#ffffff","option_select_default_settings":"0","background_color":"#fde799","price_color":"#000000","price_compared_color":"#989898","price_size":"0.9em","unselected_price_fontsize":"0.9em","unselected_compare_price_fontsize":"0.9em","selected_price_fontsize":"0.9em","selected_compare_price_fontsize":"0.9em","offer_color":"#333232","title_best":"Best Offer!","color_best":"#000000","link_choice":"form","installed":"1","affiliate_id":"0","ref":null,"onboarding":"{\"steps\":{\"1\":1,\"2\":1,\"3\":1,\"4\":1,\"5\":0}}","notifications":"0","economic_color":"#000000","economic_text":"-{{percent}}% (-{{amount}})","economic_display":"0","selected_savings_fontsize":"0.9em","unselected_savings_fontsize":"0.9em","option_color":"#333232","option_fontsize":"0.8em","rtl":"0","enabled":"1","review":"0","onboarding_guided":"1","ask_referal":"1","price_separator":".","form_id":"product-form form[data-type=\"add-to-cart-form\"]","price_id":"not checked","select_id":"0","email_given":"0","email_perso":null,"before_code":"","after_code":"","trustbadge":"","offer_selected_color":"#333232","best_selected_color":"#050505","message_border_size":"0px","unselected_message_border_size":"0px","message_border_color":"#000000","unselected_message_border_color":"#000000","message_border_radius":"15px","unselected_message_border_radius":"15px","message_background_color":"#ffffff","unselected_message_background_color":"#fde799","message_background_transparency":"","unselected_message_background_transparency":"","unselected_free_gift_text_color":"#000000","unselected_free_gift_text_style":"none","unselected_free_gift_background_color":"#fffcf0","unselected_free_gift_icon_color":"#000000","selected_free_gift_text_color":"#ffffff","selected_free_gift_text_style":"none","selected_free_gift_background_color":"#f9d44e","selected_free_gift_icon_color":"#000000","price_selected_color":"#000000","price_compared_selected_color":"#989898","economic_selected_color":"#000000","update_price":"0","design_code":"2","svg_number":"0","svg_size":"1.2em","display_quantity":"0","bg_button_quantity":"#ffffff","color_button_quantity":"#000000","bg_input_quantity":"#ffffff","color_input_quantity":"#000000","style_blinking":"none","style_title":"none","style_economic":"none","style_price":"none","style_compared_price":"none","style_variants_selected":"none","style_blinking_selected":"none","style_title_selected":"none","selected_title_fontsize":"1.2em","unselected_title_fontsize":"1.2em","style_economic_selected":"none","style_price_selected":"none","preview_heading_color":"#5b4949","preview_heading_position":"center","preview_heading_font_size":"0.9em","preview_heading_font_style":"none","heading_line_color":"#000000","heading_line_size":"2px","heading_line_display":"1","style_compared_price_selected":"none","offers_heading_font_size":"0.9em","auto_round":"0","country_code":"FR","shopify_plan":"professional","no_decimal":"0","add_pixel":"1","utm_source":"new_wb_site","custom_css":".checkedWB{\n  display: none;\n}\n.value-left{\n  min-width: 20px !important;\n}\n\n.corner-offer{\n  background-color: var(--wb-border-color) !important;\n}\n\n.diagonal-offer::before{\n  background: linear-gradient(rgba(0, 0, 0, 0.5) 0 0) bottom\/100% var(--d) no-repeat var(--wb-border-color) !important;\n}\n\n.best-title{\n  padding: 4px 10px !important;\n  width: fit-content !important;\n  display: block !important;\n}\n\n.selectable{\n  border: 2px dashed var(--wb-unselected-border-color) !important;\n}\n\n.wb-gift-product-wrapper{\n  border-bottom-left-radius: calc(var(--wb-selected-border-radius) - 2px) !important;\n  border-bottom-right-radius: calc(var(--wb-selected-border-radius) - 2px) !important;\n}\n\n.gift-price-new-form{\n  color: var(--wb-unselected-free-gift-text-color);\n}","currency_code":"EUR","shop_creation":"2023-05-03 09:42:28","shop_id":"75469553960","referer":"Shopify App Store","plan":"incremental","partner_test_store":"0","thumbnail_size":"m","thumbnail_color":"#e9e9e9","unselected_thumbnail_size":"m","unselected_thumbnail_color":"#e9e9e9","unselected_border_color":"#fde799","unselected_background_color":"#afafaf","unselected_background_transparency":"00","font_unselected_custom_sentence":"auto","font_selected_custom_sentence":"auto","selected_custom_fontsize":"0.8em","unselected_custom_fontsize":"0.8em","unselected_title_text_color":"#000000","unselected_title_text_bg":"#fff5d1","unselected_title_text_size":"0.7em","unselected_title_text_border":"#ffffff","unselected_title_text_radius":"15px","unselected_title_text_style":"none","unselected_title_text_font":"auto","selected_title_text_color":"#ffffff","selected_title_text_bg":"#f97a6a","selected_title_text_size":"0.8em","selected_title_text_border":"#000000","selected_title_text_radius":"15px","selected_title_text_style":"none","selected_title_text_font":"auto","atc_content_text":"En rupture de stock","enable_atc_button":"0","current_amount":"29.99","current_additional_usd":"3104.35","legacy_additional_usd":"2667.36","billing_cycle":"2026-05-21","current_sales":"2289","legacy_amount":"29.99","priority_support":"0","advanced_price":null,"priority_price":null,"color_best_banner":"#000000","best_selected_color_banner":"#000000","js_code":null,"onboarding_closing":"0","widereview_closing":"0","integrations_closing":"0","scopes":"read_themes,read_products,write_products,read_orders,write_discounts,read_inventory,write_inventory,read_shipping,read_locations,read_locales,unauthenticated_read_product_listings,unauthenticated_read_product_inventory","banners_closing":"0","shopify_discount_id":"[\"gid:\\\/\\\/shopify\\\/DiscountAutomaticNode\\\/2341000151425\"]","discount_label":"offer","translations":"{}","notification_closing":"0","unselected_free_gift_text_fontsize":"0.9em","selected_free_gift_text_fontsize":"0.9em","round_prices_automatic":"0","is_hook_collection_delete":"1","design_info_closing":"0","first_bundle_sale":"1","storefront_token":"7031c9aed9192b9bb94d42abae7836a1","dg_choose_btn_text":"Choisir un produit","dg_popup_heading_text":"Choisissez le produit que vous souhaitez dans ce bundle"};
wideBundle.domain = 'https://widebundle.com/';
wideBundle.shop = wideBundle.settings.shop;
wideBundle.templates = [];
wideBundle.templates = Object.keys(wideBundle.templates).map(key => wideBundle.templates[key]);
wideBundle.ipHash = 2226917496;
wideBundle.targetProductSearch = null;
console.log('WB targetProductSearch:', wideBundle.targetProductSearch);
//Get the position of word in url
function posInUrl(text, subStrings) {
    var positions = {};
    subStrings.forEach(subString => {
      positions[subString] = text.indexOf(encodeURI(subString));
    });
    return positions;
}

//Check if a child is descendant of a parent
function isDescendant(parent, child){
    if(!parent){
      return false;
    }
    let node = child.parentNode;
    while (node != null) {
      if (node === parent) {
        return true;
      }
      node = node.parentNode;
    }
    return false;
};

//Get closest parent form
function getClosestParentForm(child){
  let node = child.parentNode;
  while (node) {
      if (node.tagName === "FORM") {
          return node;
      }
      node = node.parentNode;
  }
  return null;
}

//Add some style to the page
function addStyleToPage(styles, attribute = ''){
    var wbAttribute = 'wb-default-style';
    if (attribute !== '') {
      wbAttribute = 'wb-' + attribute + '-style';
    } 
    var css = document.createElement('style');
    css.setAttribute(wbAttribute, '');

    css.type = 'text/css';
    if (css.styleSheet)
        css.styleSheet.cssText = styles;
    else
        css.appendChild(document.createTextNode(styles));

    if (!document.querySelector(`[${wbAttribute}]`)) {
      document.getElementsByTagName("head")[0].appendChild(css);
    }
}

//Check if string is json
function isJsonString(str) {
  try {
      JSON.parse(str);
  } catch (e) {
      return false;
  }
  return true;
}

//Get SVG codes
function AddSVG(){
  var size = wideBundle.settings.svg_size;
  var color = wideBundle.settings.atc_color;
  var svg = wideBundle.settings.svg_number;

  if(svg == 1){
    svgCode = '<svg style=\'margin-right:10px;fill:'+color+';\' height=\''+size+'\' width=\''+size+'\' viewBox=\'0 -31 512.00033 512\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'m166 300.003906h271.003906c6.710938 0 12.597656-4.4375 14.414063-10.882812l60.003906-210.003906c1.289063-4.527344.40625-9.390626-2.433594-13.152344-2.84375-3.75-7.265625-5.964844-11.984375-5.964844h-365.632812l-10.722656-48.25c-1.523438-6.871094-7.617188-11.75-14.648438-11.75h-91c-8.289062 0-15 6.710938-15 15 0 8.292969 6.710938 15 15 15h78.960938l54.167968 243.75c-15.9375 6.929688-27.128906 22.792969-27.128906 41.253906 0 24.8125 20.1875 45 45 45h271.003906c8.292969 0 15-6.707031 15-15 0-8.289062-6.707031-15-15-15h-271.003906c-8.261719 0-15-6.722656-15-15s6.738281-15 15-15zm0 0\'/><path d=\'m151 405.003906c0 24.816406 20.1875 45 45.003906 45 24.8125 0 45-20.183594 45-45 0-24.8125-20.1875-45-45-45-24.816406 0-45.003906 20.1875-45.003906 45zm0 0\'/><path d=\'m362.003906 405.003906c0 24.816406 20.1875 45 45 45 24.816406 0 45-20.183594 45-45 0-24.8125-20.183594-45-45-45-24.8125 0-45 20.1875-45 45zm0 0\'/></svg>';
    return svgCode;
  }
  else if(svg == 2){
    svgCode = '<svg version=\'1.1\' id=\'Layer_1\' xmlns=\'http://www.w3.org/2000/svg\' height=\''+size+'\' width=\''+size+'\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'	 viewBox=\'0 0 512 512\' style=\'enable-background:new 0 0 512 512;margin-right:10px;fill:'+color+';\' xml:space=\'preserve\'><g>	<g>		<path d=\'M402.351,381.058h-203.32l-11.806-47.224h266.587L512,101.085H129.038L108.882,20.46H0v33.4h82.804l82.208,328.827			c-24.053,5.971-41.938,27.737-41.938,53.611c0,30.461,24.781,55.242,55.241,55.242c30.459,0,55.241-24.781,55.241-55.242			c0-7.755-1.613-15.138-4.511-21.841h122.577c-2.897,6.703-4.511,14.086-4.511,21.841c0,30.461,24.781,55.242,55.241,55.242			c30.459,0,55.241-24.781,55.241-55.242C457.592,405.84,432.811,381.058,402.351,381.058z M287.029,300.434h-37.08l-8.284-66.275			h45.365V300.434z M411.912,134.484h57.31l-16.568,66.275h-49.026L411.912,134.484z M399.453,234.16h44.85l-16.568,66.275h-36.566			L399.453,234.16z M320.428,134.484h57.824l-8.284,66.275h-49.539V134.484z M320.428,234.159h45.365l-8.284,66.275h-37.08V234.159z			 M287.029,134.484v66.275h-49.539l-8.284-66.275H287.029z M137.388,134.484h58.158l8.284,66.275h-49.873L137.388,134.484z			 M162.307,234.159h45.699l8.284,66.275h-37.414L162.307,234.159z M178.315,458.141c-12.043,0-21.841-9.798-21.841-21.842			c0-12.043,9.798-21.841,21.841-21.841s21.841,9.798,21.841,21.841C200.156,448.343,190.358,458.141,178.315,458.141z			 M402.351,458.141c-12.043,0-21.841-9.798-21.841-21.842c0-12.043,9.798-21.841,21.841-21.841			c12.043,0,21.841,9.798,21.841,21.841C424.192,448.343,414.394,458.141,402.351,458.141z\'/>	</g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g></svg>';
    return svgCode;
  }
  else if(svg == 3){
    svgCode = '<svg version=\'1.1\' id=\'Capa_1\' xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'	 viewBox=\'0 0 502.187 502.187\' style=\'enable-background:new 0 0 502.187 502.187;margin-right:10px;fill:'+color+';\' height=\''+size+'\' width=\''+size+'\' xml:space=\'preserve\'><g>	<g>		<polygon points=\'277.333,112.427 277.333,48.427 234.667,48.427 234.667,112.427 170.667,112.427 170.667,155.093 			234.667,155.093 234.667,219.093 277.333,219.093 277.333,155.093 341.333,155.093 341.333,112.427 		\'/>	</g></g><g>	<g>		<circle cx=\'170.667\' cy=\'432.427\' r=\'42.667\'/>	</g></g><g>	<g>		<circle cx=\'341.333\' cy=\'432.427\' r=\'42.667\'/>	</g></g><g>	<g>		<rect y=\'27.093\' width=\'85.333\' height=\'42.667\'/>	</g></g><g>	<g>		<polygon points=\'384,112.427 384,155.093 436.48,155.093 370.133,304.427 146.56,304.427 106.88,27.093 85.333,27.093 			64.213,30.08 109.44,347.093 397.867,347.093 502.187,112.427 		\'/>	</g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g></svg>';
    return svgCode;
  }
  else if(svg == 4){
    svgCode = '<svg version=\'1.1\' id=\'Capa_1\' xmlns=\'http://www.w3.org/2000/svg\' xmlns:xlink=\'http://www.w3.org/1999/xlink\' x=\'0px\' y=\'0px\'	 height=\''+size+'\' width=\''+size+'\' viewBox=\'0 0 45.402 45.402\' style=\'margin-right:10px;fill:'+color+';enable-background:new 0 0 45.402 45.402;\'	 xml:space=\'preserve\'><g>	<path d=\'M41.267,18.557H26.832V4.134C26.832,1.851,24.99,0,22.707,0c-2.283,0-4.124,1.851-4.124,4.135v14.432H4.141		c-2.283,0-4.139,1.851-4.138,4.135c-0.001,1.141,0.46,2.187,1.207,2.934c0.748,0.749,1.78,1.222,2.92,1.222h14.453V41.27		c0,1.142,0.453,2.176,1.201,2.922c0.748,0.748,1.777,1.211,2.919,1.211c2.282,0,4.129-1.851,4.129-4.133V26.857h14.435		c2.283,0,4.134-1.867,4.133-4.15C45.399,20.425,43.548,18.557,41.267,18.557z\'/></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g></svg>';
    return svgCode;
  }
  else if(svg == 5){
    svgCode = '<svg style=\'margin-right:10px;fill:'+color+';\' id=\'Layer_1\' enable-background=\'new 0 0 512 512\' height=\''+size+'\' width=\''+size+'\' viewBox=\'0 0 512 512\' xmlns=\'http://www.w3.org/2000/svg\'><g><path d=\'m512 213.206h-55.385l-46.288-119.318-27.969 10.849 42.08 108.469h-141.111l90.415-142.055h-53.912v-71.15h-127.705v71.15h-53.919l90.458 142.055h-141.08l42.079-108.469-27.969-10.849-46.288 119.318h-55.406v60.004h512z\'/><path d=\'m64.868 511.999h382.263l31.391-208.789h-445.044zm266.149-171.306h30v103.822h-30zm-60.004 0h30v103.822h-30zm-60.004 0h30v103.822h-30zm-60.004 0h30v103.822h-30z\'/></g></svg>';
    return svgCode;
  }
  else{
    return '';
  }
}

//Get base URL
function getShopifyBaseUrl() {
  if (Shopify?.routes?.root) {
    return Shopify.routes.root;
  }
  return "/";
}

//Compare 2 arrays
function arraysEqual(_arr1, _arr2) {

  if (!Array.isArray(_arr1) || ! Array.isArray(_arr2) || _arr1.length !== _arr2.length)
    return false;

  var arr1 = _arr1.concat().sort();
  var arr2 = _arr2.concat().sort();
  for (var i = 0; i < arr1.length; i++) {
      if (arr1[i] !== arr2[i])
          return false;
  }
  return true;
}

//Check if a text contains only numbers
function containsOnlyNumbers(text) {
  return /^\d+$/.test(text);
}

function wbHtmlentities(rawStr) {
  return rawStr.toString().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function wbEscapeSwatchValue(rawStr) {
  if (typeof rawStr !== 'string') {
    return rawStr;
  }
  
  // Escape special characters for use in attribute selectors
  return rawStr
    .replace(/\\/g, '\\\\')  // Escape backslashes first
    .replace(/"/g, '\\"')    // Escape double quotes
    .replace(/'/g, "\\'")    // Escape single quotes
    .replace(/\//g, '\\/')   // Escape forward slashes
    .replace(/\[/g, '\\[')   // Escape opening square brackets
    .replace(/\]/g, '\\]')   // Escape closing square brackets
    .replace(/\^/g, '\\^')   // Escape caret
    .replace(/\$/g, '\\$')   // Escape dollar sign
    .replace(/\*/g, '\\*')   // Escape asterisk
    .replace(/\(/g, '\\(')   // Escape opening parenthesis
    .replace(/\)/g, '\\)')   // Escape closing parenthesis
    .replace(/\s/g, '\\ ');  // Escape spaces
}

//Send the event change on element
function fireChangeEvent(node){
  if('createEvent' in document){
    var evt = document.createEvent('HTMLEvents');
    evt.initEvent('change', false, true);
    node.dispatchEvent(evt);
  }
  else{
    node.fireEvent('onchange');
  }
  setTimeout(function() {
    if('createEvent' in document){
      var evt = document.createEvent('HTMLEvents');
      evt.initEvent('change', false, true);
      node.dispatchEvent(evt);
    }
    else{
      node.fireEvent('onchange');
    }
  }, 100);
}

//Trigger mouse event
function triggerMouseEvent (node, eventType) {
  var clickEvent = document.createEvent ('MouseEvents');
  clickEvent.initEvent (eventType, true, true);
  node.dispatchEvent (clickEvent);
}

//Dispatch click event
function dispatchClick(node){
  if('createEvent' in document){
    var evt = document.createEvent('HTMLEvents');
    evt.initEvent('click', false, true);
    node.dispatchEvent(evt);
  }
  else{
    node.fireEvent('click');
  }
  setTimeout(function() {
    if('createEvent' in document){
      var evt = document.createEvent('HTMLEvents');
      evt.initEvent('click', false, true);
      node.dispatchEvent(evt);
    }
    else{
      node.fireEvent('click');
    }
  }, 100);
}

//Frire un event
function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

//Some shops are using this function even if we don't need it anymore at least it won't send an error
function showAndReduceForm() {
  return;
}

//Copy style from an element to another
function copyStyle(sourceElement, targetElement) {
  const sourceStyle = window.getComputedStyle(sourceElement);

  for (let i = 0; i < sourceStyle.length; i++) {
    const styleProperty = sourceStyle[i];
    targetElement.style[styleProperty] = sourceStyle.getPropertyValue(styleProperty);
  }

  const styleSheets = document.styleSheets;
  //For hover
  for (const styleSheet of styleSheets) {
    let cssRules;
    try {
      cssRules = styleSheet.cssRules;
    } catch (e) {
      // Skip CORS protected stylesheets
      continue;
    }

    for (const cssRule of cssRules) {
      if (cssRule.selectorText && cssRule.selectorText.includes(':hover')) {
        const sourceSelector = cssRule.selectorText.replace(':hover', '').trim();

        if (sourceElement.matches(sourceSelector)) {
          const targetSelector = sourceSelector + '[data-copied-style="true"]';
          const hoverStyle = cssRule.cssText.replace(cssRule.selectorText, targetSelector);
          const styleElement = document.createElement('style');

          styleElement.innerHTML = hoverStyle;
          document.head.appendChild(styleElement);

          targetElement.setAttribute('data-copied-style', 'true');
          break;
        }
      }
    }
  }
}

function AddGoogleFont(fontFamily) {
  if (!document.querySelector(`link[data-wb-font="${fontFamily}"]`)) {
    const link = document.createElement("link");
    link.setAttribute("data-wb-font", fontFamily);
    link.rel = "stylesheet";
    link.type = "text/css";
    link.href = `https://fonts.googleapis.com/css2?family=${fontFamily.replace(/\s/g, "+")}:ital,wght@0,400;0,700;1,400;1,700&display=swap`;
    document.head.appendChild(link);
  }
}

function GetLoadingGifBase64() {
  return "data:image/gif;base64,R0lGODlhPAA8APMAAOjo6NPT09fX19vb29/f3+Dg4Ofn5+jo6Ozs7PLy8vn5+QAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQJCgAAACH/C0ltYWdlTWFnaWNrDmdhbW1hPTAuNDU0NTQ1ACH+KU9wdGltaXplZCB3aXRoIGh0dHBzOi8vZXpnaWYuY29tL29wdGltaXplACwAAAAAPAA8AAAE/xDISau9OOvNu/9glyRhaU7jeK5emrKskrkqhsCZousXTVqIg/CGq+x4Ft9FyCwaj7KKssJsOifQKGVKqQqv2KyURvUSwQDxljwJetEUtYQL8B7gcTnXzTzj01AobHVvMEcYWVFTdn4UBgUFBhxyeYcAi4UVj5CQkjmJWmGHSoyam5yRG6ChgJYuEnZdp6gFdxqrSBKBF3y2ErO0npO4ujsafb+0qMIfxCbKnAa+Ic4gwJ3MJ6Al19mGu9bLeJbcnX/nzbi5MAQD7u/wAwQW6pQlBO3x+vLzovXr9/YJ7FfsH8AQ+QTGI9jKIIuECt8xbKgOB8SBBdBpVHXQwwABAp3+2OvwEaSAAWC2hRAQwCRIlDhWlWDp0mQMmSVK1nxZomLBW7l2uoTZwSdFROR0CiX6SWVBYw2frlNak2MieoHEjKTKsym5SlDVjASwk+kFcGDD7rpqQafZHF5zyRkr4a0JthS14B2HlhLdInv9/v32Ne+Twk5GKkabmLHhw1BTIn4MmRXgyWMdX45rOczGs5o/A50senTn0qhTr4gAACH5BAkKAAAAIf8LSW1hZ2VNYWdpY2sOZ2FtbWE9MC40NTQ1NDUALAAAAAA8ADwAgwAAANfX19vb29/f3+Dg4Ofn5+jo6Ozs7PLy8vX19fn5+QAAAAAAAAAAAAAAAAAAAAT/EMhJq7046827/2CnjGFpSiN5rmKqsqeSua+VJDBGX7RsI0BcrrKz9C4JIHBILFKOlaQSIWQCoE/nZEq1Zl1NMEWqrHp7PpSWHPSGU1/4hI1wv+VXJ91sz4v9eFx1MH93KlB7FwcGjAccWHGHRVx8EouMjRpoNWpiO4kUl5iZmptpgJIqbGaio6QzpqdaY1OhrqOOLaYTeEhUQq2uuSCxJ7e4Mbshx68rmyXHw0OQHq3SZ5wfl9d93Y+x2SYGBeTl5uUGhuAsBQTu7/DxBZHgpyXx+Pj06yv5/u77iq1o9+/dAALz1KHJMQ6hP3LpvEn8Zu8DgQEDulHrQECARwEZt608CzEggMkAHkMSGgligICTHw86U1bC5UmUKUvw86PBJUgJGE1+jPlBYKdwAEqepODT402MFBfyKiLmpkkKF52+NCkTllR6qGRsPalSQtaPKAls2Bj2qAqrAi40Nam2VC+wbQGMFXqhgM+yyf5gsRpg4lcsSmFKhARpb2GNjLUk5tuHGjXHgKfNyksBrp2NGzG72cyZwt66IgtNVQ1U8eeKq+9O6Jh5olvYtqPizm13N+/fwFlEAAAh+QQJCgAAACH/C0ltYWdlTWFnaWNrDmdhbW1hPTAuNDU0NTQ1ACwAAAAAPAA8AIMAAADX19fb29vf39/g4ODn5+fo6Ojs7Ozy8vL19fX5+fkAAAAAAAAAAAAAAAAAAAAE/xDISau9OOvNu/8gp4xhaU4jea5dmrKskrnqJcMYbet7jaOu3svC+wGDFdqNojQyi8fhE+mUNKdS67UK2Gqp3yzXS4Zyu9u094ymqsEneHR4VS4riHxCZA6r6n0ACXmEezN2d34yTWuChI+Gh3ZJPEheg4+PfIh3gW0+maEenDVilCqYoXklpCeqhXGcJa8IkSuIs6pVjRyibKYesGzDIKTAJQfJysvLRMaeHgcG09TV1gdYz4kh1t3d2c8s3uPT4MYs0uTXp+Ew6Qbv09LzxPUtPiAF+sO8GwUEAAkU2DUpRMCDBn7ICvHvIMACCWPhKmHA4cGBIc590TBgAIEJDbUtCvyg8dM2CR0DBBgwwUBIhxA3FVQkQaVKlCoFCGAJUiTADQvBARhgc+XQnQJuVngZEGMOXleKKtWZtOMFpk6fHruStCjOlAI+Wqj4EMeWrjknECW6M0M5GDPRKh0agGpbYl7kCqAwwO5efnml8tWp0uovM1L/qu1qeEwfvRbA3iUoB3IFtn0VOwkkN8CFzDrPcC6qeQIBqjwdZ5Dq+QLA1PYqJI5dgqhN2LQ99K2bu7dvNhEAACH5BAkKAAAAIf8LSW1hZ2VNYWdpY2sOZ2FtbWE9MC40NTQ1NDUALAAAAAA8ADwAgwAAANfX19vb29/f3+Dg4Ofn5+jo6Ozs7PLy8vX19fn5+QAAAAAAAAAAAAAAAAAAAAT/EMhJq7046827/2CnjGFpSiN5rmKqsqeSua9VwxR90fKe4jaXTxj8AXO6Cq9oPKKSSGK06QQspzder2q9PqVfKtfbBZO5ZalXi1ZC19AVGKu6sofbWXxiT57DYm53dIBpN4ZzTGR9dXtah4qLiYV8j5B4g4FRlZYllnkgn3KdIaIwj56DQH8crKuXrbBts3qfoCcIuQgJur26graaH77ExHS2LMXKucemuMvFzaTPvbzLkagwugnc17TfsbceB+QHba4aBwbrBuZO2SDq5evup/Af8uTs5KP38e3z6KWaJiCAAA0FEhaQUE4dO4EenAEIQNEghgIEMhKg4HBfw3CqsQpWDCBhgMkBEjBqXDhBn8dyGqZNGElRgoCbAjaqXFnBJT1+tSaJrIiSAE4BKAFozMiy58sNe2zSPKj0KNWdTC+4rLeCJkkJRo9OwLrx21CKVKuKTbmUQNM2XimExUmBLK2zFifMvUnBQNu3VeLKtVqBLGAgeJPqJVyhbdnAI9MuXlv3LxeaF/ZKHrsUzdDNYBlX8JsVzQCkGDRnSAgu9VHFrUGcvvk49gcCJ23r3t0mAgAh+QQJCgAAACH/C0ltYWdlTWFnaWNrDmdhbW1hPTAuNDU0NTQ1ACwAAAAAPAA8AIMAAADT09PX19fb29vf39/g4ODn5+fo6Ojs7Ozy8vL19fX5+fkAAAAAAAAAAAAAAAAE/xDISau9OOvNu/9gt4xhaUpjeq5iSrLrkrnvVcMVbev7jaOunspCk/0mRSKPUjQeAc3cEjl9JpnV6JM6vXKH2+/NC62GteUg0HxeeskntvaKlvqE93SQLofb/XwqdXpsWE1OhEZqcId5ho1iGF2NiBqUTmBCa4cllyaUMZAhoDCco4OlhZaqqZUfamGxn5eOp7RKtLUtuWO8uhy+vb4swYjFxMG4nq23ss4gA9EnCdQKsgMCAgECAyXU3wlb2NnkAt7g3z/l5d0h6ODWJ+Pl2wIEJu/wIfPr3BMEA+5lQEAQgYR84DwQWBegYbYC/6IFxEDwgEWDBxFS48CPHYUCEsInAjhgoKSEihcpKNAYLsPCfu0oAJQo0ECBmwYAVNxZYWU+DQbWDYBYASRNiAdu4jyJ8sCFnxpeirQwM5rApEpz6iyY0oLPjTBCTsW6lCnKZxIMiBU4UmkBrQAUIDgwly7atRTIvqUwt65dWUZp8nULF0CCvgWdVZU2OGsFxInDBA5IdILewma7blnM1jJhC4ctaj5StbNnxxb8/n1iACCBynk/g66LMYxNzKfLXiCINsPl3ids3nQKvARJk8WTK38WAQAh+QQJCgAAACH/C0ltYWdlTWFnaWNrDmdhbW1hPTAuNDU0NTQ1ACwAAAAAPAA8AIMAAADX19fb29vf39/g4ODn5+fo6Ojs7Ozy8vL19fX5+fn8/PwAAAAAAAAAAAAAAAAE/xDISau9OOvNu/9gpyhhaU7jeK5emrIsibnqDGf0pSz8IluuGzBo6fF+FNdCWNn5aslc8wllApzPITFJRVqPL+7I16R5meAxt+cdh63R1HLCrsp5cO14Dqj/qEd5elBdf103W2VSNHN+ZxKJM05VdHtzZhJPPRdGbzpuckNGkEFKeBRGhxp7Soo7MlSkkXdSOJO0cTuSaiimkRlpoHyeeqSOlCJKbie+xCBmoSGMYIhmfB/T19W/HJiCV8gtzt/kGwPn6OnpQtDeFQHw8fLzAyyphe4AAvP88zH3cvLt60fw3y1LoCgMINhPQAxWdzp5GSCgosWLFuvBiNjuUbmPFv/OEWAWTgjFjCXy3SBwEqU0UCVDtMSYEmLMDjMxjqwp8SaGnBc1AihAVAOCoyiO+VSIMaPQAgSiFsBwtGouS6c0AK0odGhUqRIQHBgbtirSXtk2EGgqoKsEqF+nAhhrwMABAGaPJnCVMMPaoG69fiUwdeyBunfnjrWqJ5BWlxYGE5ZwuK7dsIb1fhp3YecFuF8NULaLeELms+UMSJar2HBivAfyfgQdlYJrshPyIihHe7JpxLglJDiamdzqCgiAvy6beW+e3qJtWw6eezFqK7RZ/55uQfduOJIvuL7c3axz7HHFGyZfYTjj5wWid6fLvjxIDOvr3/9gWf/+Dq79J+AEgN9EAAAh+QQJCgAAACH/C0ltYWdlTWFnaWNrDmdhbW1hPTAuNDU0NTQ1ACwAAAAAPAA8AIMAAADX19fb29vf39/g4ODn5+fo6Ojs7Ozy8vL19fX5+fkAAAAAAAAAAAAAAAAAAAAE/xDISau9OOvNu/9gp4xhaUpjeq5iSrKrkrnvJcMYbet7jU+8Cu0mdP2KRqRKuTwChhYok+h8BlFXa/Y4pEqBW+dX2ySXq+bat4uOBtfhkCBAF/SSUvadQ+8H7i95YXoYA359dlNYKoSLYxeHfomOgUuPXWcWhpF9FHFXmJkYc5x0YFRulaElpXUmoT4gpJwlsDizfrWNt4e6SW2dr6JtxBwDAsjJysgEP7Ciy9HKAyzPY8fS0tQx1r8A2NnR1TQJthMF4dHbJ93eAATg4evc3cX2HwX57LFOBQT/BAr4GnbCH0CAA90VPHgwoUIQBhn+E+jw4YaIEgNKOMBRQ5NnH6UyAqQI4ICBkwcwlCsDcoNIjRNMnjwpAYFNBJS8rNJgICPJCTNn1ryJc9dODD0Z/twY1EDKBERxpgHEr0LEpUCbSoBKNCcqSh6wxmyaEgDXm6cIHpE5s6zZqGnV4mBLc8JZm57i/KDrlMJdqV6LNTVQ4e+Ur3PJFoarCI3ixV0POw7q1i7jxk7YVrYcmQkxjps5o82B+N7Wy6ZDoE794Szr17DvRQAAIfkECQoAAAAh/wtJbWFnZU1hZ2ljaw5nYW1tYT0wLjQ1NDU0NQAsAAAAADwAPACDAAAA19fX29vb39/f4ODg5+fn6Ojo7Ozs8vLy9fX1+fn5AAAAAAAAAAAAAAAAAAAABP8QyEmrvTjrzbv/YKeMYWlKY3quYkqy60Bg7nspcEYE/HDXNFWuIuDxfi6kcCgpGgWWGq4inTIBA2OPCuQmrxNtAEqRer9grJiM6k7M6YnTWHYDqvFJVsuG3/15AHNHbWiAJwQDijMWO3yFQnhKHANOAj4Wg2N/X4eQSxcFlXuKmBSDZECSb1VWGJU8ArKXjBJ7dJxTh602GKIBlbNbck9BhryuGoqzsmOXcrIancgly5aXMibIyR+JzLOmH9QwBMyjJa1gwbLhHp5MpSdogfQcBff4Bgb49wZD270mFCBAkAA/ggMRsgBoZ19BgwYPFlzIENS+ew8TPiToT17FXhfLN2bEWEvbx2QX+anEl+NjvZcbDhg44JEbE5n69KGzkwNnTp0h0vX8+XPnKhM+ic40KRREUqU0ARw4gECajW0flP6MCgCBV6/GemHdoDUnhQRfweb65GoshqdmK6RVq2pX0wsIoFqYCxbOu6MXfHKVO5ctW5s8MwwmnDaB4cf0EkxNy+pYYjBTJ1etDOodE6+Zp9aZB/hKWtGjQeVSPYSv49QBV9uEwTdK4tK0G9uexzl27q9KfF/OATz47D8wjSc36nu51ebOo0s/EQEAIfkECQoAAAAh/wtJbWFnZU1hZ2ljaw5nYW1tYT0wLjQ1NDU0NQAsAAAAADwAPACDAAAA19fX29vb39/f4ODg5+fn6Ojo7Ozs8vLy9fX1+fn5/Pz8AAAAAAAAAAAAAAAABP8QyEmrvTjrzbv/YDcIQ2iekhCsBOqK6yq8b5ENcTBjCp0Vo0HLgovtLIpkz1cZCUiXouyiVCyYzeez1MwdJ9YqluLcEr3IhXgsIQTNZDSlqmRPys+hRKqrJNVJdhRacHtyEkoLileCe1pBd4eAVmqNZIRHfEeKay8GBaAYBJhcmhKLnX51GwUErqFEmIZGiH+KF4uTGq2uvQUGFaOEJXwlVYsVuZNLPwS8rzZkZVwqfQB0jGC2dBufoL3Ql4Vu2qu1icsdB9/gr8AAbgNcPKu2y38gn+2+KMf3KPr2RQOBjRMzF+z4hSiYzUfAVyboBLLjbeBCc5YycjjAsaPHjlj/JIq8cMCAyZMoUR54oeyeRAolU8pE+YJSrkQvJ8ScObOmGoP2/kyUsJOnyprb0N08CIBjyo4GYq6koVTkUI1YMSRAkKDfVTZbEYjtejGVj7Bi00YUitEF2rRi11IyG+ItXK5yl37tYPcuWU4azNkc6eGuX22AMAAtp/QWB8NpyZ5bhepUOsb2Gl6APFbVmsVAmV7DtpcCZMmYA6GaOKkSkpwZ4KKew230GpuJX7fVOpt2J9hLM5QOsXooJ8CWa1tSdpC5791jMjdEd7CxJX+ekSNGJohw6jS67MD+7ucyG+VzFusejhT6YNG22bdXrF53Vlz1739Ar78D3f4ABvhCAQQAIfkECQoAAAAh/wtJbWFnZU1hZ2ljaw5nYW1tYT0wLjQ1NDU0NQAsAAAAADwAPACDAAAA09PT19fX29vb39/f4ODg5+fn6Ojo7Ozs8vLy+fn5AAAAAAAAAAAAAAAAAAAABP8QyEmrvTjrzbv/YEcQYWlOxDCQZ9sVqsq655HB8WzpdHUUQMMFJ8MIjoOeBcgcxlaXo1RZKRgMweUzWSFIkdSJ9QrU5izfY3hyxWYpxFFlkOauAWSmUJzjpQV3cExlfGcTdF92gW5BewBEKih/gVWDBYUxE18BgDQICAcIGIxYe5BcA5xSihQKrgocB6Gfohakpk8skxavvRqgs5+hS5aPuQCIqxW9zBuytLLDFIxWEilQyGnLzL6/s9HB06WOFXUT3M0dwODAtWTkFohc6N0fws/ttSX0ryf34NJA8IPlCWDAD/TWrDvogRslYfpC1KNE0UOCixgzYqQysJ8FjSCwNbro6HBCAgQhU44kOfFkyk8iW7Bs+RJmxpUzCZpMCbJHzopAO3jc54piSYHpOKIjehRn04YJZQ40MVViVQBDLwztiPBq0m1br2oQW7JbU7Fao7ZK1+wpVrVp3S4t+/WcW7BF43qkW1dCXww6eSU9etdv4BNLDddLbPTr2b9KHUuG7LPu08I0GCvOujnvGrl9MUvl3Plw50B/71LGCZiy56B4X8PuSno2h4m2c+sOEwEAIfkECQoAAAAh/wtJbWFnZU1hZ2ljaw5nYW1tYT0wLjQ1NDU0NQAsAAAAADwAPACDAAAA09PT19fX29vb39/f4ODg5+fn6Ojo7Ozs8vLy9fX1+fn5AAAAAAAAAAAAAAAABP8QyEmrvTjrzbv/YGeMYWlKRVocZyuqheG6SGbAMlbMGXL8NctNlbMQBgMCz/JrXoapIuWIHCwrB4TWJ8RZCtXk7irJblkVaMwYVpIn2iZ6opYCwMf8G+5rBiV1FVRVexRyWhSBE4NIboUAcmZ0XihVeo8TkXOKAIxWMwoJCQoYfX6AlGBtGAMCAp8aorKkFltbqEQSjI5Trr6wF6Gys0xmiIGqloKtvq7AF8PRtGV+aEM5VJeVza4BArzB0cPTkEB/FcnAzNzOHsLioxKmGgT1YwTsv+Ab7/An6wK8OdvnDl68EACbPTPRT1aJfAtd9CPnAWCSQgpCUfzQ6iKmjx6/FogcSXLklZIoRV5IyXKBi5YsKcBM+XJmSZk2SdbMqXICT5Mtfvb0yZPHT5BINwAtsXQPSqY3ycQMMXVGS6g0g8I0sZVqVwBNLSyd+YGshKhidZ79qoHtU7BA366tiuFqhbc35RLNWlfvXp140eIUvFJtWrWBCc8dqjSD3MeKfS7hCzmyVMF6/b7hC9dwZ8+bCfvVPHm0YtJWT6sGXTrsYsZ/XTpl/Rn260euX8sunLQw7d5KfwN3nHu48eMtIgAAIfkECQoAAAAh/wtJbWFnZU1hZ2ljaw5nYW1tYT0wLjQ1NDU0NQAsAAAAADwAPACDAAAA19fX29vb39/f4ODg5+fn6Ojo7Ozs8vLy9fX1+fn5/Pz8AAAAAAAAAAAAAAAABP8QyEmrvTjrzbv/YHccYWlORmqcrHeoBtmySaa+8rXOGOIjNctomKMYCMgCz/LzXYijC3K6rDSdFVjMUpgiq5QrwqItSrxfsCQhzkIrXa9SLWkb3xT0nA5gXylEWxNoBHxhV0EAQyk5cVN7hgB2ijA5hDwKmQo9dmUSjkkYA6OFG5kLC5kXnZVnaFICsbGlGJqpthV+TZQ3AKAEkAAEA7ICxLS1CqiaylZ/ijiujxXEsdXHpsq3p6mHPxigFNXGxcYey8y3C2vfGXE74+XmINvazCfE8dbIIMz+6yH0kRuAyV+zgPlkEQRjsES8hXTumRg1gF+kixrSoZPIg6LHjxDyJygzyM0WwBMCAqhcybJlhZEk6x080bJmSwEUUMnUWe+kCZtAVebkqU6nvxYpg7YMCYCkUx7yos7DSDWDzhOaImlbVqIhw1Ngu5ZUVZCkWKNZWaA9KnYr235u33LNkLbpWo4cTPIk2xQmho0i//HsoHGZT69GJWzcFLiwzwsy6zZOi05xPQsGb2mIfCEd47WKbTF+6ZUuXgpeU+8djfp0MtMcS682zePuBMPdLL81NPv23tauvxIFPleC3sdfuZG2R3own9KT+YoEHHG3cet2g8/AbndbZ+0tuMf9Ljn5X+qYpVf17X09XPDuk6mPT7/+jAgAOw==";
}

// Pre-calculate the CRC32 lookup table once
function wbMakeCRCTable() {
  let c;
  const crcTable = [];
  for (let n = 0; n < 256; n++) {
    c = n;
    for (let k = 0; k < 8; k++) {
      // PHP's crc32 uses the reflected polynomial (0xEDB88320) and reflected input/output
      // JavaScript's bitwise right shift (>>>) is necessary for unsigned operations
      c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
    }
    crcTable[n] = c;
  }
  return crcTable;
}

/**
 * Calculates a CRC32 checksum compatible with PHP's crc32() function.
 * Note: PHP's crc32() works on bytes, so the input string should be treated as bytes (e.g., UTF-8 encoded).
 * @param {string} str - The input string (treated as UTF-8 byte sequence).
 * @returns {number} - The unsigned 32-bit integer CRC32 checksum.
 */
function wb_php_crc32(str) {
  // 1. Convert the string to a Uint8Array (UTF-8 byte representation)
  const bytes = new TextEncoder().encode(str);

  // 2. Initialize CRC value to 0xFFFFFFFF (inverted initial value)
  // The -1 trick in JS is a compact way to get 0xFFFFFFFF as a signed 32-bit integer
  let crc = -1; 

  for (let i = 0; i < bytes.length; i++) {
    // 3. XOR the current CRC byte with the next data byte
    // Bitwise AND 0xFF is to ensure we only use the lower 8 bits of the byte
    const byte = bytes[i] & 0xFF;
    
    // 4. Update the CRC value using the lookup table
    crc = (crc >>> 8) ^ wbCRCTable[(crc ^ byte) & 0xFF];
  }

  // 5. Final XOR with 0xFFFFFFFF and convert to unsigned 32-bit integer
  // The >>> 0 converts the result from a signed 32-bit integer to its unsigned 32-bit representation (a positive number).
  return (crc ^ (-1)) >>> 0;
}

const wbCRCTable = wbMakeCRCTable();

//Function to create tags <link> for all used Google fonts
wideBundle.loadGoogleFonts = function(){
    const settingsKeys = ["atc_font", "font_unselected_custom_sentence", "font_selected_custom_sentence"];
    settingsKeys.forEach(function (key) {
        if (wideBundle.settings[key] != "auto") {
            AddGoogleFont(wideBundle.settings[key]);
        }
    });
};

//Function to get the Add To Cart Button
wideBundle.getAddToCartButton = function(){

    //Add to cart button selectors in the form
    var submitButtons = [
        "gp-product-button button", ".bettercart_checkout.elm_pos_0", ".bettercart_checkout", ".add-to-cart-first", ".add_to_cart", ".button--add-to-cart", ".shg-btn", "button[data-pf-type='ProductATC2']", "input[type='submit']", ".smart-wrapper .add-to-cart-btn#AddToCartDesk", ".btn--add-to-cart",
        ".product-form__item--submit .product-form__cart-submit", ".gt_product-button", ".add", "button#addToCartCopy", 'button[data-name="Product Button"]', ".paymentButtonsWrapper button[type='submit']", "button[type='submit']", ".gf_add-to-cart", "button[data-pf-type=\"ProductATC\"]", "button.add-to-cart",
        ".product-form__submit", "button.single_add_to_cart_button", '.tt-wrapper .btn-addtocart', '#AddToCart', 'button.product-submit', '.button--addToCart', '.product__buy .product__add-to-cart', "button[class*='f-buy-buttons']", ".product-buy-buttons--cta", 'button[data-replo-repeated-index][role="button"]',
        ".form-actions button[data-product-add].button.button-secondary", "button[data-replo-add-product-variant-to-cart]", ".product-form__buttons #submitProduct[name='add']",
        "a#add-to-cart-btn.product--addtocart", "x-buy-button.x-product-buy-button[type='submit']", "button[id*='buy_group_add_to_cart_template--'].smi-button-wrapper", ".mm-main-product-CTA-container .mm-btn-secondary", "product-buy-buttons-element button.product-buy-buttons--primary"
    ];

    //exceptions
    var buttonsExceptions = [
      ".spr-button", "#judgeme_product_reviews"
    ];

    if(wideBundle.formInfo.element){
        findButton:
        for(i=0; i<submitButtons.length; i++){
            buttonFound = wideBundle.formInfo.element.querySelector(submitButtons[i]);
            if(buttonFound){ //Button in form

                for(var x=0; x < buttonsExceptions.length; x++){ //Check exceptions
                    exceptionAll = wideBundle.formInfo.element.querySelectorAll(buttonsExceptions[x]);
                    for(var z=0; z < exceptionAll.length; z++){
                        exception = exceptionAll[z];
                        //If the button is child of an exception
                        if(exception == buttonFound || isDescendant(exception, buttonFound) || isDescendant(buttonFound, exception)){
                            console.log('button is an exception...');
                            continue findButton;
                        }
                    }
                }

                return {
                    element: buttonFound,
                    id: submitButtons[i]
                }
            }
            else if(wideBundle.formInfo.id == "page builder"){ //Button in the whole page but it's a page builder
                buttonFound = document.querySelector(submitButtons[i]);
                if(buttonFound && buttonFound.parentNode){
                    closestForm = getClosestParentForm(buttonFound);
                    if(buttonFound.hasAttribute('data-replo-repeated-index') || buttonFound.hasAttribute('data-replo-add-product-variant-to-cart')){ //For Replo
                        return {
                            element: buttonFound,
                            id: submitButtons[i]
                        }
                    }
                    else if(closestForm && isDescendant(closestForm, document.querySelector('#new-form'))){ //Check if WB is inside this form
                        return {
                            element: buttonFound,
                            id: submitButtons[i]
                        }
                    }
                }
            }
        }
        return null;
    }
    return null;
}

//Function to get the variants selector
wideBundle.getVariantsSelector = function(specificFormToUse = ""){

    if(specificFormToUse == ""){
      var formWB = wideBundle.formInfo.element ? wideBundle.formInfo.element : wideBundle.manualWidget;
    }
    else{
      formWB = specificFormToUse;
    }

    //Selectors for <select> elements
    var selsWB = [
        ".single-option-selector", ".variant__input-product-template:not(input[type=\"radio\"])", ".single-option-selector-product-template", ".single-option-selector__radio.product-form__input", ".shg-product-variant-select",
        ".product-form__single-selector", "gp-product-variants select", ".AddToCartForm .gf_variants", ".product-form__controls-group .product-form__option select", ".option-selectors .selector-wrapper select",
        "select.pf-variant-select", ".product-form__input select.select__select", "div[data-product-options-container] .form-field-select-wrapper .form-field-select", ".variants-ui__input-select.form-field-input.form-field-select",
        ".product-options.grid .js", 'options-selection select', "variant-select select", '.zpa-single-option-selector', '.prd-block_options .prd-block_select select', '.product-page-info__variants select', 'product-variants select',
        '.dynamic-variant-input', '.product-options select', "variant-selector select", "fieldset[data-node-type='add-to-cart-option'] [data-node-type='add-to-cart-option-select']", '.js-product-option-input',
        '.product__variants select', "gp-product-variants select", "variant-selects fieldset select", '.product__option-select-wrapper select', 'select[data-replo-repeated-index][role="listbox"]', 'variant-selects select.field__input',
        ".product__option .select-wrapper select.input", "select[data-replo-variant-select-dropdown]", ".product__block.product__variant-select select", "select.original-selector[name='id']",
        "div[data-product-option] select[data-product-option-selector]", ".product__form-block .selector-wrapper select", "variant-dropdown .product-variant__option__item select",
        "x-variant-picker.x-variant-picker .x-variant-picker__field-wrapper select", "product-selector.main-product__selector .select select", "f-variant-picker .f\\:variant-picker__field-wrapper select", ".wb-custom-variants-selector select",
        "loess-variant-picker loess-variant-selects select", '.variant-picker__form .variant-option__select-wrapper select.variant-option__select', "variant-selects .select__select", ".shopify-product-form .product-variants.product-variants--only select"
    ];

    //Selectors for <input> <select> <button> <span> elements
    //You need to add the parent that contains the options with inputs inside (If 3 options like "offer, size and color" then you should have a size of 3 for the parent)
    var fieldsetsWB = [
        ".single-option-radio", ".variant-input-wrap:not(.recommendation-variant-input-wrap)", ".SizeSwatchList", ".input-field.materialize-select", "fieldset.swatch.clearfix", ".swatches-wrapper .swatch", ".swatch_options .swatch",
        ".radios--root", ".Product__OffScreen .Popover__ValueList", ".Popover__ValueList", "#product-variants .swatch", ".selector-wrapper.product-form__item", ".selector-wrapper.js", ".block-swatch-list", ".swatch-container .swatch__container", ".form-options .option-values",
        ".product-block .variant-input-wrap", "variant-radios .product-form__input", ".swatch.clearfix .swatch-inner", ".variant-group .swatch--product", ".product__selectors .radio__fieldset", ".product-options .inline-field-wrapper",
        ".option-selector-fieldset .option-selector__btns", ".swatches_options .product_options", 'fieldset .option-selector__btns', '.product-form .swatch .pr_form_item', '.product-options--swatches .swatches--offer .swatches__options',
        ':not(.product-sticky-form__form) > product-variants combo-box .combo-box__option-list', 'fieldset.product-variant-picker-block', '.body .product-variant-option .swatch.clearfix', '.pf-option-swatches', ':not(.pupsdreams_popup_product-details-info) > variant-picker fieldset .variant-picker__option-values',
        '#bcpo .bcpo-buttons', '.gf_swatches .gf_swatches-selector', '.product-form-grid .option-values', 'options-selection .options-selection__option-values', '.product__swatches .swatches__holder', 'options-selection fieldset.swatch .swatch__options','variant-radios.variant-select fieldset', '.variations fieldset.product-form__input',
        '#product-swatch .swatch-elements-options', 'f-variant-picker [class*="variant-picker__option-values"]', ':not(form[action="/localization"]) > x-listbox','.product-loop-variants', "variant-selects .product-form__input", '.product-information-variant-picker-button-variants', '.product-variant__container--radio',
        'div.swatch div.swatch-items-wrapper', '.product-swatches div[data-product-swatch].form-field .form-field__swatch-options', '.product_main_detail variant-radios fieldset.product_main_swachter', "variant-picker variant-button .m-product-option--content", "product-page.container product-variants .product-variants--radio",
        ".product-variants variant-radios fieldset.product-form-input", "div.\\#product-options-radio.\\@columns(label[class$='product-options-radio-item'])", ".variant_picker variant-radios fieldset.product-form__inpt",
        ".product__selector product-selector fieldset.product-selector__buttons", "product-variant-selector .\\#product-options-radio", ".product-variant-selector ul.product-options .product-option-wrapper ul.list-unstyled",
        "form div.variants-wrapper.product-form__item.wpb-variants-swatch .variants__options", ".x-variant-picker__field-wrapper .x-variant-picker__input .x-variant-picker__option-values",
        '[id*="variant-selects-template--"] .pp-variant-picker', ".swatch.swatches-selector-wrapper .swatch_item", '.wt-product__option fieldset ul.f-button__list',  "high-variant-selects.variant-selects fieldset.product-form-input", "variant-picker.variant-picker .variant-picker__form fieldset.variant-option",
        'variant-picker .product-form__option-selector .select-wrapper combo-box', 'fieldset.variant-input-wrapper ul.swatches.swatches--variant', "variant-picker .m-product-option .m-product-option--content", "hybrid-variant-picker fieldset.product-form__input section.swatches-container", "variant-selector .mm-product-form-variant-values",
        "variant-radios-detail fieldset.product-form__input", ".simple-variant-picker .simple-variant-picker__container .simple-variant-picker__values", ".x-variant-picker fieldset.product-form__input", "dm-variant-selects fieldset", "product-swatch .swatch-items-wrapper"
    ];

    //Selectors for <a> <li> <div> elements
    var swatchsWB = [
        ".tt-options-swatch", ".swatches-select", ".pt-options-swatch", ".product-options__section", ".product-options__option", ".selectric-items .selectric-scroll", ".pg__option .pg__option__values",
        ".input-field.product-option-select", ".button-group-hero.w-commerce-commerceaddtocartoptionpillgroup", ".product__selectors .select-popout__list", 'fieldset.select__fieldset .select-popout',
        'div[data-dropdown-wrapper] .t4s-dropdown__content', '.t4s-swatch__list', '.product-details-wrapper .wetheme-dropdown__wrapper ul', '.disclosure--form', 'gp-product-variants .variant-inside(input)', 'gp-product-variants(input)', 'div[data-replo-variant-select]',
        ".product-detail__options .option-selector ul.cc-select__listbox"
    ];

    var selectorsException = [
        '#great_sticky_bar', '.t4s-sticky-atc__product div[data-sticky-v-title] .t4s-dropdown .t4s-current-scrollbar',  '#sticky-cart-button div[data-pf-type="ProductVariantSwatches"]', '.variations.variations--siblings', `[id*='__featured_product_'].shopify-section--featured-product .section__color-wrapper`, "footer .Footer__LocalizationItem .Popover__Content"
        , 'form#localization_form_header[action="/en/localization"]', ".wb-exception-product-variants"
    ];
    var selectorsExceptionWB = document.querySelectorAll(selectorsException.join(','));

    var elementsToTest = [
        {array: swatchsWB, type: 'swatch'},
        {array: fieldsetsWB, type: 'fieldset'},
        {array: selsWB, type: 'select'}
    ]

    for(var x=0; x<elementsToTest.length; x++){
        elementTesting = elementsToTest[x];
        length = elementTesting.array.length;
        for(i=0; i<length; i++){
            testHasChild = elementTesting.array[i].split('(');
            hasChild = "";
            if(testHasChild.length > 1 && !elementTesting.array[i].includes(":not")){
                theElementToUse = testHasChild[0];
                hasChild = testHasChild[1].split(')')[0];
            }
            else{
                theElementToUse = elementTesting.array[i];
            }
            if(formWB){
                nodeElement = formWB.querySelectorAll(theElementToUse);
                if(nodeElement[0] != undefined){
                    if(hasChild == "" || nodeElement[0].querySelector(hasChild)){
                        return {
                            element: nodeElement,
                            id: theElementToUse,
                            type: elementTesting.type,
                            total: nodeElement.length
                        }
                    }
                }
            }
            nodeElement = document.querySelectorAll(theElementToUse);

            if(nodeElement[0] != undefined){
                isSelectorException = false
                isSelectorException = Array.from(selectorsExceptionWB).some(node =>  isDescendant(node, nodeElement[0]));

                if(!isSelectorException && (hasChild == "" || nodeElement[0].querySelector(hasChild))){
                    return {
                        element: nodeElement,
                        id: theElementToUse,
                        type: elementTesting.type,
                        total: nodeElement.length
                    }
                }
            }
        }
    }

    return null;
}

//Update the prices of the offer
wideBundle.updatePricesInOffer = function(){
    const variantIdsSelectedWithType = wideBundle.mapSelectedVariantsToOffers();
    const variantIdsSelectedWithUpsell = wideBundle.mapSelectedVariantsToOffers(true);
    const variantIdsSelected = variantIdsSelectedWithUpsell.map(variant => variant.variantId);
    const offerSelected = wideBundle.getSelectedOffer();
    
    if (offerSelected.automatic_discount) {
        const offerValuePrice = parseFloat(wideBundle.getAmountFromPrice(document.querySelector('.wb_hidden_prices .wb_hidden_price[offer-idx="' + offerSelected.offersPointer + '"]').innerHTML).replace(",", "."));

        let totalPrice = 0;
        let totalCompareAtPrice = 0;
        let discountedPrice = 0;
        let giftPrice = 0;  // Declare giftPrice variable
        let variantsString = offerSelected.offersPointer + "@" + variantIdsSelected.join("+");
        let giftProductsCounter = 0;
        const giftVariantIds = wideBundle.getGiftVariantIds(offerSelected.offersPointer);
        const upsellVariantIds = wideBundle.getUpsellVariantIds(offerSelected.offersPointer);
        const giftWrapperElements = Array.from(wideBundle.activeWidget.querySelectorAll('.selectedWB .wb-gift-product-wrapper'));
        variantIdsSelectedWithType.forEach((variant, index) => {
            const variantId = variant.variantId;
            const hiddenPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="' + variantId + '"]');
            const hiddenCompareAtPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_compared_price[variant-id="' + variantId + '"]');
            if (!hiddenPriceElement) return;

            const variantPrice = parseFloat(wideBundle.getAmountFromPrice(hiddenPriceElement?.innerHTML).replace(',', '.'));
            if (variant.productType === "target") {
                totalPrice += variantPrice;
            }

            if (variant.productType !== "upsell" && hiddenCompareAtPriceElement && hiddenCompareAtPriceElement.innerHTML !== "") {
                const variantCompareAtPrice = parseFloat(wideBundle.getAmountFromPrice(hiddenCompareAtPriceElement.innerHTML).replace(',', '.'));
                totalCompareAtPrice += variantCompareAtPrice;
            }
            else if (variant.productType !== "upsell") {
                totalCompareAtPrice += variantPrice;
            }

            if (
                variant.productType === "gift" &&
                giftWrapperElements[giftProductsCounter]
            ) {
                const giftWrapper = giftWrapperElements[giftProductsCounter];
                const giftPriceElement = giftWrapper.querySelector('.gift-price-WB');
                const giftCompareAtPriceElement = giftWrapper.querySelector('.gift-compare-at-price-WB .crossed-price-WB');

                if (giftPriceElement && giftCompareAtPriceElement) {
                    // Added currency conversion here
                    const giftPrice = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal("0.00")));
                    const originalGiftPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantId}"]`).innerHTML;
                    const giftCompareAtPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantId}"]`).innerHTML;
                    
                    giftPriceElement.innerHTML = giftPrice;
                    // Added currency conversion here
                    giftCompareAtPriceElement.innerHTML = wideBundle.replaceCurrencyForMarket(giftCompareAtPrice && giftCompareAtPrice !== "" ? giftCompareAtPrice : originalGiftPrice);
                    
                    handleTranscyPrice(giftPrice, giftPriceElement);
                    handleTranscyPrice(giftCompareAtPrice && giftCompareAtPrice !== "" ? giftCompareAtPrice : originalGiftPrice, giftCompareAtPriceElement);
                }
                giftPrice = variantPrice;
                giftProductsCounter++;
            }
        });
        variantIdsSelectedWithUpsell.filter((variant) => variant.productType === "upsell").forEach((upsell) => {
            const upsellOffer = wideBundle.offers[offerSelected.offersPointer].find((offer) => offer.product_is_upsell);
            const priceElement = wideBundle.activeWidget.querySelector('.selectedWB .upsell-price-new-form');
            const totalPrice = wideBundle.getAmountFromPrice(document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${upsell.variantId}"]`)?.innerHTML ?? "").replace(",", ".");
            const price = Math.max(0, totalPrice - ((totalPrice / 100) * upsellOffer.upsell_discount)).toFixed(2);
            const compareAtPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${upsell.variantId}"]`)?.innerHTML ?? "";
            const formattedPrice = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(price))));
            const formattedCompareAtPrice = compareAtPrice?.length > 0 ? wideBundle.replaceCurrencyForMarket(compareAtPrice) : wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(totalPrice))));
            let priceHtml = `
                <span class='gift-price-WB notranslate money conversion-bear-money transcy-money'>${formattedPrice}</span>
            `;
            let compareAtPriceHtml = `
                <span class='gift-compare-at-price-WB notranslate money transcy-money conversion-bear-money'><s class="crossed-price-WB">${formattedCompareAtPrice}</s></span>
            `;
            if (
                Number(wideBundle.getAmountFromPrice(formattedPrice) ?? 0).toFixed(2) ===
                Number(wideBundle.getAmountFromPrice(formattedCompareAtPrice) ?? 0).toFixed(2)
            ) {
                compareAtPriceHtml = '';
            }
            priceElement.innerHTML = priceHtml + compareAtPriceHtml;
        });

        let combinedPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_prices_element[data-calculated] .wb_hidden_price[variant-id="' + variantsString + '"]');
        let combinedCompareAtPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_prices_element[data-calculated] .wb_hidden_compared_price[variant-id="' + variantsString + '"]');
        if (!combinedPriceElement || !combinedCompareAtPriceElement) {
            const divHiddenPrices = document.querySelector('.wb_hidden_prices');
            switch (offerSelected.discount_type) {
                case "amount":
                case "value":
                    discountedPrice = Math.max(0, totalPrice - offerValuePrice);
                    break;
    
                case "percent":
                    discountedPrice = Math.max(0, totalPrice - ((totalPrice / 100) * offerValuePrice));
                    break;
    
                case "fixed":
                    if (offerValuePrice === 0) {
                        discountedPrice = totalPrice;
                    } else {
                        discountedPrice = offerValuePrice;
                    }
                    break;

                case "gift":
                    discountedPrice = totalPrice - giftPrice;
            }

            discountedPrice = discountedPrice.toFixed(2);
            totalCompareAtPrice = totalCompareAtPrice.toFixed(2);
            totalPrice = totalPrice.toFixed(2);

            const roundPrices = wideBundle.settings.round_prices_automatic == 1 && parseFloat(window?.Shopify?.currency?.rate) !== 1.0 && offerSelected.discount_type !== "gift";
            if (roundPrices && !Number.isInteger(parseFloat(discountedPrice))) {
                if (Math.ceil(discountedPrice) <= parseFloat(totalPrice)) {
                    discountedPrice = Math.ceil(discountedPrice).toFixed(2);
                }
            }

            let compareAtPriceToShow = "";

            if (totalCompareAtPrice > 0) {
                if (parseFloat(wideBundle.getAmountFromPrice(discountedPrice)) >= parseFloat(wideBundle.getAmountFromPrice(totalCompareAtPrice))) {
                    compareAtPriceToShow = "";
                }
                else{
                    compareAtPriceToShow = totalCompareAtPrice;
                }
            } else {
                compareAtPriceToShow = parseFloat(wideBundle.getAmountFromPrice(discountedPrice)) >= parseFloat(wideBundle.getAmountFromPrice(totalPrice)) ? "" : totalPrice;
            }
            divHiddenPrices.innerHTML += `
                <p class="wb_hidden_prices_element" data-calculated>
                    <span class="wb_hidden_price notranslate money conversion-bear-money  transcy-money" variant-id="${variantsString}" product-id="null">${wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(discountedPrice))))}</span>
                    <span class="wb_hidden_compared_price notranslate money conversion-bear-money transcy-money" variant-id="${variantsString}" product-id="null">${wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(compareAtPriceToShow))))}</span>
                </p>
            `;

            combinedPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="' + variantsString + '"]');
            combinedCompareAtPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_compared_price[variant-id="' + variantsString + '"]');
        }
        const price = combinedPriceElement.innerHTML;
        const compareAtPrice = combinedCompareAtPriceElement.innerHTML;
        wideBundle.updateSavingsText(price, compareAtPrice);

        for (var y = 0; y < document.querySelectorAll('.selectedWB .price-new-form span.first-price-WB').length; y++) {
            document.querySelectorAll('.selectedWB .price-new-form span.first-price-WB')[y].innerHTML = price;
            handleTranscyPrice(price, document.querySelectorAll('.selectedWB .price-new-form span.first-price-WB')[y]);
            if (document.querySelectorAll('.selectedWB .price-new-form .second-price-WB s')[y]) {
                document.querySelectorAll('.selectedWB .price-new-form .second-price-WB s')[y].innerHTML = compareAtPrice;
            }
            else {
                document.querySelectorAll('.selectedWB .price-new-form .second-price-WB')[y].innerHTML = compareAtPrice;
            }
            handleTranscyPrice(compareAtPrice, document.querySelectorAll('.selectedWB .price-new-form .second-price-WB')[y]);
        }

        const giftProductWrappers = Array.from(wideBundle.activeWidget.querySelectorAll('.selectedWB .wb-gift-product-wrapper'));
        giftProductWrappers.forEach((wrapper) => {
            const offersPointer = wrapper.dataset.gOffersPointer;
            const productPointer = wrapper.dataset.gProductPointer;
            const productId = wrapper.dataset.gProductId;
            const firstPrice = wrapper.querySelector('.gift-compare-at-price-WB');
            const secondaryPrices = Array.from(document.querySelectorAll(`.wb-gift-product-wrapper[data-g-product-id="${productId}"][data-g-offers-pointer="${offersPointer}"][data-g-product-pointer="${productPointer}"] .gift-compare-at-price-WB`));

            secondaryPrices.forEach((price) => {
                price.innerHTML = firstPrice.innerHTML;
            });
        });

        //Free gift under bundle cards
        const freeGiftCards = document.querySelectorAll('#wb-all-free-gifts-container .wb-gift-card-wrapper');
freeGiftCards.forEach((wrapper) => {
    const giftCard = wrapper.querySelector('.wb-gift-card');
    if (giftCard && giftCard.classList.contains('wb-gift-available')) {
        const productId = giftCard.dataset.productId;
        
        // Find the corresponding gift wrapper in the selected offer
        const giftWrapperInOffer = document.querySelector(`.selectedWB .wb-gift-product-wrapper[data-g-product-id="${productId}"]`);
        
        if (giftWrapperInOffer) {
            const sourcePrice = giftWrapperInOffer.querySelector('.gift-price-WB');
            const sourceComparePrice = giftWrapperInOffer.querySelector('.gift-compare-at-price-WB .crossed-price-WB');
            
            if (sourcePrice && sourceComparePrice) {
                const targetPrice = wrapper.querySelector('.wb-gift-price-WB');
                const targetComparePrice = wrapper.querySelector('.wb-gift-compare-at-price-WB .crossed-price-WB');
                
                if (targetPrice && targetComparePrice) {
                    targetPrice.innerHTML = sourcePrice.innerHTML;
                    targetComparePrice.innerHTML = sourceComparePrice.innerHTML;
                    
                    if (typeof handleTranscyPrice === 'function') {
                        handleTranscyPrice(sourcePrice.innerHTML, targetPrice);
                        handleTranscyPrice(sourceComparePrice.innerHTML, targetComparePrice);
                    }
                }
            }
        }
    }
});


} else {

    var variantIdSelected = variantIdsSelected[0];
    //Get prices for the selected variant
    var price = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="' + variantIdSelected + '"]').innerHTML;
    var compareAtPrice = document.querySelector('.wb_hidden_prices .wb_hidden_compared_price[variant-id="' + variantIdSelected + '"]').innerHTML;
    if(wideBundle.getAmountFromPrice(compareAtPrice) == 0){ //Sometimes because of currency converter it's $0 so we put null immediately
      compareAtPrice = "";
    }
    wideBundle.updateSavingsText(price, compareAtPrice); //Update the saving text of the offer

    for (var y = 0; y < document.querySelectorAll('.selectedWB .price-new-form span.first-price-WB').length; y++) {
        document.querySelectorAll('.selectedWB .price-new-form span.first-price-WB')[y].innerHTML = price;
        handleTranscyPrice(price, document.querySelectorAll('.selectedWB .price-new-form span.first-price-WB')[y]);
        if (document.querySelectorAll('.selectedWB .price-new-form .second-price-WB s')[y]) {
            document.querySelectorAll('.selectedWB .price-new-form .second-price-WB s')[y].innerHTML = compareAtPrice;
        }
        else {
            document.querySelectorAll('.selectedWB .price-new-form .second-price-WB')[y].innerHTML = compareAtPrice;
        }
        handleTranscyPrice(compareAtPrice, document.querySelectorAll('.selectedWB .price-new-form .second-price-WB')[y]);
    }

}
    wideBundle.updateMainPrice(); //Update price below title

    // Create and dispatch price change event
    const priceElement = document.querySelector('.selectedWB .first-price-WB');
    const compareAtPriceElement = document.querySelector('.selectedWB .second-price-WB');
    const priceAmount = priceElement ? wideBundle.getAmountFromPrice(priceElement.innerHTML) : '';
    const compareAtPriceAmount = compareAtPriceElement ? wideBundle.getAmountFromPrice(compareAtPriceElement.innerHTML) : '';
    const priceChangeEvent = new CustomEvent('widebundle:price:change', {
        detail: {
            price: priceAmount,
            compareAtPrice: compareAtPriceAmount,
            currency: Shopify.currency ? Shopify.currency.active : wideBundle.settings.currency_code
        }
    });
    document.dispatchEvent(priceChangeEvent);

}

//Update the design of the widget when there are diagonal custom messages
wideBundle.updateDiagonalOffer = function(){
    var diagonals = document.querySelectorAll('.diagonal-offer');
    for (let i = 0; i < diagonals.length; i++) {
        diagonals[i].style.height = 'auto';
        if (diagonals[i].scrollHeight > diagonals[i].clientHeight && wideBundle.settings.design_code !== '5') {
            diagonals[i].style.height = diagonals[i].scrollHeight + 'px'
        }
    } 
} 
//Handle Transcy Price when prices are different from an offer to another we have to update property data-tc-price
function handleTranscyPrice(price, element){
    if(element && element.hasAttribute('data-tc-price')){
        element.setAttribute('data-tc-price', price);
    }
}

//Update add to cart button when the price changes
document.addEventListener('widebundle:price:change', function(){
    var atcText = wideBundle.getTranslatedText(wideBundle.settings.atc_text);
    if(atcText && (atcText.includes('{{price}}') || atcText.includes('{{compare-price}}'))){
        var priceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.first-price-WB') : null;
        var comparePriceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.second-price-WB') : null;
        var price = priceEl ? priceEl.outerHTML : '';
        var comparePrice = comparePriceEl ? comparePriceEl.outerHTML : '';
        atcText = atcText.replace(/{{price}}/g, price);
        atcText = atcText.replace(/{{compare-price}}/g, comparePrice);
    }
    var content = AddSVG() + atcText;
    document.querySelectorAll('.new-form-atc').forEach(function(btn){
        btn.innerHTML = content;
    });
});

//Update the prices in savings text
wideBundle.updateSavingsText = function(price, compareAtPrice){
    if(compareAtPrice != '' && wideBundle.settings.economic_display == 1){
        var priceDifference = getAmountDifference(price, compareAtPrice)
        priceDifferenceFormatted = wideBundle.updatePriceSeparator(wideBundle.removeDecimal(wideBundle.getCurrentCurrencyOnly(price).replace('{{amount}}', priceDifference.amount)));

        for(var i = 0; i < document.querySelectorAll('.selectedWB .percent-wb').length; i++){
            document.querySelectorAll('.selectedWB .percent-wb')[i].innerHTML = priceDifference.percent;
        }
        for(var i = 0; i < document.querySelectorAll('.selectedWB .span-economic-wb').length; i++){
            document.querySelectorAll('.selectedWB .span-economic-wb')[i].innerHTML = priceDifferenceFormatted;
            handleTranscyPrice(priceDifferenceFormatted, document.querySelectorAll('.selectedWB .span-economic-wb')[i]);
        }
        for(var i = 0; i < document.querySelectorAll('.selectedWB .economic-wb').length; i++){
            economicDiv = document.querySelectorAll('.selectedWB .economic-wb')[i]
            economicDiv.style.display = "block";
            economicDiv.closest(".new-form-option").classList.add("with-economic-text");
        }
    }
    else{
        for(var i = 0; i < document.querySelectorAll('.selectedWB .economic-wb').length; i++){
            economicDiv = document.querySelectorAll('.selectedWB .economic-wb')[i]
            economicDiv.style.display = "none";
            economicDiv.closest(".new-form-option").classList.remove("with-economic-text");
        }
    }
}

//Get selected variant id
wideBundle.getSelectedVariantId = function(includeUpsell = false){
    var offerSelected = wideBundle.getSelectedOffer();
    var variants;
    var selectedOptionsGroups = wideBundle.getSelectedVariants(includeUpsell);

const variantIds = selectedOptionsGroups.flatMap((selectedOptions) => {
    if (offerSelected.automatic_discount) {
        variants = wideBundle.offers[selectedOptions.offersPointer][selectedOptions.productPointer].variants;
    } else {
        variants = offerSelected.variants;
    }

    //If we don't have any options in this offer
    if(selectedOptions.option2.length == 0){
        return [
            Number(wideBundle.activeWidget.querySelector(`.selectedWB`)?.getAttribute('data-variant-id'))
        ]; //Return the attribute data-id of the selected offer
    }

    //Associate the option 3 with the option 2 in the selected options
    var combinedSelectedOptions = [];
    for(var i = 0; i < selectedOptions.option2.length; i++){
        if(selectedOptions.option4.length > 0 && selectedOptions.option4[i]){ //If we have option 4
            combinedSelectedOptions.push(selectedOptions.option2[i].toLowerCase().trim() + ' / ' + selectedOptions.option3[i].toLowerCase().trim() + ' / ' + selectedOptions.option4[i].toLowerCase().trim());
        }
        else if(selectedOptions.option3.length > 0){ //If we have option 3
            combinedSelectedOptions.push(selectedOptions.option2[i].toLowerCase().trim() + ' / ' + selectedOptions.option3[i].toLowerCase().trim());
        }
        else{
            combinedSelectedOptions.push(selectedOptions.option2[i].toLowerCase().trim());
        }
    }

    //Associate the option 3 with option 2 in all the variants of the product
    for(var i = 0; i < variants.length; i++){
        var combinedVariants = [];
        var variant = variants[i];
        var option2 = offerSelected.automatic_discount ? variant.option2.split('|').slice(0, 1) : variant.option2.split(',');
        var option3 = variant.option3 != null ? (offerSelected.automatic_discount ? variant.option3.split('|').slice(0, 1) : variant.option3.split(',')) : [];
        var option4 = variant.option4 != null && offerSelected.automatic_discount ? variant.option4.split('|').slice(0, 1) : [];

        for(var j = 0; j < option2.length; j++){
            if (option4.length > 0 && offerSelected.automatic_discount){
                combinedVariants.push(option2[j].toLowerCase().trim() + ' / ' + option3[j].toLowerCase().trim() + ' / ' + option4[j].toLowerCase().trim());
            }
            else if(option3.length > 0){
                combinedVariants.push(option2[j].toLowerCase().trim() + ' / ' + option3[j].toLowerCase().trim());
            }
            else{
                combinedVariants.push(option2[j].toLowerCase().trim());
            }
        }
        if(arraysEqual(combinedVariants, combinedSelectedOptions)){ //If we found the variant selected
            return [Number(variant.id)];
        }
    }
    return [];
});

    return variantIds;
}

wideBundle.mapSelectedVariantsToOffers = function(includeUpsell = false) {
    const selectedVariantIds = wideBundle.getSelectedVariantId(includeUpsell);
    const selectedOffer = wideBundle.getSelectedOffer();
    const variantTypes = [];
    wideBundle.offers[selectedOffer.offersPointer].map((offer, offerIndex) => {
        const offerVariantIds = offer.variants.map(variant => Number(variant.id));
        for (let i = 0; i < offer.product_qty; i++) {
            const selectedVariant = Number(selectedVariantIds.shift());
            if (!offerVariantIds.includes(selectedVariant)) {
                console.debug(`WARN: Selected variant ${selectedVariant} not found in offer ${offerIndex} with product ID ${offer.product_id}`);
                break;
            }
            variantTypes.push({
                variantId: selectedVariant,
                productId: offer.product_id,
                productType: offer.product_is_gift ? "gift" : offer.product_is_upsell ? "upsell" : "target",
            });
        }
    });

    return variantTypes;
}

//Get offer selected
wideBundle.getSelectedOffer = function(){
    var selectedNode = wideBundle.activeWidget.querySelector('.selectedWB');
    var allNodes = wideBundle.activeWidget.querySelectorAll('.new-form-option');
    var selectedNodeIndex = Array.from(allNodes).indexOf(selectedNode);
    return { ...wideBundle.offers[selectedNodeIndex][0], offersPointer: selectedNodeIndex };
}

//Get offer selected variant
wideBundle.getSelectedVariant = function(){
    var selectedOffer = wideBundle.getSelectedOffer();
    for(var i = 0; i < selectedOffer.variants.length; i++){
        if(selectedOffer.variants[i].id == wideBundle.getSelectedVariantId()[0]){
            return selectedOffer.variants[i];
        }
    }
}

//Get variants values selected
wideBundle.getSelectedVariants = function(includeUpsell = false){
    let optionGroups = [];

    const offerProductElements = wideBundle.activeWidget.querySelectorAll('.selectedWB [data-product-id]:not(input[type="checkbox"]');
    if (offerProductElements.length === 0) {
        const offersPointer = Number(wideBundle.activeWidget.querySelector('.selectedWB')?.dataset.offersPointer);
        const selectedOffer = wideBundle.offers[offersPointer][0];

        return [{
            option1: selectedOffer.offer_title,
            option2: [],
            option3: [],
            option4: [],
            product_id: selectedOffer.product_id,
            offersPointer,
            productPointer: 0,
        }];
    }

offerProductElements.forEach((offerProductElement) => {
    const offersPointer = Number(offerProductElement.dataset.offersPointer);
    const productPointer = Number(offerProductElement.dataset.productPointer);
    const selectedOffer = wideBundle.offers[offersPointer][productPointer];
    if (selectedOffer?.product_is_upsell) {
        const upsellCheckbox = wideBundle.activeWidget.querySelector(`.wb-upsell-checkbox[data-offers-pointer="${offersPointer}"][data-product-pointer="${productPointer}"]`);
        if (!includeUpsell || (upsellCheckbox && !upsellCheckbox.checked)) {
            return; // Skip this upsell product if not selected
        }
    }

    var option2 = [];
    var option3 = [];
    var option4 = [];

    offerProductElement.querySelectorAll('.select-option-second').forEach(function(select) {
        if(select.selectedIndex > -1){
            var selectedOption = select.options[select.selectedIndex];
            option2.push(selectedOption.value);
        }
    });

    offerProductElement.querySelectorAll('.select-option-third').forEach(function(select) {
        if(select.selectedIndex > -1){
            var selectedOption = select.options[select.selectedIndex];
            option3.push(selectedOption.value);
        }
    });

    offerProductElement.querySelectorAll('.select-option-first').forEach(function (select) {
        if (select.selectedIndex > -1) {
            var selectedOption = select.options[select.selectedIndex];
            option4.push(selectedOption.value);
        }
    });

    var options = {
        option1: selectedOffer.offer_title,
        option2: option2,
        option3: option3,
        option4: option4,
        product_id: selectedOffer.product_id,
        offersPointer,
        productPointer,
    };

    if (selectedOffer.automatic_discount) {
        optionGroups.push(options);
    } else {
        if (optionGroups[0]) {
            optionGroups[0].option2 = [optionGroups[0].option2, ...option2].flat();
            optionGroups[0].option3 = [optionGroups[0].option3, ...option3].flat();
            optionGroups[0].option4 = [optionGroups[0].option4, ...option4].flat();
        } else {
            optionGroups.push(options);
        }
    }
});

    return optionGroups;
}

//Change the offer selected after we clicked on an offer
wideBundle.changeSelectedOffer = function(){
    var isAlreadySelected = this.classList.contains('selectedWB');
    var dataId = this.getAttribute('data-id');

    if(!isAlreadySelected){ //If we didn't click on an already selected offer
        var selectedOffers = document.querySelectorAll('.selectedWB');
        for(var i = 0; i < selectedOffers.length; i++){ //Remove the selected class
            selectedOffers[i].classList.remove('selectedWB');
            selectedOffers[i].classList.add('selectable');
        }
        var offerToSelect = document.querySelectorAll('.new-form-option[data-id="' + dataId + '"]');
        for(var i = 0; i < offerToSelect.length; i++){ //Add the selected class
            offerToSelect[i].classList.add('selectedWB');
            offerToSelect[i].classList.remove('selectable');
        }
        wideBundle.updateQuantityInputs(1); //Reset all the quantity inputs to 1
        wideBundle.updatePricesInOffer() //Update the prices in the offer
        wideBundle.updateProductForm(); //Update the product form with new selected offer and variants
        wideBundle.updateQuantityDisabled(1, false); //Check the out of stock system
        wideBundle.updateDiagonalOffer(); //Update the design when there is a diagonal custom text
        setupReleaseItProducts();

        var selectedElement = document.querySelector('.selectedWB');
        if (selectedElement) {
            var selectedOfferPointer = selectedElement.getAttribute('data-offers-pointer');
            
            // Update gifts display
            wideBundle.updateGiftsDisplay(selectedOfferPointer);
        }
    }
}

//Update variant selected on WideBundle based on variant parameter in url or if an offer was preselected by default
wideBundle.updateVariantSelectedInFormWithConditions = function(){
    hasVariant = new URLSearchParams(window.location.search.toLowerCase()).get('variant');
    hasPreselectedOffer = false;
    for(var i = 0; i<wideBundle.offers.length; i++){
        if(wideBundle.offers[i][0].preselected == 1){
            hasPreselectedOffer = true;
            break;
        }
    }

    if(hasVariant || hasPreselectedOffer){

        if(document.readyState == "complete"){
            wideBundle.updateProductForm();
        }
        else{
            window.addEventListener('load', function() {
                wideBundle.updateProductForm();
            });
        }
    }
}

wideBundle.getTranslatedText = function(defaultText) {
    // Check if defaultText is null or "null"
    if (defaultText && defaultText === "null") {
        return "";
    }

    // Check if Shopify.locale exists
    const locale = typeof Shopify !== 'undefined' && Shopify.locale ? Shopify.locale : null;

    if (!locale) {
        return defaultText;
    }

    // Check if translations object exists and is valid
    if (!wideBundle.settings || !wideBundle.settings.translations) {
        return defaultText;
    }

    // Decode JSON if translations are in a string format
    if (typeof wideBundle.settings.translations === 'string') {
        try {
            wideBundle.settings.translations = JSON.parse(wideBundle.settings.translations);
        } catch (error) {
            console.error("Failed to parse translations JSON:", error);
            return defaultText;
        }
    }

    /*
    we remove this handle pt-Pt local. for shopify it is 'pt', but in our settings it is pt-Pt
    // Check if translations exist for the current locale
    if (!wideBundle.settings.translations[locale]) {
        return defaultText;
    }

    const localeTranslations = wideBundle.settings.translations[locale];
    */
    let localeTranslations;
        // Check if translations exist for the current locale
    if (wideBundle.settings.translations[locale]) {
        localeTranslations = wideBundle.settings.translations[locale];
    } else {
        const targetLocale = locale;

        let matchedKey = null;
        
        // Loop through all keys
        for (const key in wideBundle.settings.translations) {
            if (!wideBundle.settings.translations.hasOwnProperty(key)) continue;
            
            // Split key on "-" and take the first part
            const base = key.split("-")[0];
            
            if (base === targetLocale) {
                matchedKey = key;
                break;
            }
        }
        
        if (matchedKey) {
            console.log("Found match:", matchedKey, wideBundle.settings.translations[matchedKey]);
            localeTranslations = wideBundle.settings.translations[matchedKey];
        } else {
            console.log("No matching locale found for:", targetLocale);
            return defaultText;
        }
    }

    // Ensure locale translations are valid and not null/empty
    if (!localeTranslations || Object.keys(localeTranslations).length === 0) {
        return defaultText;
    }

    // UTF-8 safe Base64 encoding
    const encodedText = btoa(unescape(encodeURIComponent(defaultText)));

    if (localeTranslations[encodedText]) {
        try {
            // UTF-8 safe Base64 decoding
            const decodedTranslation = decodeURIComponent(escape(atob(localeTranslations[encodedText])));
            if (decodedTranslation && decodedTranslation.trim()) {
                return decodedTranslation;
            }
        } catch (error) {
            console.error("Failed to decode translation:", error);
            return defaultText;
        }
    }

    return defaultText;
};



//Get the values of the options selected
wideBundle.getOfferValuesForVariant = function(variantId){
    for(var i = 0; i < wideBundle.offers.length; i++){
        var offer = wideBundle.offers[i][0];
        for(var j = 0; j < offer.variants.length; j++){
            var variant = offer.variants[j];
            if(variant.id == variantId){
                values = {};
                if(variant.option2){
                    if (wideBundle.isAutomaticDiscount) {
                        values.option1 = variant.option2.split("|");
                    } else {
                        values.option1 = variant.option2.split(',');
                    }
                }
                else{
                    values.option1 = [];
                }
                if(variant.option3){
                    if (wideBundle.isAutomaticDiscount) {
                        values.option2 = variant.option3.split("|");
                    } else {
                        values.option2 = variant.option3.split(',');
                    }
                }
                else{
                    values.option2 = [];
                }
                if(variant.option4){
                    if (wideBundle.isAutomaticDiscount) {
                        values.option3 = variant.option4.split("|");
                    } else {
                        values.option3 = variant.option4.split(',');
                    }
                }
                else{
                    values.option3 = [];
                }
                return values;
            }
        }
    }
    return null;
}

//Update the price under the product Title
wideBundle.updateMainPrice = function(){
    if(wideBundle.settings.update_price == 1){
        exceptionsPrices = [
            ".collection"
        ];

        wideBundle.priceInfo = wideBundle.getPriceNode();
        wideBundle.replaceSelectedPrice();
        var priceContent = document.querySelector('.selectedWB .price-new-form')?.innerHTML ?? ""; //Get the price from selected offer
        var price = wideBundle.priceInfo.element;

        formPrice:
        for(var i = 0; i < wideBundle.priceInfo.element.length; i++){
            for(var j=0; j < exceptionsPrices.length; j++){ //Check if the price is not an exception
                var exceptionAll = document.querySelectorAll(exceptionsPrices[j]);
                for(var k=0; k < exceptionAll.length; k++){
                    var exception = exceptionAll[k];
                    if(typeof exception != "undefined" && isDescendant(exception, price[i])){
                        console.log('price is descendant of an exception...');
                        continue formPrice;
                    }
                }
            }
            //price[i].innerHTML = priceContent; //Replace the content of the price under the title --OLD SYSTEM

            const firstPriceElement = price[i].querySelector('.first-price-WB');
            if (firstPriceElement) {
              firstPriceElement.remove();
            }
            const secondPriceElement = price[i].querySelector('.second-price-WB');
            if (secondPriceElement) {
              secondPriceElement.remove();
            }
            for (let y = 0; y < price[i].childNodes.length; y++) {
              const child = price[i].childNodes[y];
              if (child.nodeType === Node.ELEMENT_NODE) {
                child.style.display = 'none';
              } else if (child.nodeType === Node.TEXT_NODE) {
                child.nodeValue = '';
              }
            }
            price[i].innerHTML += priceContent;
            // --NEW SYSTEM

            if(typeof price[i].querySelector('.first-price-WB') !== 'undefined'){
                price[i].querySelector('.first-price-WB').style.color = wideBundle.settings.price_color;
            }
            if(typeof price[i].querySelector('.second-price-WB') !== 'undefined'){
                price[i].querySelector('.second-price-WB').style.color = wideBundle.settings.price_compared_color;
            }
            price[i].style.fontWeight = 'bold';
            if(price.length > 2 || wideBundle.locationWebsite.indexOf(encodeURI('products/')) == -1){
                break;
            }
        }
        for(i=0; i<document.querySelectorAll('.price-wb').length; i++){
            price = document.querySelectorAll('.price-wb')[i]; //Update also our custom prices that can be placed manually
            price.innerHTML = priceContent;
            if(typeof price[i].querySelector('.first-price-WB') !== 'undefined'){
                price[i].querySelector('.first-price-WB').style.color = wideBundle.settings.price_color;
            }
            if(typeof price[i].querySelector('.second-price-WB') !== 'undefined'){
                price[i].querySelector('.second-price-WB').style.color = wideBundle.settings.price_compared_color;
            }
            price[i].style.fontWeight = 'bold';
        }
    }
}

//Get the variants from JSON in the theme
wideBundle.getVariantsFromJson = function(variantId){
    var variantsOfProducts = "";
    if(typeof wideBundle.scriptCache != "undefined"){
        if(wideBundle.scriptCache == ""){
            return "";
        }
        if(typeof wideBundle.scriptCache[variantId] != "undefined"){
            if(typeof jsonParseScript[variantId] != "string" && jsonParseScript[variantId] != "null"){ //Weird bug where this jsonParseScript exists but inside we have the word "in" for each
                variantsOfProducts = [];
                variantsOfProducts.push(wideBundle.scriptCache[variantId]);
                return variantsOfProducts;
            }
        }
        else{
            return wideBundle.scriptCache;
        }
        return "";
    }

    if(!wideBundle.allScripts){
        var allScripts = document.querySelectorAll('script, [data-product], [id*="json"], [id*="Json"], [data-variant-json]');
        wideBundle.allScripts = allScripts;
    }
    else{
        var allScripts = wideBundle.allScripts;
    }
    outerLoop: for(var i=0; i<allScripts.length; i++){
        var script = allScripts[i];
        if(isJsonString(script.innerHTML)){ //Check if script is json and if it contains the variants
            jsonParseScript = JSON.parse(script.innerHTML);
            if(jsonParseScript != null && typeof jsonParseScript.id != "undefined" && typeof jsonParseScript.variants != "undefined"){
                if(typeof jsonParseScript.handle != "undefined" && jsonParseScript.handle != null && typeof wideBundle.currentHandle != "undefined"){
                    if(jsonParseScript.handle == wideBundle.currentHandle || encodeURI(jsonParseScript.handle) == wideBundle.currentHandle ){
                        variantsOfProducts = jsonParseScript.variants;
                        wideBundle.scriptCache = variantsOfProducts;
                        return variantsOfProducts;
                    }
                }
                else{
                    variantsOfProducts = jsonParseScript.variants;
                    break;
                }
            }
            else if(jsonParseScript != null && typeof jsonParseScript[0] != "undefined" && typeof jsonParseScript[0]["option1"] != "undefined"){
                for(var y=0; y<jsonParseScript.length; y++){
                    if(jsonParseScript[y].id == variantId){
                        variantsOfProducts = jsonParseScript;
                        wideBundle.scriptCache = jsonParseScript;
                        return variantsOfProducts;
                    }
                }
            }
            else if(jsonParseScript != null && typeof jsonParseScript[variantId] != "undefined"){
                if(typeof jsonParseScript[variantId] != "string" && jsonParseScript[variantId] != "null"){ //Weird bug where this jsonParseScript exists but inside we have the word "in" for each
                    variantsOfProducts = [];
                    variantsOfProducts.push(jsonParseScript[variantId]);
                    wideBundle.scriptCache = jsonParseScript;
                    return variantsOfProducts;
                }
            }
            else if(jsonParseScript != null && typeof jsonParseScript.product != "undefined" && jsonParseScript.product != null && jsonParseScript.product.id != "undefined" && typeof jsonParseScript.product.variants != "undefined"){
                variantsOfProducts = jsonParseScript.product.variants;
                wideBundle.scriptCache = variantsOfProducts;
                return variantsOfProducts;
            }
        }
        else if(script.getAttribute('data-product') != null && isJsonString(script.getAttribute('data-product'))){
            jsonParseScript = JSON.parse(script.getAttribute('data-product'));
            if(jsonParseScript != null && typeof jsonParseScript.id != "undefined" && typeof jsonParseScript.variants != "undefined"){
                variantsOfProducts = jsonParseScript.variants;
                wideBundle.scriptCache = variantsOfProducts;
                return variantsOfProducts;
            }
        }
    }

    if(variantsOfProducts == ""){
        if(typeof ProductJSON != "undefined" && ProductJSON.id && ProductJSON.variants){
            variantsOfProducts = ProductJSON.variants;
            wideBundle.scriptCache = variantsOfProducts;
            return variantsOfProducts;
        }
        wideBundle.scriptCache = "";
    }
    return variantsOfProducts;
}

//For customer support to get infos about the page
getInfosWB = function(){
    wideBundle.hideOrShowProductForm('show');
    console.log("%cStore Link:%c " + Shopify.shop, 'font-weight: bold;', 'font-weight: normal;');
    console.log("%cStore Theme:%c " + Shopify.theme.name, 'font-weight: bold;', 'font-weight: normal;');
    console.log("%cCurrency Selected:%c " + Shopify.currency.active + " %c& rate:%c " + Shopify.currency.rate, 'font-weight: bold;', 'font-weight: normal;', 'font-weight: bold;', 'font-weight: normal;');

    if(document.querySelector('div[data-pf-type="Body"]') && document.querySelector('div[data-pf-type="Layout"]')){
        console.log('The user is using PageFly');
        if(wideBundle.formInfo.id != "page builder"){
            console.log("%cPROBLEM: The user didn't use WideBundle Module from PageFly.", "color: red;");
        }
        else{
            console.log("%cThe user is using the WideBundle Module from PageFly.", "color: green;");
        }
    }
    else if(document.querySelector('div[data-label="Row"][data-key="row"]') && document.querySelector('html.gemapp')){
        console.log('The user is using Gempages');
        if(wideBundle.formInfo.id != "page builder"){
            console.log("%cPROBLEM: The user didn't use WideBundle Module from GemPages", "color: red;");
        }
        else{
            console.log("%cThe user is using the WideBundle Module from GemPages", "color: green;");
        }
    }
    else if(wideBundle.formInfo.id == "page builder"){
        console.log('The user is using a page builder');
    }
    else{
        console.log('The user is using a normal theme');
    }
    if(!wideBundle.getVariantsSelector()){
        console.log("%cPROBLEM: The variants selector doesn't exist or WideBundle didn't find it", "color: red;");
    }
    else{
        console.log("%cThe variants selector has been found", "color: green;");
        if(typeof wideBundle.formInfo.element != "undefined" && wideBundle.formInfo.element){
            if(wideBundle.formInfo.element.querySelector('div[data-combined="true"][data-pf-type="ProductVariantSwatches"]') != null){
                console.log("%cThe user is probably using the first variants selector from PageFly that doesn't work", "color: red;");
            }
        }
    }
    if(!wideBundle.getAddToCartButton()){
        console.log("%cPROBLEM: The Add to cart button doesn't exist or WideBundle didn't find it", "color: red;");
    }
    else{
        console.log("%cThe Add to cart button has been found", "color: green;");
    }
    if(wideBundle.settings.link_choice == "form"){
        console.log("WideBundle is configured to open the side cart");
    }
    else if(wideBundle.settings.link_choice == "cart"){
        console.log("WideBundle is configured to open the cart page");
    }
    else{
        console.log("WideBundle is configured to open the checkout");
    }
}

//Run Weglot translation
wideBundle.runTranslationApps = function(){
  if (typeof Weglot !== 'undefined') {
      if (Weglot.initialize && Weglot.options.dynamics) {
          Weglot.options.dynamics.push({ value: "#new-form" }, { value: ".new-wb-form" });
      } else {
          Weglot.initialize( {
              api_key: Weglot.options.api_key,
              dynamic: "#new-form, .new-wb-form"
          });
      }
  }
}

//Create an error on the widget
wideBundle.createError = function(message, link = null){
    var elementsToRemove = document.getElementsByClassName('widebundle_error'); // Remove current errors
    for (var i = elementsToRemove.length - 1; i >= 0; i--) {
      elementsToRemove[i].parentNode.removeChild(elementsToRemove[i]);
    }
  
    for(var i = 0 ; i <wideBundle.widgetContainers.length; i++){ //Add the error in every container
      var container = wideBundle.widgetContainers[i];
      var newError = document.createElement('p');
      var svg = `<svg xmlns="http://www.w3.org/2000/svg" height="15" width="15" viewBox="0 0 1000 1000" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#cc0000">
      <metadata>IcoFont Icons</metadata>
      <title>warning-alt</title>
      <glyph glyph-name="warning-alt" unicode="&#xf025;" horiz-adv-x="1000" />
      <path d="M500 62.5c-241.5 0-437.5 196-437.5 437.5s196 437.5 437.5 437.5c241.79999999999995 0 437.5-196 437.5-437.5s-195.70000000000005-437.5-437.5-437.5z m65.5 644.9c0 36.700000000000045-27.100000000000023 65.5-65.5 65.5s-65.10000000000002-28.699999999999932-65.10000000000002-65.5v-1.6999999999999318c0-36.700000000000045 26.700000000000045-65.10000000000002 65.10000000000002-65.10000000000002 38.39999999999998 0 65.5 28.399999999999977 65.5 65.10000000000002v1.6999999999999318z m-30.100000000000023-151.29999999999995c-2.2999999999999545 20.699999999999932-16 33.69999999999993-35.39999999999998 33.69999999999993-19 0-33.10000000000002-13-35.39999999999998-33.69999999999993l-33.10000000000002-288.90000000000003c-2-22.399999999999977 10-40.099999999999994 30.69999999999999-40.099999999999994h75.50000000000006c20.699999999999932 0 33.09999999999991 17.700000000000017 30.699999999999932 40.099999999999994l-33 288.90000000000003z"/>
      </svg>`;
      if(link){
        newError.innerHTML += svg + " " + message + ` <a target='_blank' href='${link}'>Click here for the tutorial</a>`;
      }
      else{
        newError.innerHTML += svg + " " + message;
      }
      newError.className = "widebundle_error";
      container.append(newError);
      (function(newError) {
        setTimeout(function() {
            newError.classList.add('visible');
        }, 50);
      })(newError);
    }
}

//Apply values to inputs when the user uses swatches on WB
wideBundle.mergeSwatch = function(radio) {
    // Get the product container
    let productContainer = radio.closest('[data-product-id]');
    
    // Update the select within the same product
    let select = productContainer.querySelector('#swatch-' + radio.dataset.variantid + '-select-' + radio.dataset.swatchid + '-' + radio.dataset.dropdownid + '--' + radio.dataset.productid);
    select.value = radio.value;

    // Only update radios within the same product
    let escapedValue = wbEscapeSwatchValue(radio.value);
    let radios = productContainer.querySelectorAll(`.swatch-${radio.dataset.variantid}-radio-${radio.dataset.dropdownid}[value="${escapedValue}"]`);
    radios.forEach(function(element) {
        if(element !== radio) {
            element.checked = true;
        }
    });

    var event = new Event('change');
    select.dispatchEvent(event);
}

//System to simplify the text of the colors (used to store colors)
wideBundle.simplifyColor = function(color) {
    return color.split('(').find(Boolean).trim().toLowerCase()
        .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
        .replace(":", "")
        .replace("\\", "")
        .replace("/", "")
        .replace(":", "")
        .replace("*", "")
        .replace("?", "")
        .replace("\"", "")
        .replace("<", "")
        .replace(">", "")
        .replace("|", "")
        .replace(" ", "")
        .replace("-", "")
        .replace("_", "");
}

wideBundle.calcOptionsAvailability = function(selectedOptions, productOptions, _productVariants) {
    const productVariants = _productVariants.map((_productVariant) => {
        return {
            ..._productVariant,
            option2: (_productVariant?.option2 && _productVariant?.option2 !== null) ? _productVariant.option2.split('|')[0] : null,
            option3: (_productVariant?.option3 && _productVariant?.option3 !== null) ? _productVariant.option3.split('|')[0] : null,
            option4: (_productVariant?.option4 && _productVariant?.option4 !== null) ? _productVariant.option4.split('|')[0] : null,
        };
    });
    const maxDepth = productOptions.length - 1;
    let availability = [];

    for (let depth = 0; depth <= maxDepth; depth++) {
        switch (depth) {
            case 0:
                availability[depth] = productOptions[depth].map((value) => {
                    return productVariants.findIndex((variant) => {
                        return variant.option2 === value;
                    }) !== -1;
                });
                break;

            case 1:
                availability[depth] = productOptions[depth].map((value) => {
                    return productVariants.findIndex((variant) => {
                        return variant.option2 === selectedOptions[depth - 1]
                        && variant.option3 === value;
                    }) !== -1;
                });
                break;

            case 2:
                availability[depth] = productOptions[depth].map((value) => {
                    return productVariants.findIndex((variant) => {
                        return variant.option2 === selectedOptions[depth - 2]
                        && variant.option3 === selectedOptions[depth - 1]
                        && variant.option4 === value;
                    }) !== -1;
                });
                break;
        }
    }

    return availability;
}

function setupReleaseItProducts() {
    // Add CSS rule to handle visibility
    if (!document.getElementById('wide-bundle-rsi-styles')) {
      const styleSheet = document.createElement('style');
      styleSheet.id = 'wide-bundle-rsi-styles';
      styleSheet.textContent = `
        #new-form:has(.new-form-atc--out-of-stock) ._rsi-buy-now-button {
          display: none !important;
        }
        #new-form:not(:has(.new-form-atc--out-of-stock)) ._rsi-buy-now-button {
          display: block !important;
        }
      `;
      document.head.appendChild(styleSheet);
    }
  
    // Rest of the product setup logic
    if (!window.wideBundle?.isAutomaticDiscount || !window._rsi) {
      return false;
    }
  
    try {
      const variantIds = wideBundle.getSelectedVariantId();
      
      if (!Array.isArray(variantIds) || variantIds.length === 0) {
        return false;
      }
  
      const variantCounts = variantIds.reduce((acc, id) => {
        acc[id] = (acc[id] || 0) + 1;
        return acc;
      }, {});
  
      const formattedProducts = Object.entries(variantCounts).map(([id, quantity]) => ({
        id: String(id),
        quantity: quantity
      }));
  
      window._RSI_COD_FORM_OVERWRITE_ATC_ITEMS = formattedProducts;
      return true;
    } catch (error) {
      console.error('Error setting up ReleaseIt products:', error);
      return false;
    }
  }

wideBundle.checkSelectsAvailability = function(event) {
    wideBundle._lastActiveWidget = event.target.closest('.new-wb-form,#new-form');

    if (!wideBundle.isAutomaticDiscount) {
        wideBundle.updatePricesInOffer();
        wideBundle.updateSelectsInOffers(event.target);
        wideBundle.updateProductForm();
        wideBundle.updateQuantityDisabled();
        return;
    }

    let selectsParent = event.target.closest(".has-double-select,.div-select2");
    if (!selectsParent) return;

    const parentId = selectsParent.getAttribute("id");
    const offersPointer = Number(selectsParent.dataset.offersPointer);
    const productPointer = Number(selectsParent.dataset.productPointer);
    const selectedOffer = wideBundle.offers[offersPointer][productPointer];
    let currentSelects = selectsParent.querySelectorAll(`select[name^="Variants"]`);
    const maxDepth = selectedOffer.options_number - 1;
    let selectedOptions = [currentSelects[0].value];
    if (maxDepth > 0 && currentSelects?.[1]) selectedOptions.push(currentSelects[1].value);
    if (maxDepth > 1 && currentSelects?.[2]) selectedOptions.push(currentSelects[2].value);

    let optionAvailability = wideBundle.calcOptionsAvailability(
        selectedOptions,
        [
            selectedOffer.option2_values,
            selectedOffer.option3_values,
            selectedOffer.option4_values,
        ],
        selectedOffer.variants,
    );
    let selectedVariant = selectedOffer.variants.find((variant) => {
        return (variant.option2.split('|')[0] === selectedOptions[0])
            && (selectedOptions[1] ? variant.option3.split('|')[0] === selectedOptions[1] : true)
            && (selectedOptions[2] ? variant.option4.split('|')[0] === selectedOptions[2] : true);
    });

    if (!selectedVariant) {
        let candidates = [];
        selectedOffer.variants.forEach((variant) => {
            let distance = 0;
            if (selectedOptions?.[0] && selectedOptions?.[0] !== variant.option2.split('|')[0]) {
                distance += 3;
            } else {
                distance += 0.3;
            }

            if (selectedOptions?.[1] && selectedOptions?.[1] !== variant.option3.split('|')[0]) {
                distance += 2;
            } else {
                distance += 0.2;
            }

            if (selectedOptions?.[2] && selectedOptions?.[2] !== variant.option4.split('|')[0]) {
                distance += 1;
            } else {
                distance += 0.1;
            }

            candidates.push({
                distance,
                options: [
                    variant?.option2 ? variant?.option2.split('|')[0] : null,
                    variant?.option3 ? variant?.option3.split('|')[0] : null,
                    variant?.option4 ? variant?.option4.split('|')[0] : null,
                ].slice(0, maxDepth + 1),
            });
        });
        candidates = candidates.filter((candidate) => {
            return selectedOptions?.[0] && selectedOptions?.[0] === candidate.options?.[0];
        });
        candidates.sort((a, b) => a.distance - b.distance);
        if (candidates.length === 0) return;

        const candidate = candidates[0];
        selectedVariant = selectedOffer.variants.find((variant) => {
            return (variant.option2.split('|')[0] === candidate.options[0])
                && (candidate.options[1] ? variant.option3.split('|')[0] === candidate.options[1] : true)
                && (candidate.options[2] ? variant.option4.split('|')[0] === candidate.options[2] : true);
        });
        selectedOptions = candidate.options;
        optionAvailability = wideBundle.calcOptionsAvailability(
            selectedOptions,
            [
                selectedOffer.option2_values,
                selectedOffer.option3_values,
                selectedOffer.option4_values,
            ],
            selectedOffer.variants,
        );
    }

    for(var j=0; j<wideBundle.widgetContainers.length; j++){
        const widebundleContainer = wideBundle.widgetContainers[j];
        selectsParent = widebundleContainer.querySelector(`.selectedWB #${parentId}`);
        currentSelects = selectsParent.querySelectorAll(`select[name^="Variants"]`);
        const currentSwatches = selectsParent.querySelectorAll(`select[name^="Variants"] ~ .wb-color-swatch-box [type="radio"]`);
        Array.from(currentSelects).forEach((currentSelect, currentDepth) => {
            Array.from(currentSelect.options).forEach((currentOption, currentOptionIndex) => {
                currentOption.disabled = !optionAvailability[currentDepth][currentOptionIndex];
            });

            currentSelect.value = selectedOptions[currentDepth];
        });
        Array.from(currentSwatches).forEach((currentSwatch) => {
            const matchingSelect = selectsParent.querySelector(`#swatch-${currentSwatch.dataset.variantid}-select-${currentSwatch.dataset.swatchid}-${currentSwatch.dataset.dropdownid}--${currentSwatch.dataset.productid}`);
            if (matchingSelect) {
                let currentDepth = parseInt(currentSwatch.dataset.variantid) - 2;
                if (currentDepth < 0) currentDepth = 2;
                const currentOptionIndex = parseInt(currentSwatch.dataset.k);
                currentSwatch.checked = currentSwatch.value === matchingSelect.value;
                currentSwatch.disabled = !optionAvailability[currentDepth][currentOptionIndex];
            }
        });

        if (selectedOffer.product_handle === wideBundle.currentHandle || encodeURI(selectedOffer.product_handle) === wideBundle.currentHandle ) {
            const offersWrapper = selectsParent.closest('.selectedWB');
            const parents = offersWrapper.querySelectorAll('.has-double-select,.div-select2');
            parents.forEach((parent) => {
                if (parent.getAttribute('id') === selectsParent.getAttribute('id')) {
                    parent.setAttribute('data-last-selected-target', selectedVariant.id);
                } else {
                    parent.removeAttribute('data-last-selected-target');
                }
            });
        }
    }

    setTimeout(() => {
        wideBundle.updatePricesInOffer();
        wideBundle.updateSelectsInOffers(event.target);
        wideBundle.updateProductForm();
        wideBundle.updateQuantityDisabled(1, false);
        setupReleaseItProducts();
    }, 0);
}

wideBundle.initDynamicGroups = function() {
    wideBundle.dynamicGroupsCache = {
        products: {},
        collections: {},
    };
}

wideBundle.getGiftVariantIds = function(offersPointer = -1) {
    let selectedOffer = null;
    try {
        if (offersPointer > -1) {
            selectedOffer = wideBundle.offers[offersPointer][0];
        } else {
            selectedOffer = wideBundle.getSelectedOffer();
        }
    } catch (_) {
        selectedOffer = wideBundle.offers[0][0];
    }
    if (!selectedOffer || !selectedOffer.automatic_discount) {
        return [];
    }

    const offerGroups = wideBundle.offers[selectedOffer.offersPointer];
    const giftProductOffers = offerGroups.filter((offer) => Boolean(offer?.product_is_gift));
    const variantIds = new Set();
    giftProductOffers.forEach((offer) => {
        offer.variants.forEach((variant) => {
            variantIds.add(parseInt(variant.id));
        });
    });

    return Array.from(variantIds);
}

wideBundle.getUpsellVariantIds = function(offersPointer = -1) {
    let selectedOffer = null;
    try {
        if (offersPointer > -1) {
            selectedOffer = wideBundle.offers[offersPointer][0];
        } else {
            selectedOffer = wideBundle.getSelectedOffer();
        }
    } catch (_) {
        selectedOffer = wideBundle.offers[0][0];
    }
    if (!selectedOffer || !selectedOffer.automatic_discount) {
        return [];
    }

    const offerGroups = wideBundle.offers[selectedOffer.offersPointer];
    const upsellProductOffers = offerGroups.filter((offer) => Boolean(offer?.product_is_upsell));
    const variantIds = new Set();
    upsellProductOffers.forEach((offer) => {
        offer.variants.forEach((variant) => {
            variantIds.add(parseInt(variant.id));
        });
    });

    return Array.from(variantIds);
}

wideBundle.getOfferWithTargetProduct = function() {
    let offerWithTargetProduct;            
    let productHandleOnPage = wideBundle.currentHandle;
       wideBundle.offers.forEach((offerGroup) => {
        offerGroup.forEach((offer) => {
            let productHandleInDB = offer.product_handle;
            let encodedProductHandleInDB = encodeURI(productHandleInDB);
            if (productHandleInDB == productHandleOnPage || encodedProductHandleInDB == productHandleOnPage) {
                offerWithTargetProduct = offer;
            } 
        });
    });
    return offerWithTargetProduct;
}

wideBundle.updateFormHiddenIds = function(desiredForm) {
    const selectedOffer = wideBundle.getSelectedOffer();
    const offerGroup = wideBundle.offers[selectedOffer.offersPointer];
    const offerIsAutomaticDiscount = selectedOffer.automatic_discount;
    if (!offerIsAutomaticDiscount) return;

    const formNodes = [];
    const addToCartButton = wideBundle.getAddToCartButton()?.element;
    const atcForm = addToCartButton?.closest("form");
    const primaryForm = desiredForm || wideBundle.getFormNode()?.element;
    if (atcForm) formNodes.push(atcForm);
    if (primaryForm) formNodes.push(primaryForm);

    formNodes.forEach((formNode) => {
        let hiddenExcludeOffers = formNode.querySelector(`input[type="hidden"][name="properties[__wide-bundle-excl-offers]"]`);
        if (wideBundle.abTestExcludeOffers.length > 0) {
            if (!hiddenExcludeOffers) {
                hiddenExcludeOffers = document.createElement("input");
                hiddenExcludeOffers.type = "hidden";
                hiddenExcludeOffers.name = "properties[__wide-bundle-excl-offers]";
                formNode.appendChild(hiddenExcludeOffers);
            }
            hiddenExcludeOffers.value = wideBundle.abTestExcludeOffers.join(",");
        } else if (hiddenExcludeOffers) {
            hiddenExcludeOffers.remove();
        }
    
        let hiddenTestVariant = formNode.querySelector(`input[type="hidden"][name="properties[__wide-bundle-variant]"]`);
        if (!hiddenTestVariant) {
            hiddenTestVariant = document.createElement("input");
            hiddenTestVariant.type = "hidden";
            hiddenTestVariant.name = "properties[__wide-bundle-variant]";
            formNode.appendChild(hiddenTestVariant);
        }
        const abTestVariant = wideBundle.abTestEnabled ? wideBundle.retrieveAbTestVariant() : 'A';
        hiddenTestVariant.value = `${abTestVariant}:${offerGroup[0].offer_db_id}:${offerGroup[0].index}`;

        if (offerGroup[0].user_text_enabled) {
            const userTextInput = wideBundle.activeWidget.querySelector(".selectedWB .input-user-text");
            let hiddenUserTextProperty = formNode.querySelector(`input[type="hidden"][name="properties[${CSS.escape(offerGroup[0].user_text_property)}]"]`);
            if (userTextInput && offerGroup[0].user_text_required && !userTextInput.checkValidity()) {
                // Validation error is handled in addToCart
                hiddenUserTextProperty?.remove();
            } else if (userTextInput) {
                if (!hiddenUserTextProperty) {
                    hiddenUserTextProperty = document.createElement("input");
                    hiddenUserTextProperty.type = "hidden";
                    hiddenUserTextProperty.name = `properties[${offerGroup[0].user_text_property}]`;
                    formNode.appendChild(hiddenUserTextProperty);
                }
                hiddenUserTextProperty.value = userTextInput.value.trim();
            }
        }
    });
}

//Function to update the product form
wideBundle.updateProductForm = function(){
    const offerIsAutomaticDiscount = wideBundle.getSelectedOffer().automatic_discount;
    const selectedVariants = wideBundle.getSelectedVariantId();
    const selectedVariantId = selectedVariants[0];
    var variantToSelect = wideBundle.getVariantToSelectFromDb(selectedVariantId);
    wideBundle.variantsSelector = wideBundle.getVariantsSelector(); //Get the variants selector with type + ID
    if (!wideBundle.variantsSelector) {
        if (offerIsAutomaticDiscount) {
            wideBundle.updateFormHiddenIds();
        }
        return;
    }
    const offerWithTargetProduct = wideBundle.getOfferWithTargetProduct();
    if (offerIsAutomaticDiscount && offerWithTargetProduct) {
        const lastSelectedTarget = wideBundle.activeWidget.querySelector('.selectedWB [data-last-selected-target]');
        if (lastSelectedTarget) {
            variantToSelect = offerWithTargetProduct.variants.find((variant) => variant.id == Number(lastSelectedTarget.getAttribute('data-last-selected-target')));
        } else {
            variantToSelect = offerWithTargetProduct.variants.find((variant) => selectedVariants.includes(variant.id));
        }
    }
    if (!variantToSelect) return;

    for(var j=0; j<wideBundle.widgetContainers.length; j++){ //We will update the form for each container if the main or secondary widget has a form and variants selector
      var widebundleContainer = wideBundle.widgetContainers[j];
      isMainForm = widebundleContainer.id == "new-form" ? 1 : 0; //Test if it's the main widget or the secondary one

      var parentForm = getClosestParentForm(widebundleContainer); //if the container has a form as parent (it means usually they are on page builder)
      variantsSelectorToUpdate = parentForm
        ? wideBundle.getVariantsSelector(parentForm) // We get the variants selector close to the widget (whether it's the main or secondary)
        : wideBundle.variantsSelector; // Otherwise we get the variants selector on the page without worrying about the form

      if(parentForm || isMainForm){ //If we found a form as a parent (page builder) or if it's the main widget we run that system

        if(!variantsSelectorToUpdate && isMainForm){
          console.error("WideBundle didn't find the variants selector on the page");
          return;
        }
        var numberOfOptions;
        if (offerIsAutomaticDiscount) {
            numberOfOptions = (variantToSelect.option4 != null) ? 3 : (variantToSelect.option3 != null) ? 2 : 1;
        } else {
            numberOfOptions = (variantToSelect.option3 != null) ? 3 : (variantToSelect.option2 != null) ? 2 : 1;
        }

        for(var i = 0; i<numberOfOptions; i++){ //For each option
            var optionNumber = i+1; //Option we are currently checking (option 1, option 2 or option 3)
            if (offerIsAutomaticDiscount) {
                optionNumber += 1; // Shift option number for automatic discounts to exclude static Offer option
            }
            var optionValue = variantToSelect[`option${optionNumber}`].toLowerCase();
            if (offerIsAutomaticDiscount) {
                optionValue = optionValue?.toString()?.split("|")?.[0];
            }
            var valuesToTest = [ //Values we will test to select the right variant
                optionValue, //Value from the database
                selectedVariantId, //Variant ID
                wideBundle.getVariantToSelectFromJson(selectedVariantId)[`option${optionNumber}`]?.toLowerCase() ?? '', //Value from the JSON
                wideBundle.getVariantToSelectFromOffer().toLowerCase() //Value from the offer widget
            ];

            // Add translated value(s) for both variant-based bundles and automatic discounts
            if (variantToSelect[`option${optionNumber}`]) {
                const originalValue = variantToSelect[`option${optionNumber}`];
                
                if (!offerIsAutomaticDiscount && originalValue.includes(',')) {
                    // Handle comma-separated values (variant-based bundles only)
                    const optionValues = originalValue.split(',');
                    let hasTranslation = false;
                    const translatedValues = optionValues.map(value => {
                        const trimmedValue = value.trim();
                        const translated = wideBundle.getTranslatedText(trimmedValue);
                        if (translated !== trimmedValue) {
                            hasTranslation = true;
                        }
                        return translated || trimmedValue;
                    });
                    
                    if (hasTranslation) {
                        const translatedCommaString = translatedValues.join(',').toLowerCase();
                        valuesToTest.push(translatedCommaString);
                    }
                } else {
                    // Handle single value for:
                    // - variant-based bundles without commas
                    // - automatic discounts (always single value)
                    const translated = wideBundle.getTranslatedText(originalValue);
                    if (translated !== originalValue) {
                        valuesToTest.push(translated.toLowerCase());
                    }
                }
            }

            if (offerIsAutomaticDiscount && !offerWithTargetProduct) {
                break;
            }
            if(variantsSelectorToUpdate.type == "fieldset" && variantsSelectorToUpdate.element.length > 0){ //If we have a fieldset
                console.log("fieldsets");
                var element = variantsSelectorToUpdate.element[i];
                console.log(element);
                if(!element && isMainForm){
                  console.error("WideBundle tried to update the variants selector but didn't find them all (Maybe the store uses swatch colors OR use a single variants selector that contains all the variants)");
                  break;
                }
                if (element.querySelector('select')) { //If fieldsets are <select>
                    console.log("fieldsets selects");
                    wideBundle.updateSelect(element.querySelector('select'), valuesToTest);
                } else if (element.querySelector('button')) { //If fieldsets are <button>
                    console.log("fieldsets buttons");
                    wideBundle.updateButton(element, valuesToTest);
                } else if (element.querySelector('input')) { //If fieldsets are <input>
                    console.log("fieldsets inputs");
                    wideBundle.updateInput(element, valuesToTest);
                } else if (element.querySelector('span')) { //If fieldsets are <span>
                    console.log("fieldsets are spans");
                    wideBundle.updateSpan(element, valuesToTest);
                }
            }
            else if(variantsSelectorToUpdate.type == "swatch" && variantsSelectorToUpdate.element.length > 0){ //If we have a swatch
                console.log("swatchs");
                var element = variantsSelectorToUpdate.element[i];
                console.log(element);
                if(!element && isMainForm){
                    if(wideBundle.variantsSelector?.id != "div[data-replo-variant-select]"){ //Because Replo page builder always has a single variants selector
                        console.error("WideBundle tried to update the variants selector but didn't find them all (Maybe the store uses swatch colors OR use a single variants selector that contains all the variants)");
                        break;
                    }
                    else{
                        break;
                    }
                }
                const divElements = [
                    ".product-options__value", ".product-option-item", ".button-hero.w-commerce-commerceaddtocartoptionpill",
                    ".t4s-swatch__item", '.disclosure--option-link', ".option-item .option-item-inner [option-value]", ".option-item div", "div[data-replo-set-active-variant]"
                ];
                if (element.querySelector('a')) { //If swatchs are <a>
                    console.log("swatchs a");
                    wideBundle.updateA(element, valuesToTest);
                } else if (element.querySelector('li')) { //If swatchs are <li>
                    console.log("swatchs li");
                    wideBundle.updateLi(element, valuesToTest);
                } else if(element.querySelector('select')){ //If swatchs are <selects>
                    console.log("swatchs select");
                    wideBundle.updateSelect(element.querySelector('select'), valuesToTest);
                }
                for(var j = 0; j<divElements.length; j++){ //Testing the divs if we have to update divs
                    if(element.querySelector(divElements[j])){
                        console.log("swatchs div");
                        wideBundle.updateDiv(element, valuesToTest, divElements[j]);
                        break;
                    }
                }
            }
            else if(variantsSelectorToUpdate.type == "select" && variantsSelectorToUpdate.element.length > 0){ //If we have a select
                console.log("selects");
                var element = variantsSelectorToUpdate.element[i];
                console.log(element);
                if(!element){
                    if(wideBundle.variantsSelector?.id != "div[data-replo-variant-select]"){ //Because Replo page builder always has a single variants selector
                        console.error("WideBundle tried to update the variants selector but didn't find them all (Maybe the store uses swatch colors OR use a single variants selector that contains all the variants)");
                        break;
                    }
                    else{
                        break;
                    }
                }
                wideBundle.updateSelect(element, valuesToTest);
            }

            wideBundle.variantsSelector = wideBundle.getVariantsSelector(); //For form that regenerates the variants selector
            variantsSelectorToUpdate = parentForm
            ? wideBundle.getVariantsSelector(parentForm) 
            : wideBundle.variantsSelector;
            
        }

        if (offerIsAutomaticDiscount) {
            wideBundle.updateFormHiddenIds();
        }

        wideBundle.fireAllChangeEvent();
      }
    }

    wideBundle.manageSelectedVariantForDynamicButton(); //To update the selected variant ID if the user uses dynamic buttons
}

//Function to get the variant we need to select in the product form based on selected offer in WideBundle
wideBundle.getVariantToSelectFromDb = function(variantId){
    var offerSelected = wideBundle.getSelectedOffer();
    for(var i = 0; i<offerSelected.variants.length; i++){
        var variant = offerSelected.variants[i];
        if(variant.id == variantId){
            return variant;
        }
    }
}

//Function to get variant option values from JSON
wideBundle.getVariantToSelectFromJson = function(variantId) { // IMPORTANT: Can also get from the select name id
    const variantsOfProducts = wideBundle.getVariantsFromJson(variantId);
    if (variantsOfProducts == "") {
      return {option1: null, option2: null, option3: null};
    }
    for (const variant of variantsOfProducts) {
        if (variant.id == variantId) {
            if (typeof variant.option1 != "undefined") {
                return {option1: variant.option1, option2: variant.option2, option3: variant.option3};
            } else if (typeof variant.public_title != "undefined") {
                const values = variant.public_title.split("/");
                const options = {option1: values[0].trim(), option2: null, option3: null};
                if (values.length > 1) {
                    options.option2 = values[1].trim();
                }
                if (values.length > 2) {
                    options.option3 = values[2].trim();
                }
                return options;
            }
        }
    }
    return {option1: null, option2: null, option3: null};
}

//Function to get offer name from the offer widget - We only get offer name for the moment but we might need to
wideBundle.getVariantToSelectFromOffer = function() {
    offerName = document.querySelector('#new-form .selectedWB .title-variant').innerText;
    if(!offerName){
      return null;
    }

    return offerName.toLowerCase();
}

//Function to update a <select> value
wideBundle.updateSelect = function(element, valuesToTest) {
    if(typeof element == "undefined"){ return; };

    const options = element.options;
    for (const valueToTest of valuesToTest) {
        for (let i = 0; i < options.length; i++) {
            if (options[i].value.toLowerCase() == valueToTest 
                    || options[i].innerText.toLowerCase() == valueToTest
                    || options[i].innerText.toLowerCase().trim() == valueToTest
                ) {
                options[i].selected = true;
                options[i].setAttribute("selected", "selected")
                //Change start
                //check if the element is a shogun selector
                let isShogunSelector = element.classList.contains(
                "shg-product-variant-select"
                );
                //don't fire change event if the element is a shogun selector
                if (!isShogunSelector) {
                fireChangeEvent(element);
                }
                //change end
                //For Replo Page Builder
                if(element.hasAttribute('data-replo-repeated-index')){
                    if ('createEvent' in document) {
                        var evt = document.createEvent('HTMLEvents');
                        evt.initEvent('change', true, true);
                        element.dispatchEvent(evt);
                    } else {
                        element.fireEvent('onchange');
                    }
                }

                return;
            } else {
                options[i].removeAttribute("selected")
            }
        }
    }
}

//Function to click on <button> to select variants
wideBundle.updateButton = function (element, valuesToTest) {
    let selectorsToCheck = [
      ".Popover__Value",
      ".combo-box__option-item",
      ".popover-listbox__option",
      "a.select-popout__option",
      "x-popover x-listbox[data-option-selector] button"
    ];
    let elementsToClick;
    for (let i = 0; i < selectorsToCheck.length; i++) {
      elementsToClick = element.querySelectorAll(selectorsToCheck[i]);
      if (elementsToClick.length > 0) {
        break;
      }
    }
  
    if (elementsToClick.length) {
      for (const valueToTest of valuesToTest) {
        for (let i = 0; i < elementsToClick.length; i++) {
          if (
            elementsToClick[i].innerHTML?.toLowerCase() == valueToTest ||
            elementsToClick[i].value?.toLowerCase() == valueToTest ||
            elementsToClick[i].getAttribute("data-value")?.toLowerCase() == valueToTest
          ) {
            elementsToClick[i].disabled = false; //Enable buttons for some themes with troubles
            elementsToClick[i].click();
            elementsToClick[i].click(); // Double click for some themes with troubles
            return;
          }
        }
      }
      return;
    }
  }

//Function to change selected <input>
wideBundle.updateInput = function(element, valuesToTest) {
    console.log("updating the inputs");
    inputs = element.querySelectorAll('input');
    for (const valueToTest of valuesToTest) {
        for (let i = 0; i < inputs.length; i++) {
            if (inputs[i].value.toLowerCase() == valueToTest ||
                (inputs[i].hasAttribute('data-value') && inputs[i].getAttribute('data-value').toLowerCase() == encodeURI(valueToTest)) ||
                (inputs[i].hasAttribute('data-value') && inputs[i].getAttribute('data-value').toLowerCase() == valueToTest) 
            ) {
                    inputs[i].disabled = false; //Enable inputs for some themes with troubles
                    inputs[i].click();
                    inputs[i].click(); // Double click for some themes with troubles
                    if(wideBundle.variantsSelector.id == ".product-options--swatches .swatches--offer .swatches__options"){
                        fireChangeEvent(inputs[i]);
                    }
                    return;
            }
        }
    }
}

//Function to change selected <span>
wideBundle.updateSpan = function(element, valuesToTest) {
    console.log("updating the spans");
    spans = element.querySelectorAll('span');
    for (const valueToTest of valuesToTest) {
        for (let i = 0; i < spans.length; i++) {
            if (spans[i].hasAttribute("data-value") && spans[i].getAttribute("data-value").toLowerCase() == valueToTest) {
                spans[i].click();
                spans[i].click(); // Double click for some themes with troubles
                return;
            }
            else if(spans[i].hasAttribute("data-swatch-option") && spans[i].getAttribute("data-swatch-option").toLowerCase() == valueToTest
                    && !spans[i].classList.contains('swatch--active')){
              spans[i].click();
              return;
            }
        }
    }
}

//Function to change selected <a>
wideBundle.updateA = function(element, valuesToTest) {
    console.log("updating the a");
    as = element.querySelectorAll('a');
    for (const valueToTest of valuesToTest) {
        for (let i = 0; i < as.length; i++) {
            if ((as[i].hasAttribute("data-value") && as[i].getAttribute("data-value").toLowerCase() == valueToTest) ||
                as[i].innerText.toLowerCase() == valueToTest) {
                if(wideBundle.variantsSelector.id != ".product__selectors .select-popout__list" &&
                    wideBundle.variantsSelector.id != "fieldset.select__fieldset .select-popout"){
                        as[i].href = 'javascript:void(0);';
                }
                as[i].click();
                as[i].click(); // Double click for some themes with troubles
                return;
            }
        }
    }
}

//Function to change selected <li>
wideBundle.updateLi = function(element, valuesToTest) {
    console.log("updating the li");
    lis = element.querySelectorAll('li');
    for (const valueToTest of valuesToTest) {
        for (let i = 0; i < lis.length; i++) {
            if ((lis[i].hasAttribute("data-escape") && lis[i].getAttribute("data-escape").toLowerCase() == valueToTest) ||
                lis[i].innerText.toLowerCase() == valueToTest ||
                (lis[i].hasAttribute("value") && lis[i].getAttribute("value").toLowerCase() == valueToTest) ||
                (lis[i].hasAttribute("data-value") && lis[i].getAttribute("data-value").toLowerCase() == valueToTest)) {
                    lis[i].click();
                    lis[i].click(); // Double click for some themes with troubles
                    triggerMouseEvent(lis[i], "mousedown");
                    return;
            }
        }
    }
}

//Function change selected <div>
wideBundle.updateDiv = function(element, valuesToTest, divElement) {
    console.log("updating the div");
    valuesToTest = valuesToTest.map(val => {
        let returnValue = val;
        if(typeof val == "number"){
            returnValue = val.toString()            
        } 
        return returnValue;
    })
    divs = element.querySelectorAll(divElement);
    for (const valueToTest of valuesToTest) {
        for (let i = 0; i < divs.length; i++) {
            if (divs[i].innerHTML.toLowerCase().trim() == valueToTest.replace(/&/g, "&amp;").trim()) {
                divs[i].click();
                divs[i].click(); // Double click for some themes with troubles
                dispatchClick(divs[i]);
                return;
            }
            else if (divs[i].innerText.toLowerCase().trim() == valueToTest.replace(/&/g, "&amp;").trim()) {
                divs[i].click();
                divs[i].click(); // Double click for some themes with troubles
                dispatchClick(divs[i]);
                return;
            }
            else if (divs[i].innerText.toLowerCase().replace(/&/g, "&amp;").trim() == valueToTest.replace(/&/g, "&amp;").trim()) {
                divs[i].click();
                divs[i].click(); // Double click for some themes with troubles
                dispatchClick(divs[i]);
                return;
            }
            else if(divs[i].hasAttribute('data-replo-set-active-variant') && divs[i].getAttribute('data-replo-set-active-variant').toLowerCase() == valueToTest){
                divs[i].click();
                divs[i].click(); // Double click for some themes with troubles
                dispatchClick(divs[i]);
                return;
            } else if(divs[i].hasAttribute('option-value') && divs[i].getAttribute('option-value').toLowerCase() == valueToTest){
                divs[i].click();
                divs[i].click(); // Double click for some themes with troubles
                dispatchClick(divs[i]);
                return;
            }
        }
    }
}

//Send change event to trigger functions on the theme
wideBundle.fireAllChangeEvent = function(){

    //Elements to trigger change event with vanilla JS
    var elementsToTrigger = ["variant-selects", 'div[data-pf-type="ProductVariantSwatches"]'];

    //Elements to trigger all children with vanilla JS
    var elementsToTriggerAll = ["variant-select", "variant-picker", "product-variants", "variant-selector", ".shg-product-variant-select"];

    //Elements to trigger all in bubble with vanilla JS
    var elementsToTriggerAllBubble = [".product-block-list__item.product-block-list__item--info .product-form__single-selector:checked", ".shopify-product-form .product-options .product-option-list",
    ".product__variants--select .styled-select select.option-selector",".single-option-selector"];

    //Elements to trigger change event with jQuery
    var elementsToTriggerJquery = ["#SingleOptionSelector-0", ".option-selectors .selector-wrapper select"];

    //Elements to trigger with timeout
    var elementsToTriggerTimeout = ["main#mainWrap #productHead #prodForm .form-select-wrapper .single-option-selector",
    "#ProductSection-product-template #add-to-cart-form #product-variants select"]

    //Trigger Vanilla JS
    for (const elementToTrigger of elementsToTrigger) {
        var element = document.querySelector(elementToTrigger);
        if(element){
            if('createEvent' in document){
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent('change', false, true);
                element.dispatchEvent(evt);
            }
            else{
                element.fireEvent('onchange');
            }
        }
    }

    //Trigger Vanilla JS for all children
    for (const elementToTriggerAll of elementsToTriggerAll) {
        var element = document.querySelectorAll(elementToTriggerAll);
        for(var i = 0; i<element.length; i++){
            if('createEvent' in document){
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent('change', false, true);
                element[i].dispatchEvent(evt);
            }
            else{
                element[i].fireEvent('onchange');
            }
        }
    }

    //Trigger Vanilla JS for all children with bubble true
    for (const elementToTriggerAllBubble of elementsToTriggerAllBubble) {
        var element = document.querySelectorAll(elementToTriggerAllBubble);
        for(var i = 0; i<element.length; i++){
            if('createEvent' in document){
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent('change', true, true);
                element[i].dispatchEvent(evt);
            }
            else{
                element[i].fireEvent('onchange');
            }
        }
    }
    

    //Trigger Jquery
    if(typeof $ != "undefined"){
        for (const elementToTriggerJquery of elementsToTriggerJquery) {
            if(document.querySelector(elementToTriggerJquery)){
                $(elementToTriggerJquery).trigger("change");
            }
        }
    }

    //Triger timeout
    for (const elementToTriggerTimeout of elementsToTriggerTimeout) {
        var element = document.querySelector(elementToTriggerTimeout);
        if(element){
            if('createEvent' in document){
                var evt = document.createEvent('HTMLEvents');
                evt.initEvent('change', false, true);
                element.dispatchEvent(evt);
            }
            else{
                element.fireEvent('onchange');
            }
        }
    }

    //Manage Afterpay
    if(typeof wideBundle.variantsSelector.id != "undefined" &&
        wideBundle.variantsSelector.id == ".selector-wrapper.product-form__item" &&
        typeof Afterpay != "undefined"){
            setTimeout(function() {
                if(document.querySelector('.selector-wrapper.product-form__item') != null)
                eventFire(document.querySelector('.selector-wrapper.product-form__item'), "change");
            }, 300);
      }

    //Manage EcomSolid changing variants
    productJsonNode = document.querySelector('.ProductJson');
    if(productJsonNode){
        isGemPages = wideBundle.formInfo.element.closest('[class^=\'gt_section-\'][data-name], [class^=\'gf_section-\'][data-name], [class^=\'gt_widget-\'][data-name], [class^=\'gt_element-\'][data-name]');
        if(isGemPages){
            productJson = JSON.parse(productJsonNode.innerHTML);
            variantJson = productJson.variants;
            idSelected = wideBundle.getSelectedVariantId()[0];
            for(var i = 0; i < variantJson.length; i++){
                if(variantJson[i].id == idSelected){
                    variantObject = variantJson[i];
                    console.log(variantObject);
                    break;
                }
            }
            window.SOLID.store.dispatch("variant" + productJson.id, variantObject);
        }
    }
};

//Update the price decimal separator
wideBundle.updatePriceSeparator = function(price){
    return price.replace('.', wideBundle.settings.price_separator);
}

//Remove the decimal if it's enabled and if there is no decimal
wideBundle.removeDecimal = function(price){
    if(wideBundle.settings.no_decimal == 1){
        if(price != ''){
            price = price.replace(",", ".");
            var regp = /(\.0?)0(?![1-9])/;
            price = price.replace(regp, '');
            price = wideBundle.updatePriceSeparator(price);
            return price;
        }
        else{
            return price;
        }
    }
    else{
        return price;
    }
}

//Create the price format with currency and price
wideBundle.formatPrice = function(price){
    if(price){
        return wideBundle.settings.currency.replace('{{amount}}', price).trim();
    }
    else{
        return "";
    }
}

//The user can update the price with Shopify Market so we first check if we can get prices from the theme
wideBundle.getPricesFromJson = function(variantId){
    if(typeof wideBundle.scriptCache != "undefined"){
      variantsOfProducts = wideBundle.scriptCache;
      if(typeof wideBundle.scriptCache[variantId] != "undefined"){
        if(typeof jsonParseScript[variantId] != "string" && jsonParseScript[variantId] != "null"){ //Weird bug where this jsonParseScript exists but inside we have the word "in" for each
            variantsOfProducts = [];
            variantsOfProducts.push(wideBundle.scriptCache[variantId]);
        }
      }
    }
    else{
      var variantsOfProducts = wideBundle.getVariantsFromJson(variantId);
    }

    if(variantsOfProducts != ""){
        for(var i=0; i<variantsOfProducts.length; i++){
            var variant = variantsOfProducts[i];
            if(variant.id == variantId){
                if(typeof variant.price_raw != "undefined"){
                    prices = [];
                    prices['price'] = wideBundle.formatPriceFromJson(variant.price_raw);
                    if(variant.sale_raw != false){
                        prices['compare_at_price'] = wideBundle.formatPriceFromJson(variant.sale_raw);
                    }
                    else{
                        prices['compare_at_price'] = "";
                    }
                    return prices;
                }
                else if(typeof variant.price != "undefined"){
                    prices = [];
                    if(containsOnlyNumbers(variant.price)){
                        prices['price'] = wideBundle.formatPriceFromJson(variant.price);
                        prices['compare_at_price'] = (variant.compare_at_price || variant.compareAtPrice) ? wideBundle.formatPriceFromJson(variant.compare_at_price || variant.compareAtPrice) : "";
                    }
                    else{
                      prices['price'] = wideBundle.getAmountFromPrice(variant.price).replace(",", "."); //Get only the amount from a price and replace decimal separator
                      prices['price'] = parseFloat(prices['price']).toFixed(2); //Transform the text into a number and fixed it to float 2
                      prices['price'] = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(prices['price'])); //Format the number as a price and replace currency for Shopify Market

                      prices['compare_at_price'] = (variant.compare_at_price || variant.compareAtPrice) ? variant.compare_at_price || variant.compareAtPrice : "";
                      if(prices['compare_at_price']){
                        prices['compare_at_price'] = wideBundle.getAmountFromPrice(prices['compare_at_price']).replace(",", "."); //Get only the amount from a price and replace decimal separator
                        prices['compare_at_price'] = parseFloat(prices['compare_at_price']).toFixed(2); //Transform the text into a number and fixed it to float 2
                        prices['compare_at_price'] = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(prices['compare_at_price'])); //Format the number as a price and replace currency for Shopify Market
                      }
                    }
                    return prices;
                }
            }
        }
        return null;
      }
      else{
        return null;
      }
}

//If we find prices in JSON we have to format them but they are like this: 2600 instead of 26.00
wideBundle.formatPriceFromJson = function(price){
    var priceFormat = parseFloat(price) / 100;
    priceFormat = priceFormat.toFixed(2);
    priceFormat = wideBundle.formatPrice(priceFormat);
    priceFormat = wideBundle.replaceCurrencyForMarket(priceFormat); //Replace the currency if another one is selected than default
    return priceFormat;
}

//Format price when they use the "price per unit" feature
wideBundle.formatPriceForUnit = function(price){
  var priceFormat = parseFloat(price);
  priceFormat = priceFormat.toFixed(2);
  priceFormat = wideBundle.formatPrice(priceFormat);
  priceFormat = wideBundle.replaceCurrencyForMarket(priceFormat); //Replace the currency if another one is selected than default
  return priceFormat;
}

// Function to extract the price number in whatever string provided, can handle dots, commas and both
function extractPrice(inputString) {
  const priceRegex = /(?:\$\s?)?([\d,.]+)/;
  const matches = inputString.match(priceRegex);

  if (matches && matches.length > 1) {
    return priceWithCommas = matches[1];
  }
  return null;
}

// Function to detect if there is whitespaces between to substrings in a giving string
function spaceSubstrings(inputString, substring1, substring2) {
  const index1 = inputString.indexOf(substring1);
  const index2 = inputString.indexOf(substring2);

  if (index1 !== -1 && index2 !== -1) {
    const startIndex = Math.min(index1, index2);
    const endIndex = Math.max(index1, index2);

    const spaceBetween = inputString.substring(startIndex + substring1.length, endIndex);
    return /\s/.test(spaceBetween);
  }

  return false;
}

//Function to check and remove duplicated substrings in a string
function removeDuplicate(originalString, substrings) {
  const escapedSubstrings = substrings.map(substring => substring.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));

  const regexString = escapedSubstrings.map(substring => `(${substring})`).join('|');
  const regex = new RegExp(regexString, 'g');

  const uniqueSubstrings = [];
  const result = originalString.replace(regex, (match, ...groups) => {
    const substring = groups.find(group => group !== undefined);
    if (!uniqueSubstrings.includes(substring)) {
      uniqueSubstrings.push(substring);
      return substring;
    }
    return '';
  });

  return result;
}

// Function to remove all texts from a string and keep only the provided substrings
function keepSubstrings(price, ...substrings) {
  priceNew = removeDuplicate(price, substrings); 
  const escapedCurrencySymbols = substrings.map(symbol => symbol.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  const regex = new RegExp([...substrings, ...escapedCurrencySymbols].join('|'), 'g');
  const matchedSubstrings = priceNew.match(regex) || [];
  const filteredResult = matchedSubstrings.filter(str => str !== '');

  for(var i=0; i<(filteredResult.length)-1; i++){
    if(spaceSubstrings(priceNew, filteredResult[i], filteredResult[i+1])){
      filteredResult[i] = filteredResult[i] + ' ';
    }
  }

  return filteredResult.join('');
}

// Function to check if a string has a currency code and return it
function extractCurrencyCode(inputString) {
  const currencyCodeRegex = /[A-Z]{3}/;
  const matches = inputString.match(currencyCodeRegex);
  return matches ? matches[0] : null;
}

//If the user uses Market and another currency is selected we have to replace the symbol
wideBundle.replaceCurrencyForMarket = function(price){

    //Exit if the currency is the same as the default
    if(typeof Shopify.currency != "undefined" && Shopify.currency.active == wideBundle.settings.currency_code){
        return price;
    }
    symbols = ["MXN $", "US$", "$", "€", "£", "kr", "Kr", "CHF", 'USD', 'PLN', 'zł', 'QAR', 'AED', 'SFr', '₴', 'UAH', 'EUR', 'lei'];
    

    symbols.every(symbol => {
        if(price.includes(symbol)){
          rawPrice = extractPrice(price);
          
          if(wideBundle.settings.currency_format === 'symbol'){
            price = keepSubstrings(price, rawPrice, symbol)
            price = price.replace(symbol, wideBundle.currencySymbols[Shopify.currency.active])
          }
          else if(wideBundle.settings.currency_format === 'both'){
            currencyCode = extractCurrencyCode(price);
            if(currencyCode == null){
              price = keepSubstrings(price, rawPrice, symbol)
              price = price.replace(symbol, wideBundle.currencySymbols[Shopify.currency.active]) + ' ' + Shopify.currency.active;
            }
            else{
              price = keepSubstrings(price, rawPrice, symbol, currencyCode)
              price = price.replace(symbol, wideBundle.currencySymbols[Shopify.currency.active]);
              price = price.replace(currencyCode, Shopify.currency.active);
            }
          }
          else {
            price = keepSubstrings(price, rawPrice, symbol)
            price = price.replace(symbol, wideBundle.currencyCodes[Shopify.currency.active])
          }

          return false;
        }
        return true;
    });

    return price;
}

wideBundle.updateHiddenPriceFromAjax = function(product){
  let priceStructured, compareAtPriceStructured;

  product.variants.forEach(variant => { //Format prices we received
    priceStructured = wideBundle.formatPriceFromJson(variant.price);
    priceStructured = wideBundle.updatePriceSeparator(priceStructured.toString());
    if(variant.compare_at_price){
      compareAtPriceStructured = wideBundle.formatPriceFromJson(variant.compare_at_price)
      compareAtPriceStructured = wideBundle.updatePriceSeparator(compareAtPriceStructured.toString());
      compareAtPriceStructured = parseFloat(wideBundle.getAmountFromPrice(priceStructured)) >= parseFloat(wideBundle.getAmountFromPrice(compareAtPriceStructured)) ? "" : compareAtPriceStructured
    }
    else{
      compareAtPriceStructured = "";
    }
    //Replace the prices in hidden prices and after creating the widget we will use them
    const hiddenPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="'+variant.id+'"]');
    if (hiddenPriceElement) {
      hiddenPriceElement.innerHTML = wideBundle.removeDecimal(priceStructured);
    }
    const hiddenComparedPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_compared_price[variant-id="'+variant.id+'"]');
    if (hiddenComparedPriceElement) {
      hiddenComparedPriceElement.innerHTML = wideBundle.removeDecimal(compareAtPriceStructured);
    }
  });
}

//Replace hidden prices with prices from Ajax if we couldn't get them from the theme JSON
wideBundle.addPricesFromAjax = function(){
    if (window.hasOwnProperty("wideBundlePreviewMode") && window?.wideBundlePreviewMode === true) {
      return;
    }

    if(typeof Shopify != "undefined" && typeof Shopify.currency != "undefined"){
        //Check if we can't get prices from json
        if(wideBundle.isAutomaticDiscount || !wideBundle.getPricesFromJson(document.querySelector('.wb_hidden_prices .wb_hidden_price').getAttribute('variant-id'))){
          console.log('doing ajax');

          const allOfferProducts = wideBundle.offers.reduce((acc, offerProducts) => {
            return [...acc, ...offerProducts];
          }, []).filter((product) => product.dynamicGroupUuid === null);

          Promise.all(allOfferProducts.filter((product) => {
            if (typeof product === typeof undefined || typeof product?.product_handle === typeof undefined) {
              return false;
            }

            if (product.dynamicGroupUuid !== null && product.dynamicGroupSelected === null) {
              return false;
            }

            return true;
          }).map((product) => {
            return fetch(`${window.Shopify.routes.root}products/${product.product_handle}.js`)
              .then(response => response.json());
          })).then((productResponses) => {
            productResponses.forEach((product) => {
              // console.log(product.variants);
              // console.log("PriceJson Script not available");
              wideBundle.updateHiddenPriceFromAjax(product);
            });
            wideBundle.updatePriceOnAllOffers(); //Update the offers with the new prices
          });
        }
      }
}

//Remove currency from a price
wideBundle.getAmountFromPrice = function(price) {

  // Count occurrences of dots and commas surrounded by two numbers
  /*var dotsCount = (price.match(/\d\.\d/g) || []).length;
  var commasCount = (price.match(/\d,\d/g) || []).length;

  if (dotsCount > 2 || commasCount > 2 || (dotsCount === 1 && commasCount === 1)) {
      // Remove the first occurrence of dot or comma surrounded by numbers
      price = price.replace(/(\d)([.,])(\d)/, '$1$3');
  }*/

  var regp = /[^0-9.,]*(\d+(?:[.,]\d+)?)(?:[^0-9.,]|$)/;
  match = structuredClone(price).match(regp);
  if (match) {
      return match[1];
  } else {
      return price;
  }
}


//Get only the current currency format
wideBundle.getCurrentCurrencyOnly = function(price){
    if(price != "" && price != null){
        return price.replace(/\d+.\d+/g,'{{amount}}').replace(/\d+/g,'{{amount}}');
    }
}

//Get the difference between two prices
function getAmountDifference(price, compareAtPrice){
    numberForPrice = parseFloat(wideBundle.getAmountFromPrice(price).replace(',', '.')); //Get the amount only for the price
    numberForCompareAtPrice = parseFloat(wideBundle.getAmountFromPrice(compareAtPrice).replace(',', '.')); //compare at price
    var amountDifference = numberForCompareAtPrice - numberForPrice;

    percentDifference = 100 * parseFloat(amountDifference) / numberForCompareAtPrice;
    percentDifference = Math.round(percentDifference);

    amountDifference = amountDifference.toFixed(2); //We round the price so we can have "34.00" or "34.99"

    return {
        "amount": amountDifference,
        "percent": percentDifference
    };
}

//Send observer to change the main price
function observePriceChanges(target) {
  const config = {
    childList: true,
    subtree: true,
    characterData: true,
  };

  const callback = function (mutationsList, observer) {
    if (!window.pricesWB) return;
    for (let mutation of mutationsList) {
      for (let selector of pricesWB) {
        let targetMatch = false;
        let addedMatch = false;
        let removedMatch = false;

        if (mutation.target.matches !== undefined && mutation.target.matches(selector)) {
          targetMatch = true;
        }

        Array.from(mutation.addedNodes).forEach(node => {
          if (node.matches !== undefined && node.matches(selector)) {
            addedMatch = true;
          }
        });

        Array.from(mutation.removedNodes).forEach(node => {
          if (node.matches !== undefined && node.matches(selector)) {
            removedMatch = true;
          }
        });

        if (mutation.target.nodeType != 3 && mutation.target.nodeType != 8) {
          if (mutation.target.querySelector('.first-price-WB') || mutation.target.querySelector('.second-price-WB')) continue;
        }

        if (targetMatch || addedMatch || removedMatch) {
          if (formWB.style.height == '0px' || formWB.style.display === 'none' || wideBundle.manualWidget) {
            wideBundle.updateMainPrice();
          }
        }
      }
    }
  };

  const observer = new MutationObserver(callback);
  observer.observe(target, config);
}
observePriceChanges(document);

wideBundle.updatePriceOnAllOffers = function(){
  const divHiddenPrices = document.querySelector('.wb_hidden_prices');
  offers = document.querySelectorAll('.new-form-option');
  offers.forEach(offer => {
    const offersPointer = Number(offer.getAttribute('data-offers-pointer'));
    const offerDb = wideBundle.offers[offersPointer];

    const hasVariant = new URLSearchParams(window.location.search.toLowerCase()).get('variant');
    const variantIdsSelectedWithType = offerDb.filter((offer) => !offer.product_is_upsell).reduce((ids, offer) => {
      let variantId = offer.variants[0].id;
      if (hasVariant && offersPointer==0) {
        const candidate = offer.variants.find((variant) => variant.id == hasVariant);
        if (candidate) variantId = candidate.id;
      }
      return [...ids, ...(new Array(offer.product_qty).fill({
        id: variantId,
        productType: offer.product_is_gift ? 'gift' : 'product',
      }))];
    }, []);
    const variantIdsSelected = variantIdsSelectedWithType.map((variant) => variant.id);
    const giftVariantIds = wideBundle.getGiftVariantIds(offersPointer);
    const upsellVariantIds = wideBundle.getUpsellVariantIds(offersPointer);
    const variantsString = offersPointer + "@" + variantIdsSelected.join("+");
    const variantPrices = variantIdsSelectedWithType.map((variant, index) => {
      const variantId = variant.id;
      const hiddenPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="' + variantId + '"]');
      if (!hiddenPriceElement) return 0;
      if (index > (offerDb[0].product_qty - 1) && giftVariantIds.includes(variantId) && variant.productType === 'gift') return 0;
      if (index > (offerDb[0].product_qty - 1) && upsellVariantIds.includes(variantId) && variant.productType === 'product') return 0;

      return parseFloat(wideBundle.getAmountFromPrice(hiddenPriceElement.textContent).replace(',', '.'));

    });
    const variantCompareAtPrices = variantIdsSelectedWithType.map((variant, index) => {
      const variantId = variant.id;
      const hiddenCompareAtPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_compared_price[variant-id="' + variantId + '"]');
      if (!hiddenCompareAtPriceElement || hiddenCompareAtPriceElement.textContent === "") {
        const hiddenPriceElement = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="' + variantId + '"]');
        if (!hiddenPriceElement) return 0;

        return parseFloat(wideBundle.getAmountFromPrice(hiddenPriceElement.textContent).replace(',', '.'));
      }
      if (index > (offerDb[0].product_qty - 1) && upsellVariantIds.includes(variantId) && variant.productType === 'product') return 0;

      return parseFloat(wideBundle.getAmountFromPrice(hiddenCompareAtPriceElement.textContent).replace(',', '.'));
    });
    document.querySelectorAll(`[data-calculated] [variant-id="${variantsString}"]`).forEach((element) => {
      element.parentElement.remove();
    });
    divHiddenPrices.innerHTML += wideBundle.addOfferCalculatedPrices(offerDb[0], variantIdsSelected, variantPrices, variantCompareAtPrices);

    if (offerDb[0].automatic_discount) {
      offerID = offersPointer + "@" + variantIdsSelected.join("+");
    } else {
      if(offer.classList.contains('selectedWB')){
        offerID = wideBundle.getSelectedVariantId()[0];
      }
      else{
        offerID = offer.getAttribute('data-variant-id');
      }
    }

    price = offer.querySelector('.first-price-WB');
    compareAtPrice = offer.querySelector('.second-price-WB');
    if(price){
      price.innerHTML = document.querySelector(`.wb_hidden_prices ${offerDb[0].automatic_discount ? '.wb_hidden_prices_element[data-calculated] ' : ' '}.wb_hidden_price[variant-id="${offerID}"]`).innerHTML;
      handleTranscyPrice(document.querySelector(`.wb_hidden_prices ${offerDb[0].automatic_discount ? '.wb_hidden_prices_element[data-calculated] ' : ' '}.wb_hidden_price[variant-id="${offerID}"]`).innerHTML, price);
    }
    if(compareAtPrice){
      compareAtPrice.innerHTML = document.querySelector(`.wb_hidden_prices ${offerDb[0].automatic_discount ? '.wb_hidden_prices_element[data-calculated] ' : ' '}.wb_hidden_compared_price[variant-id="${offerID}"]`).innerHTML;
      handleTranscyPrice(document.querySelector(`.wb_hidden_prices ${offerDb[0].automatic_discount ? '.wb_hidden_prices_element[data-calculated] ' : ' '}.wb_hidden_compared_price[variant-id="${offerID}"]`).innerHTML, compareAtPrice);
    }

    const priceParent = price.parentNode;
    if(priceParent.classList.contains("hidden-unit") && wideBundle.isAutomaticDiscount == false){
      const variantUnitPrice = parseFloat(wideBundle.getAmountFromPrice(price.innerHTML).replace(',', '.')) * priceParent.getAttribute('data_offer_cr');
      priceParent.parentNode.querySelector('.wb_unit_price').innerHTML = (wideBundle.removeDecimal(wideBundle.updatePriceSeparator(wideBundle.formatPriceForUnit(variantUnitPrice))));
    }

    //For "you save" text
    if(compareAtPrice.innerHTML != '' && wideBundle.settings.economic_display == 1){
      percent = offer.querySelector('.percent-wb');
      priceEconomic = offer.querySelector('.span-economic-wb');

      var priceDifference = getAmountDifference(price.innerHTML, compareAtPrice.innerHTML)
      priceDifferenceFormatted = wideBundle.updatePriceSeparator(wideBundle.removeDecimal(wideBundle.getCurrentCurrencyOnly(price.innerHTML).replace('{{amount}}', priceDifference.amount)));

      if(percent){
        percent.innerHTML = priceDifference.percent;
      }
      if(priceEconomic){
        priceEconomic.innerHTML = priceDifferenceFormatted;
      }
      savingsText = offer.querySelector('.economic-wb');
      if(savingsText){
        savingsText.closest(".new-form-option").classList.add("with-economic-text");
        savingsText.style.display = "block";
      }
    }
    else{
      var savingsText = offer.querySelector('.economic-wb');
      if(savingsText){ //Hide the savings text if we have it
        savingsText.closest(".new-form-option").classList.remove("with-economic-text");
        savingsText.style.display = "none";
      }
    }

    //Free gift
    if (offer.classList.contains('offer-free-gift')) {
      Array.from(offer.querySelectorAll('.wb-gift-product-wrapper')).forEach((giftOffer) => {
        const productPointer = parseInt(giftOffer.querySelector('[data-product-pointer]').getAttribute('data-product-pointer'));
        const giftProduct = offerDb[productPointer];
        if (!giftProduct) return;
        const variantId = giftProduct.variants[0].id;
  
        const giftPriceElement = giftOffer.querySelector('.gift-price-WB');
        const giftCompareElement = giftOffer.querySelector('.gift-compare-at-price-WB .crossed-price-WB');
  
        if (giftPriceElement && giftCompareElement) {
          const hiddenPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantId}"]`);
          const hiddenCompare = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantId}"]`);
  
          let giftPrice;
          if (giftOffer.classList.contains("wb-gift-product-wrapper--upsell")) {
            const totalPrice = wideBundle.getAmountFromPrice(hiddenPrice.innerHTML);
            const upsellPrice = Math.max(0, totalPrice - ((totalPrice / 100) * giftProduct.upsell_discount)).toFixed(2);
            giftPrice = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(upsellPrice)));
          } else {
            giftPrice = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal("0.00")));
          }
          giftPriceElement.innerHTML = wideBundle.updatePriceSeparator(giftPrice);
          giftCompareElement.innerHTML = hiddenCompare && hiddenCompare.innerHTML !== "" ? 
          hiddenCompare.innerHTML : 
          hiddenPrice.innerHTML;
          if (
            Number(wideBundle.getAmountFromPrice(giftPriceElement.innerHTML) ?? 0).toFixed(2) ===
            Number(wideBundle.getAmountFromPrice(giftCompareElement.innerHTML) ?? 0).toFixed(2)) {
            giftCompareElement.innerHTML = "";
          }
  
          handleTranscyPrice(giftPriceElement.innerHTML, giftPriceElement);
          handleTranscyPrice(giftCompareElement.innerHTML, giftCompareElement);
        }
      });
      return;
    }

  });

  wideBundle.updateMainPrice();
}

//Add the main style of the widget
wideBundle.addMainStyle = function (attribute = 'main') {
    var mainStyle = `
        :root {
            /* ===== COLOR VARIABLES ===== */
            
            /* General Colors */
            --wb-preview-heading-color: ${wideBundle.settings.preview_heading_color};
            --wb-heading-line-color: ${wideBundle.settings.heading_line_color};
            --wb-border-color: ${wideBundle.settings.border_color};
            --wb-hover-color: ${wideBundle.settings.hover_color};
            
            /* Unselected State Colors */
            --wb-unselected-background-color: ${wideBundle.settings.unselected_background_color};
            --wb-unselected-border-color: ${wideBundle.settings.unselected_border_color};
            --wb-unselected-thumbnail-color: ${wideBundle.settings.unselected_thumbnail_color};
            --wb-unselected-message-background-color: ${wideBundle.settings.unselected_message_background_color};
            --wb-unselected-message-border-color: ${wideBundle.settings.unselected_message_border_color};
            --wb-unselected-free-gift-background-color: ${wideBundle.settings.unselected_free_gift_background_color};
            --wb-unselected-free-gift-text-color: ${wideBundle.settings.unselected_free_gift_text_color};
            --wb-unselected-free-gift-icon-color: ${wideBundle.settings.unselected_free_gift_icon_color};
            --wb-unselected-title-text-color: ${wideBundle.settings.unselected_title_text_color};
            
            /* Selected State Colors */
            --wb-background-color: ${wideBundle.settings.background_color};
            --wb-thumbnail-color: ${wideBundle.settings.thumbnail_color};
            --wb-message-background-color: ${wideBundle.settings.message_background_color};
            --wb-message-border-color: ${wideBundle.settings.message_border_color};
            --wb-selected-free-gift-background-color: ${wideBundle.settings.selected_free_gift_background_color};
            --wb-selected-free-gift-text-color: ${wideBundle.settings.selected_free_gift_text_color};
            --wb-selected-free-gift-icon-color: ${wideBundle.settings.selected_free_gift_icon_color};
            --wb-selected-title-text-color: ${wideBundle.settings.selected_title_text_color};
            
            /* Text & Content Colors */
            --wb-offer-color: ${wideBundle.settings.offer_color};
            --wb-offer-selected-color: ${wideBundle.settings.offer_selected_color};
            --wb-option-color: ${wideBundle.settings.option_color};
            --wb-option-select-color: ${wideBundle.settings.option_select_color};
            
            /* Price Colors */
            --wb-price-color: ${wideBundle.settings.price_color};
            --wb-price-selected-color: ${wideBundle.settings.price_selected_color};
            --wb-price-compared-color: ${wideBundle.settings.price_compared_color};
            --wb-price-compared-selected-color: ${wideBundle.settings.price_compared_selected_color};
            
            /* Special Labels & Messages */
            --wb-color-best: ${wideBundle.settings.color_best};
            --wb-color-best-banner: ${wideBundle.settings.color_best_banner};
            --wb-best-selected-color: ${wideBundle.settings.best_selected_color};
            --wb-best-selected-color-banner: ${wideBundle.settings.best_selected_color_banner};
            --wb-economic-color: ${wideBundle.settings.economic_color};
            --wb-economic-selected-color: ${wideBundle.settings.economic_selected_color};
            
            /* Button & Input Colors */
            --wb-atc-color: ${wideBundle.settings.atc_color};
            --wb-color-button-quantity: ${wideBundle.settings.color_button_quantity};
            --wb-color-input-quantity: ${wideBundle.settings.color_input_quantity};
            
            
            /* ===== TYPOGRAPHY VARIABLES ===== */
            
            /* Heading Typography */
            --wb-preview-heading-font-size: ${wideBundle.settings.preview_heading_font_size};
            --wb-preview-heading-font-family: inherit;
            
            /* Message Typography - Unselected */
            --wb-unselected-custom-fontsize: ${wideBundle.settings.unselected_custom_fontsize};
            --wb-font-unselected-custom-sentence: ${wideBundle.settings.font_unselected_custom_sentence != 'auto' ? '"' + wideBundle.settings.font_unselected_custom_sentence + '", Arial, sans-serif' : 'inherit'};
            
            /* Message Typography - Selected */
            --wb-selected-custom-fontsize: ${wideBundle.settings.selected_custom_fontsize};
            --wb-font-selected-custom-sentence: ${wideBundle.settings.font_selected_custom_sentence != 'auto' ? '"' + wideBundle.settings.font_selected_custom_sentence + '", Arial, sans-serif' : 'inherit'};
            
            
            /* ===== SPACING & LAYOUT VARIABLES ===== */
            
            /* Border Radius */
            --wb-unselected-border-radius: ${wideBundle.settings.unselected_border_radius};
            --wb-selected-border-radius: ${wideBundle.settings.selected_border_radius || wideBundle.settings.unselected_border_radius};
            
            /* Border Width */
            --wb-border-width: ${wideBundle.settings.border_width || '2px'};
            
            /* Heading Line */
            --wb-heading-line-size: ${wideBundle.settings.heading_line_size};
            
            
            /* ===== TRANSPARENCY/OPACITY VARIABLES ===== */
            
            /* Background Transparency */
            --wb-unselected-message-background-transparency: ${wideBundle.settings.unselected_message_background_transparency || '00'};
            --wb-message-background-transparency: ${wideBundle.settings.message_background_transparency || '00'};
            --wb-unselected-background-transparency: ${wideBundle.settings.unselected_background_transparency || '00'};
            --wb-background-transparency: ${wideBundle.settings.background_transparency || '00'};
            
            
            /* ===== ANIMATION & INTERACTION VARIABLES ===== */
            
            /* Transition Duration */
            --wb-transition-duration: ${wideBundle.settings.transition_duration || '0.2s'};
            
            /* Hover Effects */
            --wb-hover-scale: ${wideBundle.settings.hover_scale || '1'};
            --wb-hover-opacity: ${wideBundle.settings.hover_opacity || '1'};
        }

        #new-form shopify-buy-it-now-button:nth-of-type(2){ /* Fix a bug where buy now button appears twice */
            display: none;
        }
        #checkout-xx-aa {
            color: white;
            font-size: 1px;
            margin-top: 0px;
            margin-bottom: 0px;
            display: none;
        }
        #new-form *, #new-form::before, #new-form::after {
           box-sizing: border-box;
        }
        #new-form, .new-wb-form {
            max-width: 700px;
            margin: auto;
            position: relative;
            ${wideBundle.settings.rtl == 1 ? 'direction: rtl;' : ''};
        }
        .product--no-media product-form.product-form{
            display: block !important;
        }
        #new-form .jumpstart-selector .arrow{
            display: none !important;
        }
        #new-form .jumpstart-selector select{
            -webkit-appearance: auto;
            appearance: auto;
        }
        .product-detail .product-form.theme-init .option-selectors{
            display: none !important;
        }
        .p-title-WB {
            overflow: hidden;
            position: relative;
	          display: flex;
            text-align: ${wideBundle.settings.preview_heading_position};
            justify-content: center;
        }
        .p-title-WB__content {
            position: relative;
            color: ${wideBundle.settings.preview_heading_color};
            font-size: ${wideBundle.settings.preview_heading_font_size};
            ${wideBundle.settings.preview_heading_font_style == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.preview_heading_font_style == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.preview_heading_font_style == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.preview_heading_font_style == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}

            ${wideBundle.settings.preview_heading_position == 'left' ? 'margin: 0 auto 0 0;' : ''}
            ${wideBundle.settings.preview_heading_position == 'center' ? 'margin: 0 auto;' : ''}
            ${wideBundle.settings.preview_heading_position == 'right' ? 'margin: 0 0 0 auto;' : ''}

            ${wideBundle.settings.preview_heading_position == 'left' && wideBundle.settings.heading_line_display == 1 ? 'padding: 0px 8px 0px 0px;max-width: 90%;' : ''}
            ${wideBundle.settings.preview_heading_position == 'center' && wideBundle.settings.heading_line_display == 1 ? 'padding: 0px 8px 0px 8px;max-width: 90%;' : ''}
            ${wideBundle.settings.preview_heading_position == 'right' && wideBundle.settings.heading_line_display == 1 ? 'padding: 0px 0px 0px 8px;max-width: 90%;' : ''}
        }

        .p-title-WB::before {
          display: ${wideBundle.settings.heading_line_display == 1 && (wideBundle.settings.preview_heading_position == 'center' || wideBundle.settings.preview_heading_position == 'right') ? 'block' : 'none'};
          content: '';
          flex-grow: 1;
          height: ${wideBundle.settings.heading_line_size};
          background-color: ${wideBundle.settings.heading_line_color};
          margin: auto;
        }

        .p-title-WB::after {
          display: ${wideBundle.settings.heading_line_display == 1 && (wideBundle.settings.preview_heading_position == 'left' || wideBundle.settings.preview_heading_position == 'center') ? 'block' : 'none'};
          content: '';
          flex-grow: 1;
          height: ${wideBundle.settings.heading_line_size};
          background-color: ${wideBundle.settings.heading_line_color};
          margin: auto;
        }

        .new-form-option{
            display:flex;
            align-items:center;
            ${wideBundle.settings.rtl == 1 ? 'padding: 10px 0px 10px 10px;' : 'padding: 10px 10px 10px 0px;'}
            cursor:pointer;
            border-radius: ${wideBundle.settings.unselected_border_radius};
            margin-bottom:15px;
            border:2px solid #c6c6c6;
            transition: background-color 0.1s ease, border 0.1s ease;
        }
        
        .offer-with-gift-flex-wrapper{
            display: flex;
            align-items: center;
            width: 100%;
        }

        .new-form-option .value-left{
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
        }

        .diagonal-offer{
            --d: 10px;
            position: relative;
            --message: 'special offer';
            ${wideBundle.settings.display_quantity == 1 && wideBundle.settings.design_code !== '1' && wideBundle.settings.design_code !== '5' ? 'padding-right: 40px !important;' : ''}
        }

        .diagonal-offer::before {
            content: var(--message);
            position: absolute;
            font-family: sans-serif;
            top: 0;
            right: 0;
            transform: translate(29.29%, -100%) rotate(45deg);
            text-align: center;
            border: 1px solid transparent;
            border-bottom: 0;
            transform-origin: bottom left;
            padding: 5px 35px calc(var(--d) + 5px);
            background: linear-gradient(rgba(0, 0, 0, 0.5) 0 0) bottom/100% var(--d)
                        no-repeat var(--c);
            background-clip: padding-box;
            clip-path: polygon(0 0,100% 0,100% 100%,calc(100% - var(--d)) calc(100% - var(--d)),var(--d) calc(100% - var(--d)),0 100%);
            -webkit-mask: linear-gradient(135deg,transparent calc(50% - var(--d) * 0.707),#fff 0) bottom left,
                        linear-gradient(-135deg, transparent calc(50% - var(--d) * 0.707), #fff 0)bottom right;
            -webkit-mask-size: 300vmax 300vmax;
            -webkit-mask-composite: destination-in, xor;
            mask-composite: intersect;
            max-width: 195px;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1;
            z-index: 2;
        }

        .corner-offer{
            --f: 14px;
            --r: 20px;
            position: absolute;
            top: -17px;
            padding: .1em .5em;
            background: #FA6900;
            border-bottom: var(--f) solid #0005;
            border-left: var(--r) solid #0000;
            clip-path: polygon(0 0,100% 0,100% calc(100% - var(--f)),calc(100% - var(--f)) 100%,
              calc(100% - var(--f)) calc(100% - var(--f)),0 calc(100% - var(--f)),
              var(--r) calc(50% - var(--f)/2));
            right: calc(-1*var(--f));
            height: 45px;
            display: flex;
            align-items: center;
            z-index: 1;
        }

        .corner-offer-container:not(.offer-free-gift){
            position: relative;
            padding: 20px 10px 20px 0px !important;
            margin-top: 20px;
        }

        .corner-offer-container.offer-free-gift{
            position: relative;
            padding: 20px 0px 0px 0px !important;
            margin-top: 20px;
        }

        .corner-offer-container.offer-free-gift .offer-with-gift-flex-wrapper{
            padding-right: 10px;
        }
        
        .selectable .corner-offer {
            background: ${wideBundle.settings.unselected_message_background_transparency !== '00' ? wideBundle.settings.unselected_message_background_color : wideBundle.settings.border_color};
            color: ${wideBundle.settings.color_best_banner};
            font-size: ${wideBundle.settings.unselected_custom_fontsize};
            ${wideBundle.settings.font_unselected_custom_sentence != 'auto' ? 'font-family: "' + wideBundle.settings.font_unselected_custom_sentence + '",  Arial, sans-serif;' : ''}
            ${wideBundle.settings.style_blinking == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_blinking == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .selectable.diagonal-offer{
            --c: ${wideBundle.settings.unselected_message_background_transparency !== '00' ? wideBundle.settings.unselected_message_background_color : wideBundle.settings.border_color};
            color: ${wideBundle.settings.color_best_banner};
        }

        .selectable.diagonal-offer::before{
            font-size: ${wideBundle.settings.unselected_custom_fontsize};
            ${wideBundle.settings.font_unselected_custom_sentence != 'auto' ? 'font-family: "' + wideBundle.settings.font_unselected_custom_sentence + '",  Arial, sans-serif;' : ''}
            ${wideBundle.settings.style_blinking == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_blinking == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        
        .selectedWB .corner-offer {
            background: ${wideBundle.settings.message_background_transparency !== '00' ? wideBundle.settings.message_background_color : wideBundle.settings.border_color};
            color: ${wideBundle.settings.best_selected_color_banner};
            font-size: ${wideBundle.settings.selected_custom_fontsize};
            ${wideBundle.settings.font_selected_custom_sentence != 'auto' ? 'font-family: "' + wideBundle.settings.font_selected_custom_sentence + '",  Arial, sans-serif;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .selectedWB.diagonal-offer{
            --c: ${wideBundle.settings.message_background_transparency !== '00' ? wideBundle.settings.message_background_color : wideBundle.settings.border_color};
            color: ${wideBundle.settings.best_selected_color_banner};
        }

        .selectedWB.diagonal-offer::before{
            font-size: ${wideBundle.settings.selected_custom_fontsize};
            ${wideBundle.settings.font_selected_custom_sentence != 'auto' ? 'font-family: "' + wideBundle.settings.font_selected_custom_sentence + '",  Arial, sans-serif;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .checkedWB{
            display: block;
            width: 17px;
            height: 17px;
            border: 3px solid #f4f4f4;
            background-color: #f4f4f4;
            border-radius: 50%;
            margin-left: 10px;
            margin-right: 10px;
        }

        .thumbnailWB{
            width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "40px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "60px" : "80px")};
            border: 1px solid ${wideBundle.settings.unselected_thumbnail_color};
            border-radius: 5px;
            
            ${wideBundle.settings.rtl == 1 ? 'margin-left: 10px;' : 'margin-right: 10px;'};
        }

        .selectedWB .thumbnailWB{
            width: ${wideBundle.settings.thumbnail_size == "s" ? "40px" : (wideBundle.settings.thumbnail_size == "m" ? "60px" : "80px")};
            border: 1px solid ${wideBundle.settings.thumbnail_color};
        }

        .value-left{
            min-width: 40px;
        }
        .offer-image{
            min-width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "88px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "108px" : "128px")};
        }

        .selectedWB .offer-image{
            min-width: ${wideBundle.settings.thumbnail_size == "s" ? "88px" : (wideBundle.settings.thumbnail_size == "m" ? "108px" : "128px")};
        }

        .value-right{
            ${wideBundle.settings.rtl == 0 ? 'text-align: left;' : ''};
        }
        .title-variant{
            text-transform: none;
            ${wideBundle.settings.rtl == 0 ? 'text-align: left;' : ''};
            margin: 0;
            color: ${wideBundle.settings.offer_color};
        }
        .best-title-new{
            line-height: 1;
            color: ${wideBundle.settings.color_best};
            transition: opacity 0.5s ease;
            font-weight: bold;
        }
        .price-new-form{
            ${wideBundle.settings.rtl == 0 ? 'text-align: left;' : ''};
            width: auto;
            margin: 0px;
            margin-bottom: 0px;
        }

        .hidden-unit{
            display: none !important;
        }

        .first-unit-WB {
            margin-right: 5px;
            text-align: left;
            width: auto;
            margin: 0px;
            margin-bottom: 0px;
        }

        .selectedWB .first-unit-WB {
            font-size: ${wideBundle.settings.selected_price_fontsize};
            color: ${wideBundle.settings.price_selected_color} !important;
            ${wideBundle.settings.style_price_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_price_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        
        }
        .selectable .first-unit-WB {
            font-size: ${wideBundle.settings.unselected_price_fontsize};
            color: ${wideBundle.settings.price_color} !important;
            ${wideBundle.settings.style_price == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_price == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        
        }

        .wb_unit_text{
            font-size: 0.85em;
        }

        .selectedWB .first-price-WB {
            font-size: ${wideBundle.settings.selected_price_fontsize};
        }
        .selectedWB .second-price-WB {
            font-size: ${wideBundle.settings.selected_compare_price_fontsize};
        }
        .selectable .first-price-WB {
            font-size: ${wideBundle.settings.unselected_price_fontsize};
        }
        .selectable .second-price-WB {
            font-size: ${wideBundle.settings.unselected_compare_price_fontsize};
        }
        span.money.first-price-WB, .first-price-WB{
            color: ${wideBundle.settings.price_color} !important;
            ${wideBundle.settings.rtl == 1 ? 'margin-left: 5px;' : 'margin-right: 5px;'}
            
        }
        span.money.second-price-WB, .second-price-WB{
            color: ${wideBundle.settings.price_compared_color} !important;
            text-decoration: line-through !important;
        }
        .crossed-price-WB{
            color: inherit;
            text-decoration: line-through !important;
        }
        .doubly.second-price-WB, .money.second-price-WB{
            color: ${wideBundle.settings.price_compared_color};
            text-decoration: line-through !important;
        }
        .spinWB{
            display: flex;
            width: 80px;
            margin-top: 20px;
            display: none;
            margin-bottom: 20px;
            flex: 0 0 80px;
            margin-left: auto;
        }
        .quantity-wb-less{
            border-radius: 4px 0px 0px 4px;
            background-color: ${wideBundle.settings.bg_button_quantity};
            color: ${wideBundle.settings.color_button_quantity};
            border: 1px solid #dadada;
            display: inline-block;
            width: 33%;
            padding-top:0px;
            padding-bottom:0px;
            text-align: center;
            cursor: pointer;
            vertical-align: 1.5px;
        }
        .quantity-wb-more{
            border-radius:0px 4px 4px 0px;
            background-color: ${wideBundle.settings.bg_button_quantity};
            color: ${wideBundle.settings.color_button_quantity};
            border: 1px solid #dadada;
            display: inline-block;
            width: 33%;
            padding-top:0px;
            padding-bottom:0px;
            text-align: center;
            cursor: pointer;
            vertical-align: 1.5px;
        }
        #new-form .quantity-wb-input, .new-wb-form .quantity-wb-input{
            -webkit-appearance: none;
            -moz-appearance: none;
            background-color: ${wideBundle.settings.bg_input_quantity};
            color: ${wideBundle.settings.color_input_quantity};
            appearance: none;
            width: 34%;
            text-align: center;
            font-weight: bold;
            border: 1px solid #dadada;
            border-left: 0;
            border-right: 0;
            padding-left:0px;
            padding-right:0px;
            padding-top: 0px;
            padding-bottom: 0px;
            align-self: stretch;
            box-sizing: border-box;
        }
        .div-select2:first-of-type{
            margin-top: 10px;
        }
        #new-form .select-option-third, .new-wb-form .select-option-third{
            margin:0;
            line-height:23px;
            position:static;
            opacity:1;
            display:block;
            background-position: right 10px center !important;
            border-radius:3px;
            border: 1px solid ${wideBundle.settings.border_color};
            font-size:16px;
            ${wideBundle.settings.rtl == 1 ? 'float:right;' : 'float:left;'}
            min-width:100px;
            max-width:auto;
            width:auto;
            min-height:24px;
            height:24px;
            padding:0;
            padding-left:3px;
            ${wideBundle.settings.rtl == 1 ? 'padding-right:3px;' : 'padding-right:25px;'}
            ${wideBundle.settings.rtl == 1 ? 'margin-right:5px;' : 'margin-left:5px;'}
            color:black;
        }
        #new-form .select-option-second, .new-wb-form .select-option-second{
            line-height:23px;
            position:static;
            opacity:1;
            display:block;
            background-position: right 10px center !important;
            border-radius:3px;
            border: 1px solid ${wideBundle.settings.border_color};
            font-size:16px;
            
            ${wideBundle.settings.rtl == 1 ? 'float:right;' : 'float:left;'}
            min-width:100px;
            max-width:auto;
            width:auto;
            min-height:24px;
            height:24px;
            padding:0;
            padding-left:3px;
            ${wideBundle.settings.rtl == 1 ? 'padding-right:3px;' : 'padding-right:25px;'}
            margin:0;
            ${wideBundle.settings.rtl == 1 ? 'padding-right:3px;' : 'padding-right:25px;'}
            color:black;
        }
        #new-form .select-option-first, .new-wb-form .select-option-first{
            line-height:23px;
            position:static;
            opacity:1;
            display:block;
            background-position: right 10px center !important;
            border-radius:3px;
            border: 1px solid ${wideBundle.settings.border_color};
            font-size:16px;
            
            ${wideBundle.settings.rtl == 1 ? 'float:right;' : 'float:left;'}
            min-width:100px;
            max-width:auto;
            width:auto;
            min-height:24px;
            height:24px;
            padding:0;
            padding-left:3px;
            ${wideBundle.settings.rtl == 1 ? 'padding-right:3px;' : 'padding-right:25px;'}
            margin:0;
            ${wideBundle.settings.rtl == 1 ? 'padding-right:3px;' : 'padding-right:25px;'}
            color:black;
        }
        #new-form .wb-swatch-container .select-option-third, .new-wb-form .wb-swatch-container .select-option-third{
            margin-left: 0px;
        }
        #new-form .pretty-select, .new-wb-form .pretty-select{
            padding: 0px 0px 0px 0px;
        }
        #new-form .disclosure .disclosure__toggle svg, .pretty-select svg, .new-wb-form .disclosure .disclosure__togle svg{
            display: none;
        }
        .title-option-wb{
            color: ${wideBundle.settings.option_color};
            font-size: ${wideBundle.settings.option_fontsize};
            margin:0;
            margin-top:3px;
            ${wideBundle.settings.rtl == 1 ? 'margin-left:5px;' : 'margin-right:5px;'}
            margin-bottom:10px;
            ${wideBundle.settings.rtl == 1 ? 'float:right;' : 'float:left;'}
        }
        .clear{
            margin:0;
            clear:both;
            margin-top: 0px !important;
            margin-bottom: 0px !important;
        }
        .economic-wb{
            margin-top: 0px;
            margin-bottom: 0px;
            color: ${wideBundle.settings.economic_color};
        }
        #new-form-atc, .new-form-atc{
            width: 100%;
            cursor: pointer;
            background-color: ${wideBundle.settings.atc_background};
            color: ${wideBundle.settings.atc_color};
            border-radius: ${wideBundle.settings.atc_radius};
            text-align: center;
            font-size: ${wideBundle.settings.atc_font_size};
            margin-top: 10px;
            margin-bottom: 15px;
            ${wideBundle.settings.atc_size == 'small' ? 'padding: 10px 0 10px 0;' : ''}
            ${wideBundle.settings.atc_size == 'medium' ? 'padding: 20px 0 20px 0;' : ''}
            ${wideBundle.settings.atc_size == 'large' ? 'padding: 30px 0 30px 0;' : ''}
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: center;
            ${wideBundle.settings.atc_font != 'auto' ? 'font-family: "' + wideBundle.settings.atc_font + '"' : ''}
        }
        #new-form-atc:hover, .new-form-atc:hover{
            background-color: ${wideBundle.settings.hover_color};
        }
        .new-form-atc .first-price-WB,
        .new-form-atc .second-price-WB{
            margin: 0 4px;
            display: inline;
        }
        .new-form-atc .second-price-WB{
            opacity: 0.85;
        }
        .before-code-wb{
            margin-top: 10px;
        }
        #new-form .selectable, .new-wb-form .selectable{
            background-color: ${wideBundle.settings.unselected_background_color + wideBundle.settings.unselected_background_transparency};
            border: ${wideBundle.settings.unselected_border_size} solid ${wideBundle.settings.unselected_border_color};
            border-radius: ${wideBundle.settings.unselected_border_radius};
            font-weight: normal;
        }
        
        .selectable span.money.first-price-WB, .selectable .first-price-WB{
            color: ${wideBundle.settings.price_color} !important;
        }
        .selectable span.money.second-price-WB, .selectable .second-price-WB{
            color: ${wideBundle.settings.price_compared_color} !important
        }
        .selectable .best-title{
            color: ${wideBundle.settings.color_best};
            border: ${wideBundle.settings.unselected_message_border_size} solid ${wideBundle.settings.unselected_message_border_color};
            border-radius: ${wideBundle.settings.unselected_message_border_radius};
            background-color: ${wideBundle.settings.unselected_message_background_color + wideBundle.settings.unselected_message_background_transparency};
            ${wideBundle.settings.unselected_message_background_transparency !== '00' || wideBundle.settings.unselected_message_border_size !== '0px' ? 'margin: 3px 0px; padding: 3px 5px;' : ''}
            display: inline-block;
            width: 100%;
            ${wideBundle.settings.unselected_message_background_transparency !== '00' || wideBundle.settings.unselected_message_border_size !== '0px' ? 'width: auto;' : ''}
            font-size: ${wideBundle.settings.unselected_custom_fontsize};
            ${wideBundle.settings.font_unselected_custom_sentence != 'auto' ? 'font-family: "' + wideBundle.settings.font_unselected_custom_sentence + '",  Arial, sans-serif;' : ''}
        }
        .selectable .checkedWB{
            background-color: #f4f4f4;
        }
        .selectable .div-select2{
            display: none;
            visibility: hidden;
        }
        .selectable .spinWB{
            display: none;
        }
        .selectable .money{
            font-weight: normal !important;
        }
        #new-form .selectedWB, .new-wb-form .selectedWB{
            background-color: ${wideBundle.settings.background_color};
            border: ${wideBundle.settings.border_size} solid ${wideBundle.settings.border_color};
            border-radius: ${wideBundle.settings.border_radius};
            font-weight: bold;
        }
        .selectedWB .title-variant{
            color: ${wideBundle.settings.offer_selected_color};
            font-size: ${wideBundle.settings.selected_title_fontsize};
            ${wideBundle.settings.style_title_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_title_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectedWB span.money.first-price-WB, .selectedWB .first-price-WB{
            color: ${wideBundle.settings.price_selected_color} !important;
            ${wideBundle.settings.style_price_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_price_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectedWB span.money.second-price-WB, .selectedWB .second-price-WB{
            color: ${wideBundle.settings.price_compared_selected_color} !important;
            ${wideBundle.settings.style_compared_price_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_compared_price_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_compared_price_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_compared_price_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectedWB .economic-wb{
            color: ${wideBundle.settings.economic_selected_color};
            font-size: ${wideBundle.settings.selected_savings_fontsize};
            ${wideBundle.settings.style_economic_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_economic_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectedWB .best-title{
            color: ${wideBundle.settings.best_selected_color};
            border: ${wideBundle.settings.message_border_size} solid ${wideBundle.settings.message_border_color};
            border-radius: ${wideBundle.settings.message_border_radius};
            background-color: ${wideBundle.settings.message_background_color + wideBundle.settings.message_background_transparency};
            ${wideBundle.settings.message_background_transparency !== '00' || wideBundle.settings.message_border_size !== '0px' ? 'margin: 3px 0px; padding: 3px 5px;' : ''}
            display: inline-block;
            width: 100%;
            ${wideBundle.settings.unselected_message_background_transparency !== '00' || wideBundle.settings.unselected_message_border_size !== '0px' ? 'width: auto;' : ''}
            font-size: ${wideBundle.settings.selected_custom_fontsize};
            ${wideBundle.settings.font_selected_custom_sentence != 'auto' ? 'font-family: "' + wideBundle.settings.font_selected_custom_sentence + '",  Arial, sans-serif;' : ''}
        }
        
        .selectedWB .checkedWB{
            background-color: ${wideBundle.settings.border_color};
        }
        .selectedWB.offer-discount-system .checkedWB{
            outline: 2px solid ${wideBundle.settings.border_color};
            border: 2px solid rgb(244, 244, 244);
        }
        .selectable.offer-discount-system .checkedWB{
            background-color: transparent;
        }
        .offer-discount-system .checkedWB{
            width: 12px;
            height: 12px;
            outline: 2px solid rgb(244, 244, 244);
            border: none;
        }
        .selectedWB .best-title-new{
            ${wideBundle.settings.style_blinking_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectedWB .span-economic-wb{
            ${wideBundle.settings.style_economic_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_economic_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectedWB .div-select2{
            ${wideBundle.settings.style_variants_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_variants_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_variants_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_variants_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectable .best-title-new{
            ${wideBundle.settings.style_blinking == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_blinking == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_blinking == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectable .span-economic-wb{
            ${wideBundle.settings.style_economic == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_economic == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectable .div-select2{
            ${wideBundle.settings.style_variants == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_variants == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_variants == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_variants == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectable .title-variant{
            color: ${wideBundle.settings.offer_color};
            font-size: ${wideBundle.settings.unselected_title_fontsize};
            ${wideBundle.settings.style_title == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_title == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectable span.money.first-price-WB, .selectable .first-price-WB{
            ${wideBundle.settings.style_price == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_price == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_price == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectable span.money.second-price-WB, .selectable .second-price-WB{
            ${wideBundle.settings.style_compared_price == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_compared_price == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_compared_price == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_compared_price == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectable .economic-wb{
            font-size: ${wideBundle.settings.unselected_savings_fontsize};
            ${wideBundle.settings.style_economic == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_economic == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_economic == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }
        .selectedWB .spinWB{
            display: flex;
        }

        .selectedWB .spinWB span{
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .selectedWB select.select-bundle.select-class-second {
            color: ${wideBundle.settings.option_select_color} !important;
            ${wideBundle.settings.option_select_default_settings == 1 ? '' : 'background: ' + wideBundle.settings.option_select_background + '!important;'}
        }

        .selectedWB select.select-bundle.select-class-first {
            color: ${wideBundle.settings.option_select_color} !important;
            ${wideBundle.settings.option_select_default_settings == 1 ? '' : 'background: ' + wideBundle.settings.option_select_background + '!important;'}
        }

        .hide-bloc-wb{
            display: none !important;
        }
        #new-form .loading-wb, .new-wb-form .loading-wb{
            width: 20px;
            height: 20px;
        }
        #cont-trustbadge-wb, .cont-trustbadge-wb{
            text-align: center;
            width: 80%;
            margin: auto;
        }
        #cont-trustbadge-wb img, .cont-trustbadge-wb img{
            width: 100%;
        }
        #after-code-wb{
            margin-top: 10px;
        }
        #new-form p:empty, .new-wb-form p:empty{
            display: block;
        }
        .d-flex.form-wb-selected{
            display: none !important;
        }
        .new-form-atc--out-of-stock,
        .new-form-atc--out-of-stock[style] {
            animation: none !important;
            -webkit-animation: none !important;
            opacity: 0.5 !important;
        }
        .new-form-atc--out-of-stock svg,
        .new-form-atc--out-of-stock[style] svg {
            display: none!important;
        }

        #new-form .widebundle_error, .new-wb-form .widebundle_error{
            color: #cc0000;
            text-align: center;
            background-color: #ffecec;
            padding: 10px;
            border: 1px solid #cc0000;
            border-radius: 5px;
            opacity: 0;
            transform: translateY(100%);
            transition: opacity 0.5s ease-in-out, transform 0.5s ease-in-out;
            font-size: 14px !important;
            font-family: Helvetica !important;
            width: 100%;
        }
        #new-form .widebundle_error.visible, .new-wb-form .widebundle_error.visible {
            opacity: 1;
            transform: translateY(0);
        }
        #new-form .widebundle_error a, .new-wb-form .widebundle_error a{
            color: #cc0000 !important;
            text-decoration: underline !important;
        }
        .widebundle_error svg{
            vertical-align: -10%;
            display: inline-block
        }
        
        .wb-color-swatch-box {
            display: flex;
            flex-wrap: wrap;
            gap: 2px;
        }
        
        .wb-color-swatch > input {
            visibility: hidden;
            position: absolute !important;
        }
        
        .wb-color-swatch > input + .wb-color-swatch-radio {
            cursor:pointer;
            border: 1px solid #ffffff;
            outline: 2px solid #c1c1c1;   
        }
        
        .wb-color-swatch > input:checked + .wb-color-swatch-radio {
            border: 1px solid #ffffff;
            outline: 2px solid ${wideBundle.settings.border_color};           
        }
        
        .wb-color-swatch > input:disabled + .wb-color-swatch-radio,
        .wb-color-swatch > input:disabled + .wb-color-swatch-radio::after {
            opacity: 0.5;       
        }
        
        .wb-color-swatch-radio {
            display: flex !important;
            position: relative;
            width: 22px;
            height: 22px;
            margin: 2px;
            background: #ffffff;
            border: 1px solid #ffffff;
            outline: 1px solid #c1c1c1;
            border-radius: 100%;
            background-size: 100% 100%;
            background-position: center;
            box-sizing: border-box;
        }

        .div-discount-system .wb-color-swatch-radio{
            margin: 0px 2px 0px 2px;
        }
        
        .wb-color-swatch-radio:after {
            content: "";
            position: absolute;
            left: -3px;
            top: -3px;
            width: 26px;
            height: 26px;
            background: #e0e0e0;
            border-radius: 100%;
            box-sizing: border-box;
            z-index: -1;
        }
        
        .wb-swatch-container .title-option-wb {
            width: 100%;
            margin: 0;
        }

        .wb-swatch-container .title-option-wb.label_num_auto_discount_wb {
            width: auto;
            margin: 0;
            margin-right: 5px;
        }
        
        .wb-swatch-container {
            display: flex;
            flex-wrap: wrap;
            gap:6px 15px;
            margin-bottom: 10px;
        }
        
        .wb-swatch-container.div-discount-system{
            gap: 0px;
            flex-wrap: nowrap;
        }

        .div-discount-system .wb-color-swatch-box{
            margin-right: 5px;
            float: left;
        }

        .div-discount-system .wb-color-swatch{
            margin-bottom: 5px;
        }

        .swatch-3-select,
        .swatch-2-select,
        .swatch-1-select {
            display: none !important;
        }

        .general_option_label_wb_wrapper {
            width: 100%;
            display: flex;
            gap: 8px;
            align-items: center;
            padding: 2px 0;
        }

        .general_option_label_wb{
            display: flex;
            align-items: center;
            gap: 8px;
            color: ${wideBundle.settings.option_color};
            font-size: ${wideBundle.settings.option_fontsize};
            font-weight: 600;
            margin-bottom: 5px !important;
            margin-top: 7px !important;
        }

        .general_option_label_wb_wrapper > p.general_option_label_wb {
            text-align: left!important;
            width: 100%!important;
            margin-top: 0!important;
            margin-bottom: 0!important;
        }

        .general_option_label_wb_wrapper > p.general_option_label_wb img {
            border-radius: ${wideBundle.settings.design_code == 4 ? '5px' : wideBundle.settings.border_radius};
            border: 1px solid ${wideBundle.settings.border_color};
        }

        .discount_system_select_wb{
            -webkit-appearance: auto !important;
            -moz-appearance: auto !important;
            appearance: auto !important;
            background-position: initial !important;
            background-image: none !important;
            background-repeat: initial !important;
            font-size: 0.8em !important;
            padding-right: 5px !important;
            width: auto !important;
            max-width: 80px;
            min-width: auto !important;
            margin-left: 0px !important;
            margin-right: 5px !important;
            margin-bottom: 5px !important;
            height: 22px !important;
            line-height: 22px !important;
            min-height: 22px !important;
        }

        .label_num_auto_discount_wb{
            margin-top: -4px !important;
            margin-bottom: 0px !important;
        }

        .div-discount-system{
            margin-top: 0px !important;
            display: flex;
            margin-bottom: 2px;
            align-items: center;
        }

        .general_option_label_wb:first-of-type{
            margin-top: 10px !important;
        }

        .selectable .general_option_label_wb{
            display: none;
        }

        .wb-gift-product-wrapper{
            width: 100%;
            order: 999;
            flex-basis: 100%;
            display: flex;
            padding: 10px;
            align-items: center;
            background: #d5d5d5;
            justify-content: space-between;
            margin-top: 10px;
            position: relative;
        }

        .wb-gift-product-wrapper.wb-gift-product-wrapper--upsell {
            display: none;
            gap: 10px;
            padding-left: 0!important;
        }

        .wb-gift-product-wrapper--upsell .gift-left-container {
            flex-grow: 1;
        }

        .wb-gift-product-wrapper--upsell .wb-upsell-checkbox {
            appearance: none!important;
            background: transparent!important;
            border: none!important;
            position: relative;
            flex-shrink: 0;
            width: 40px;
            height: 40px;
            margin: 0;
            margin-right: -8px;
            padding: 0;
            cursor: pointer;
        }

        .wb-gift-product-wrapper--upsell .wb-upsell-checkbox::before {
            content: "";
            display: block;
            position: absolute;
            top: 50%;
            left: 50%;
            width: 16px;
            height: 16px;
            background: rgb(244, 244, 244);
            border: 2px solid ${wideBundle.settings.border_color};
            border-radius: 5px;
            transform: translate(-50%, -50%);
        }

        .wb-gift-product-wrapper--upsell .wb-upsell-checkbox:checked::before {
            background: ${wideBundle.settings.border_color};
        }

        .wb-gift-product-wrapper--upsell .wb-upsell-checkbox:checked::after {
            content: "";
            box-sizing: content-box;
            display: block;
            content: "";
            position: absolute;
            top: 14.8px;
            left: 15.4px;
            border-right: 2px solid rgba(0,0,0,0);
            border-bottom: 2px solid rgba(0,0,0,0);
            transform-origin: 0% 100%;
            width: 3.2px;
            height: 8px;
            border-color: #ffffff;
            transform: translate3d(0, -4px, 0) rotate(45deg);
        }

        .gift-left-sub-container{
            margin-left: 10px;
            text-align: left;
        }

        .offer-free-gift.selectable .wb-gift-product-wrapper .free-gift-text{
            display: block;
        }

        .free-gift-text{
            margin: 0;
            ${wideBundle.settings.rtl == 0 ? 'text-align: left;' : ''};
            margin: 0;
            color: ${wideBundle.settings.offer_color};
        }

        .plus-circle {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            top: -12px;
            width: 24px;
            height: 24px;
            background-color: #808080;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
            font-weight: bold;
            font-family: Helvetica;
        }

        .wb-user-text-wrapper {
            display: none;
            flex-direction: column;
            gap: 4px;
            padding: 10px;
            padding-top: 0;
            padding-left: 0;
            margin-left: 0;
            margin-top: 10px;
        }

        .wb-user-text-wrapper .label-user-text {
            font-weight: 400;
            font-style: normal;
            line-height: 1.25;
        }

        .wb-user-text-wrapper .input-user-text {
            padding: 2px 4px;
            min-height: 24px;
            font-weight: 400;
            font-style: normal;
            border: 1px solid ${wideBundle.settings.border_color};
            border-radius: ${wideBundle.settings.border_radius};
        }

        .wb-user-text-wrapper .error-user-text {
            display: none;
            color: #ff0000;
            font-weight: 400;
            line-height: 1.25;
        }
        
        .wb-user-text-wrapper.wb-user-text-wrapper--has-error .input-user-text {
            border-color: #ff0000!important;
        }

        .wb-user-text-wrapper.wb-user-text-wrapper--has-error .error-user-text {
            display: block;
        }

        .selectedWB .wb-user-text-wrapper {
            display: flex;
        }

        .wb-offer-timer {
            border-top-left-radius: calc(${wideBundle.settings.unselected_border_radius} - ${wideBundle.settings.unselected_border_size});
            border-top-right-radius: calc(${wideBundle.settings.unselected_border_radius} - ${wideBundle.settings.unselected_border_size});
        }

        .selectedWB .wb-offer-timer {
            border-top-left-radius: calc(${wideBundle.settings.border_radius} - ${wideBundle.settings.border_size});
            border-top-right-radius: calc(${wideBundle.settings.border_radius} - ${wideBundle.settings.border_size});
        }

        .selectedWB .free-gift-text{
            color: ${wideBundle.settings.offer_selected_color};
            ${wideBundle.settings.style_title_selected == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title_selected == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_title_selected == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title_selected == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .selectable .free-gift-text{
            color: ${wideBundle.settings.offer_color};
            ${wideBundle.settings.style_title == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.style_title == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.style_title == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .offer-free-gift img:not(.thumbnailWB){
            width: 38px;
            height: 38px;
        }

        .gift-left-container{
            display: flex;
            align-items: center;
        }

        .gift-price-new-form{
            text-align: right;
            margin: 0px;
        }

        .offer-discount-system.offer-free-gift{
            padding: 5px 0px 5px 0px;
            padding-bottom: 0px;
            flex-wrap: wrap;
        }

        .offer-discount-system.offer-free-gift.selectedWB.with-economic-text{
            padding-bottom: 0px;
        }

        .offer-free-gift .price-new-form{
            padding-right: 10px;
        }

        .offer-free-gift .wb-gift-product-wrapper .general_option_label_wb{
            margin: 0px 0px 5px 0px !important;
        }

        .selectable .wb-gift-product-wrapper{
            background-color: ${wideBundle.settings.unselected_free_gift_background_color};
            border-bottom-left-radius: ${wideBundle.settings.unselected_border_radius};
            border-bottom-right-radius: ${wideBundle.settings.unselected_border_radius};
        }

        .selectable .wb-gift-product-wrapper .free-gift-text{
            color: ${wideBundle.settings.unselected_free_gift_text_color};
            ${wideBundle.settings.unselected_free_gift_text_style == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.unselected_free_gift_text_style == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.unselected_free_gift_text_style == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.unselected_free_gift_text_style == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .selectable .wb-gift-product-wrapper .plus-circle{
            background-color: ${wideBundle.settings.unselected_free_gift_icon_color};
        }

        .selectedWB .wb-gift-product-wrapper{
            background-color: ${wideBundle.settings.selected_free_gift_background_color};
            border-bottom-left-radius: ${wideBundle.settings.border_radius};
            border-bottom-right-radius: ${wideBundle.settings.border_radius};
        }

        .selectedWB .wb-gift-product-wrapper .free-gift-text{
            color: ${wideBundle.settings.selected_free_gift_text_color};
            ${wideBundle.settings.selected_free_gift_text_style == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.selected_free_gift_text_style == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.selected_free_gift_text_style == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.selected_free_gift_text_style == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .selectedWB .wb-gift-product-wrapper .plus-circle{
            background-color: ${wideBundle.settings.selected_free_gift_icon_color};
        }

        .selectable .wb-gift-product-wrapper .free-gift-text {
            font-size: ${wideBundle.settings.unselected_free_gift_text_fontsize};
        }

        .selectedWB .wb-gift-product-wrapper .free-gift-text { 
            font-size: ${wideBundle.settings.selected_free_gift_text_fontsize};
        }

        .title-variant--with-custom{
            display: inline;
        }

        .title-custom-text{
            font-size: ${wideBundle.settings.unselected_title_text_size};
            background-color: ${wideBundle.settings.unselected_title_text_bg};
            padding: 4px 10px;
            border-radius: ${wideBundle.settings.unselected_title_text_radius};
            color: ${wideBundle.settings.unselected_title_text_color} !important;
            border: 1px solid ${wideBundle.settings.unselected_title_text_border};
            height: fit-content;
            width: max-content;
            vertical-align: middle;
            position: relative;
            line-height: 1;
            margin-left: 6px;
            top: -1px;
            ${wideBundle.settings.unselected_title_text_font != 'auto' ? 'font-family: "' + wideBundle.settings.unselected_title_text_font + '", Arial, sans-serif;' : ''}
            ${wideBundle.settings.unselected_title_text_style == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.unselected_title_text_style == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.unselected_title_text_style == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.unselected_title_text_style == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        .selectable .title-custom-text {
            font-size: ${wideBundle.settings.unselected_title_text_size};
            background-color: ${wideBundle.settings.unselected_title_text_bg};
            color: ${wideBundle.settings.unselected_title_text_color} !important;
            border-color: ${wideBundle.settings.unselected_title_text_border};
        }

        .selectedWB .title-custom-text{
            font-size: ${wideBundle.settings.selected_title_text_size};
            background-color: ${wideBundle.settings.selected_title_text_bg};
            color: ${wideBundle.settings.selected_title_text_color} !important;
            border-color: ${wideBundle.settings.selected_title_text_border};
            border-radius: ${wideBundle.settings.selected_title_text_radius};
            ${wideBundle.settings.selected_title_text_font != 'auto' ? 'font-family: "' + wideBundle.settings.selected_title_text_font + '", Arial, sans-serif;' : ''}
            ${wideBundle.settings.selected_title_text_style == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.selected_title_text_style == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
            ${wideBundle.settings.selected_title_text_style == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
            ${wideBundle.settings.selected_title_text_style == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
        }

        @media screen and (max-width: 600px) {          
            .title-variant--with-custom {
                gap: 4px;
            }
        }

/* For cards without options - use full height for image */
.wb-gift-card:not(.has-options) .wb-gift-image-wrapper {
    height: 100%;
    border-radius: 5px;
}

/* Adjusting the content layout when there are options */
.wb-gift-card.has-options .wb-gift-card-content {
    display: flex;
    flex-direction: column;
}

.wb-gift-card.has-options .wb-gift-image-wrapper {
    height: 100%;
    width: 100%;
}

.wb-all-free-gifts-container {
    margin: 15px 0;
    padding: 0;
    border: none;
}

.wb-gifts-unlock-message {
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 15px 0;
}

.wb-gifts-cards-container {
    display:flex;
    flex-wrap:wrap;          /* let the cards break onto new rows   */
    gap:15px;                /* the same gap you already had        */
    justify-content:center;
}

/* Wrapper for both card and text */
.wb-gift-card-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex:0 1 calc(33.333% - 15px);   /* 3-per-row minus the gap     */
    max-width: 130px;
    min-width: 90px;
}

.wb-gift-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0;
    border-radius: 5px;
    position: relative;
    transition: all 0.3s ease;
    background-color: #d5d5d5;
    width: 100%;
    /* Set aspect ratio to be 1:1 with min-height to ensure square */
    aspect-ratio: 1/1;
    overflow: visible; /* Important for the animations */
}

.wb-gift-plus-icon {
    position: absolute;
    top: -12px;
    left: 50%;
    transform: translateX(-50%);
    width: 24px;
    height: 24px;
    background-color: #808080;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 18px;
    font-weight: bold;
    font-family: Helvetica;
    z-index: 2;
    transition: all 0.3s ease;
}

.wb-gift-available .wb-gift-plus-icon{
background-color: ${wideBundle.settings.selected_free_gift_icon_color};
}
.wb-gift-locked .wb-gift-plus-icon{
background-color: rgb(128, 128, 128);
}

.wb-gift-card-content {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
}

/* Text container outside the card */
.wb-gift-text-container {
    width: 100%;
    margin-top: -20px;
    z-index: 10;
    text-align: center;
}

.wb-gift-price-display{
font-size:0.8em;
background-color: ${wideBundle.settings.selected_free_gift_background_color};
border-radius:0px 0px 5px 5px;
padding: 1px 5px;
}

.wb-gift-card-wrapper-locked .wb-gift-price-display{
background-color: #dadada;
}

/* New styles for variant selectors outside card */
.wb-gift-variant-selectors-outside {
    width: 100%;
    margin-bottom: 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* Hide variant selectors for locked gifts */
.wb-gift-locked + .wb-gift-text-container .wb-gift-variant-selectors-outside {
    display: none;
}

.wb-gift-card-text {
    margin: 0;
    font-size: ${wideBundle.settings.selected_free_gift_text_fontsize};
    ${wideBundle.settings.selected_free_gift_text_style == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
    ${wideBundle.settings.selected_free_gift_text_style == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
    ${wideBundle.settings.selected_free_gift_text_style == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
    ${wideBundle.settings.selected_free_gift_text_style == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
    color: #333;
    text-align: center;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    line-height: 1.2;
}

.wb-gift-card-wrapper-locked .wb-gift-card-text{
    font-size: ${wideBundle.settings.unselected_free_gift_text_fontsize};
    ${wideBundle.settings.unselected_free_gift_text_style == 'none' ? 'font-style: normal !important;font-weight: normal !important;' : ''}
    ${wideBundle.settings.unselected_free_gift_text_style == 'bold' ? 'font-style: normal !important;font-weight: bold !important;' : ''}
    ${wideBundle.settings.unselected_free_gift_text_style == 'italic' ? 'font-style: italic !important;font-weight: normal !important;' : ''}
    ${wideBundle.settings.unselected_free_gift_text_style == 'bold-italic' ? 'font-style: italic !important;font-weight: bold !important;' : ''}
}

/* Image wrapper to allow full-width */
.wb-gift-image-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
    background-color: #f9f9f9;
}

/* Updated image styles */
.wb-gift-card-image {
    width: 100% !important;
    height: 100% !important;
    object-fit: cover;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.wb-gift-options-label {
    margin: 5px 0;
    font-size: 12px;
    color: #555;
    font-weight: 500;
    text-align: center;
}

.wb-gift-option-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 5px;
    flex-wrap: wrap;
}

.wb-gift-select {
    font-size: 12px;
    padding: 3px 6px;
    border: 1px solid #ddd;
    border-radius: 3px;
    max-width: 95%;
}

.wb-gift-swatch-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 5px;
}

/* Locked gift styles */
.wb-gift-locked {
    opacity: 0.9;
    background-color: #e4e4e4 !important;
}

.wb-gift-available {
    opacity: 1;
}

.wb-gift-lock-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 48px;
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2;
}

.wb-gift-lock-icon {
    opacity: 1 !important;
}

/* Simple bounce animation */
.wb-gift-bounce {
    animation: bounceEffect 0.5s ease;
}

.js-wb-dynamic-group {
    display: none;
    width: 100%;
    margin: 0;
    padding: 2px 0;
    ${wideBundle.settings.design_code == 1 ? 'padding-left: 4px;' : ''}
    text-align: left;
    border: none;
    background: transparent;
    color: ${wideBundle.settings.offer_color};
}

.js-wb-dynamic-group--slim {
    width: 38px;
    height: 38px;
    margin: 0;
    padding: 0;
}

.js-wb-dynamic-group .js-wb-dynamic-group__thumb {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    width: 38px;
    height: 38px;
    margin: 0;
    background: #ffffff;
    color: ${wideBundle.settings.border_color};
    font-size: 20px;
    font-weight: 700;
    font-family: inherit;
    line-height: 20px;
    border-radius: ${wideBundle.settings.design_code == 4 ? '5px' : wideBundle.settings.border_radius};
    border: 1px solid ${wideBundle.settings.border_color};
    pointer-events: none;
}

.js-wb-dynamic-group .js-wb-dynamic-group__choose {
    width: 100%;
    cursor: pointer;
    background-color: ${wideBundle.settings.atc_background};
    color: ${wideBundle.settings.atc_color};
    border-radius: ${wideBundle.settings.design_code == 4 ? '5px' : wideBundle.settings.atc_radius};
    text-align: center;
    font-size: 12px;
    border: 0;
    margin: 0;
    padding: 6px 15px;
    font-weight: 400;
    display: flex;
    align-items: center;
    justify-content: center;
    ${wideBundle.settings.atc_font != 'auto' ? 'font-family: "' + wideBundle.settings.atc_font + '"' : ''}
}

.js-wb-dynamic-group .js-wb-dynamic-group__choose:hover {
    background-color: ${wideBundle.settings.hover_color};
}

.js-wb-dynamic-group .js-wb-dynamic-group__close {
    cursor: pointer;
    background: transparent;
    color: ${wideBundle.settings.border_color};
    border: 0;
    margin: 0;
    padding: 7px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
}

.js-wb-dynamic-group .js-wb-dynamic-group__close:hover {
    background: rgb(0 0 0 / 10%);
}

.selectedWB .wb-gift-product-wrapper--upsell {
    display: flex;
    padding-left: 0!important;
}

.selectedWB .js-wb-dynamic-group {
    display: flex;
    gap: ${wideBundle.settings.design_code == 1 ? '8px' : '12px'};
    align-items: center;
    justify-content: flex-start;
    color: ${wideBundle.settings.offer_selected_color};
}

.selectedWB .js-wb-dynamic-group--slim {
    display: flex;
}

#wb-dynamic-group-popup.wb-dg-popup {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: env(safe-area-inset-top, 0);
    left: 0;
    width: 100%;
    height: 100svh;
    overflow: hidden;
    z-index: 9999;
}

#wb-dynamic-group-popup .wb-dg-popup__content {
    display: grid;
    grid-template-rows: auto 1fr auto;
    gap: 24px;
    width: 100%;
    height: 100%;
    padding: 16px 24px;
    background: #ffffff; /* var(--wb-msg-bg-color, #ffffff); */
}

#wb-dynamic-group-popup .wb-dg-popup__header {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
}

#wb-dynamic-group-popup .wb-dg-popup__title {
    margin: 0;
    color: var(--wb-title-color, #000000);
    font-family: var(--wb-title-font, inherit);
    font-weight: 600;
    font-size: var(--wb-title-font-size, 24px);
    text-transform: none;
}

#wb-dynamic-group-popup .wb-dg-popup__close-btn {
    display: grid;
    flex-shrink: 0;
    place-content: center;
    padding: 8px;
    border: none;
    border-radius: 50%;
    color: var(--wb-atc-color, #ffffff);
    background: var(--wb-atc-bg, #000000);
    cursor: pointer;
}

#wb-dynamic-group-popup .wb-dg-popup__close-btn:hover {
    opacity: 0.8;
}

#wb-dynamic-group-popup .wb-dg-popup__products {
    overflow-x: hidden;
    overflow-y: auto;
    margin: 0;
    padding: 0;
    list-style: none;
}

#wb-dynamic-group-popup .wb-dg-popup-product {
    display: flex;
    align-items: center;
    gap: 16px;
    margin: 0;
    padding: 0 12px;
    border-top: 1px solid var(--wb-option-border-color, #dadada);
}

#wb-dynamic-group-popup .wb-dg-popup-product:hover {
    background: rgb(0 0 0 / 10%);
}

#wb-dynamic-group-popup .wb-dg-popup-product:has(input:checked) {
    background: rgb(0 0 0 / 15%);
}

#wb-dynamic-group-popup .wb-dg-popup-product__input {
    appearance: none;
    display: grid;
    place-content: center;
    flex-shrink: 0;
    background-color: transparent;
    margin: 0;
    padding: 0;
    width: 20px;
    height: 20px;
    border: var(--wb-msg-border-size, 2px) solid var(--wb-atc-bg, #000000);
    border-radius: 0;
    cursor: pointer;
}

#wb-dynamic-group-popup .wb-dg-popup-product__input:checked {
    background-color: var(--wb-atc-bg, #000000);
}

#wb-dynamic-group-popup .wb-dg-popup-product__input:checked::before {
    content: "✓";
    place-content: center;
    display: grid;
    width: 20px;
    height: 20px;
    color: var(--wb-atc-color, #ffffff);
    background: var(--wb-atc-bg, #000000);
    font-size: 15px;
    font-weight: 600;
    line-height: 20px;
}

#wb-dynamic-group-popup .wb-dg-popup-product__label {
    display: flex;
    gap: 16px;
    flex-grow: 1;
    flex-shrink: 1;
    align-items: center;
    max-width: 95%;
    padding: 12px 0;
    font-weight: 600;
    cursor: pointer;
}

#wb-dynamic-group-popup .wb-dg-popup-product__image {
    position: relative;
    border-radius: 8px;
    flex-shrink: 0;
    width: 64px;
    height: 64px;
}

#wb-dynamic-group-popup .wb-dg-popup-product__image::after {
  content: "";
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  position: absolute;
  inset: 0px;
}

#wb-dynamic-group-popup .wb-dg-popup-product__thumb {
    width: 100%;
    height: 100%;
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
}

#wb-dynamic-group-popup .wb-dg-popup-product__title {
    font-size: 18px;
    line-height: 20px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

#wb-dynamic-group-popup .wb-dg-popup__footer {
    width: 100%;
}

#wb-dynamic-group-popup .wb-dg-popup__submit-btn {
    width: 100%;
    padding: 16px 32px;
    border: none;
    border-radius: var(--wb-atc-radius, 8px);
    color: var(--wb-atc-color, #ffffff);
    background: var(--wb-atc-bg, #000000);
    font-family: var(--wb-atc-font, inherit);
    font-size: var(--wb-atc-font-size, 18px);
    font-weight: 500;
    cursor: pointer;
}

#wb-dynamic-group-popup .wb-dg-popup__submit-btn:hover {
    opacity: 0.8;
}

#wb-dynamic-group-popup .wb-dg-popup__submit-btn:disabled {
    opacity: 0.5!important;
    pointer-events: none!important;
}

#wb-dynamic-group-popup .wb-dg-popup__overlay {
    display: none;
}

@media screen and (min-width: 520px) {
    #wb-dynamic-group-popup.wb-dg-popup {
        padding: 32px;
    }
    
    #wb-dynamic-group-popup .wb-dg-popup__content {
        max-width: 760px;
        max-height: 800px;
        border-radius: 12px; /* var(--wb-msg-border-radius, 12px); */
    }

    #wb-dynamic-group-popup .wb-dg-popup__footer {
        width: fit-content;
        justify-self: end;
    }

    #wb-dynamic-group-popup .wb-dg-popup__overlay {
        position: absolute;
        inset: 0;
        display: block;
        background: rgb(0 0 0 / 40%);
        z-index: -1;
    }
}

@keyframes bounceEffect {
    0% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.1);
    }
    100% {
        transform: scale(1);
    }
}

    `;

    addStyleToPage(mainStyle, attribute);
}

//Add the style based on structure used
wideBundle.addStructureStyle = function (attribute = 'structure') {

    if(document.querySelector('.block-settings') !== null){
        var structure = wideBundle.settings.design_code; //Layout chosen
    }
    else{
        var structure = wideBundle.settings.plan == "monthly" && wideBundle.settings.design_code > 3 ? 0 : wideBundle.settings.design_code; //Layout chosen
    }

    if (structure == 0) { //For basic and default design
        if (wideBundle.settings.display_quantity == 1) { //Add style for quantity button if enabled
            var style = `
                .value-left .offer-image{
                    min-width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "90px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "110px" : "130px")} !important;;
                }
                .selectedWB .offer-image{
                    min-width: ${wideBundle.settings.thumbnail_size == "s" ? "90px" : (wideBundle.settings.thumbnail_size == "m" ? "110px" : "130px")} !important;;
                }
                .selectedWB{
                    position: relative;
                    padding-bottom: 10px;
                }
                .spinWB{
                    position: static;
                    height: 30px;
                    right: 5px;
                    bottom: 5px;
                    margin: 0px;
                    margin-left: auto;
                }
                .quantity-wb-input{
                    height: 30px;
                }
                .selectable{
                    padding-bottom: 10px;
                }
                @media screen and (max-width: 400px){
                    .selectedWB{
                        position: relative;
                        padding-bottom: 40px;
                    }
                    .spinWB{
                        position: absolute;
                        height: 25px;
                        right: 5px;
                        bottom: 5px;
                        margin: 0px;
                    }
                    .quantity-wb-input{
                        height: 25px;
                    }
                }
            `;
            addStyleToPage(style, attribute);
        }
    }
    else if (structure == 1) { //For vertical layout
        var style = `
            .div-discount-system{
                flex-direction: row;
            }
            .general_option_label_wb:not(.wb-gift-product-wrapper .general_option_label_wb) {
                text-align: center;
            }
            .title-variant{
                text-align: center;
                margin-top: 10px;
            }
            .selectedWB .title-variant{
                font-size: ${(parseFloat(wideBundle.settings.selected_title_fontsize) -0.2) + 'em' };
            }
            .selectable .title-variant{
                font-size: ${(parseFloat(wideBundle.settings.unselected_title_fontsize) -0.2) + 'em' };
            }
            .new-form-option .first-unit-WB{
                margin-left: auto;
                margin-bottom: 0px;
                padding-left: 10px;
                text-align: center;
                display: flex;
                flex-direction: column;
            }
            .price-new-form, .first-unit-WB{
                //font-size: ${wideBundle.settings.price_size};
                text-align: center;
            }
            .best-title{
                width: 100%;
                text-align: center;
                display: block;
                margin-top: 10px;
            }
            .economic-wb{
                text-align: center;
            }
            .selectedWB .economic-wb{
                font-size: ${(parseFloat(wideBundle.settings.selected_savings_fontsize) -0.1) + 'em' };
            }
            .selectable .economic-wb{
                font-size: ${(parseFloat(wideBundle.settings.unselected_savings_fontsize) -0.1) + 'em' };
            }
            .p-title-WB{
                width: 100%;
                flex-basis: 100%;
            }
            #new-form, .new-wb-form{
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;
            }
            .new-form-option{
                display: block;
                padding: 10px 10px 10px 10px;
                margin: 7px;
                flex: 1;
            }
            .offer-with-gift-flex-wrapper{
                display: block;
                width: 100%;
            }
            .value-right{
                max-width: 100%;
                text-align: center;
            }
            .value-left{
                display: block;
            }
            .value-left img{
                margin: 0;
            }
            .checkedWB{
                margin: auto;
                margin-top: 5px;
                margin-bottom: 10px;
            }
            #new-form .select-class-second, .new-wb-form .select-class-second{
                margin: 2px 0px 0px 0px;
            }
            #new-form .select-class-first, .new-wb-form .select-class-first{
                margin: 2px 0px 0px 0px;
            }
            .selectedWB .div-select2{
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-bottom: 5px;
                justify-content: center;
            }
            .selectedWB .div-select2 p{
                margin-top: 7px;
                margin-bottom: 3px;
            }
            .selectable{
                border: ${wideBundle.settings.unselected_border_size} solid ${wideBundle.settings.unselected_border_color};
            }
            .new-form-option .value-left{
                flex-direction: column;
            }
            
            .wb-swatch-container .title-option-wb {
                text-align: center;
            }

            .wb-swatch-container .title-option-wb.label_num_auto_discount_wb {
                text-align: initial;
            }
            
            .wb-swatch-container .wb-color-swatch-box {
                margin-right: 0;
                justify-content: center;
            }

            .offer-free-gift .value-right{
                width: 100%;
            }
            .offer-free-gift{
                display: flex;
                flex-direction: column;
                flex-wrap: wrap;
            }
            .offer-free-gift .wb-gift-product-wrapper{
                margin-top: auto;
                flex-basis: auto;
            }
            .offer-free-gift .price-new-form{
                padding-right: 0px;
            }
            .offer-discount-system .block_dropdowns_wb:not(.wb-gift-product-wrapper .block_dropdowns_wb) {
                display: flex;
                flex-wrap: wrap;
                padding: 5px;
                justify-content: center;
            }
            .wb-user-text-wrapper {
                margin-left: 0;
                width: 100%;
            }
        `;
        if (wideBundle.settings.display_quantity == 1) {
            style += `
                .selectedWB{
                    position: relative;
                    padding-bottom: 5px;
                }
                .selectedWB .spinWB{
                    position: static;
                    height: 30px;
                    right: 5px;
                    bottom: 5px;
                    margin: auto;
                    margin-top: 10px;
                }
                .selectedWB .quantity-wb-input{
                    height: 30px;
                    line-height: 30px;
                }
                .selectable{
                    padding-bottom: 5px;
                }
            `;
        }
        addStyleToPage(style, attribute);
    }
    else if (structure == 2) { //For minimalist layout
        var style = `
            .thumbnailWB{
                width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "30px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "40px" : "50px")} !important;
            }

            .selectedWB .thumbnailWB{
                width: ${wideBundle.settings.thumbnail_size == "s" ? "30px" : (wideBundle.settings.thumbnail_size == "m" ? "40px" : "50px")} !important;
            }

            .offer-image{
                min-width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "78px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "88px" : "98px")} !important;
            }

            .selectedWB .offer-image{
                min-width: ${wideBundle.settings.thumbnail_size == "s" ? "78px" : (wideBundle.settings.thumbnail_size == "m" ? "88px" : "98px")} !important;
            }

            .new-form-option{
                position: relative;
                padding: 5px 10px 5px 0px;
            }
            .offer-with-gift-flex-wrapper{
                position:relative; 
            }
            .selectedWB .title-variant{
                font-size: ${(parseFloat(wideBundle.settings.selected_title_fontsize) -0.2) + 'em' };
            }
            .selectable .title-variant{
                font-size: ${(parseFloat(wideBundle.settings.unselected_title_fontsize) -0.2) + 'em' };
            }
            .new-form-option .price-new-form, .new-form-option .first-unit-WB{
                ${wideBundle.settings.rtl == 1 ? 'margin-right: auto;' : 'margin-left: auto;'}
                ${wideBundle.settings.rtl == 1 ? 'text-align: left;' : 'text-align: right;'}
                margin-bottom: 0px;
                padding-left: 10px;
                ${wideBundle.settings.rtl == 1 ? 'padding-right: 10px;' : ''}
            }

            .new-form-option .first-unit-WB{
                text-align: center;
                display: flex;
                flex-direction: column;
            }
            .economic-wb{
                margin-top: 0px;
                margin-bottom: 0px;
            }
            span.money.first-price-WB, .first-price-WB{
                margin-right: 0px;
                white-space: nowrap;
                overflow: hidden;
            }
            span.money.second-price-WB, .second-price-WB{
                margin-left: 5px;
                white-space: nowrap;
                overflow:hidden;
            }
            .div-select2{
                margin-top: 5px;
            }
            .checkedWB{
                width: 12px;
                height: 12px;
                border: 2px solid rgb(244, 244, 244);
            }
            .title-option-wb{
                margin-bottom: 0px;
            }

            .diagonal-offer{
                padding-right: 40px !important;
            }

            @media screen and (max-width: 600px){
                .title-option-wb{
                    width: 100%;
                    margin-bottom: 0px;
                }
                .div-discount-system .title-option-wb{
                    width: auto;
                    margin-bottom: 0px;
                }

                .thumbnailWB{
                    width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "30px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "40px" : "40px")} !important;
                }

                .selectedWB .thumbnailWB{
                    width: ${wideBundle.settings.thumbnail_size == "s" ? "30px" : (wideBundle.settings.thumbnail_size == "m" ? "40px" : "40px")} !important;
                }

                .offer-image{
                    min-width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "78px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "88px" : "88px")} !important;
                }

                .selectedWB .offer-image{
                    min-width: ${wideBundle.settings.thumbnail_size == "s" ? "78px" : (wideBundle.settings.thumbnail_size == "m" ? "88px" : "88px")} !important;
                }
            }

            @media screen and (max-width: 400px){
                #new-form .select-option-third, .new-wb-form .select-option-third{
                    margin-top: 2px;
                    margin-left: 0px;
                }
                #new-form .div-discount-system .select-option-third, .new-wb-form .div-discount-system .select-option-third{
                    margin-top: 0px;
                }
                #new-form .select-option-second, .new-wb-form .select-option-second{
                    float: none;
                }
                #new-form .div-discount-system .select-option-second, .new-wb-form .div-discount-system .select-option-second{
                    float: left;
                }
            }
        `;
        if (wideBundle.settings.display_quantity == 1) {
            style += `
                .spinWB{
                  margin-top: 5px;
                  margin-bottom: 5px;
                  margin-left: 10px;
                }
                .selectedWB{
                  position: relative;
                  padding-bottom: 5px;
                }
                .selectedWB .spinWB{
                  position: static;
                  height: 30px;
                  right: 5px;
                  bottom: 5px;
                  margin: 0px;
                  margin-left: 5px;
                }
                .selectedWB .quantity-wb-input{
                  height: 30px;
                }
                .selectable{
                  padding-bottom: 5px;
                }
                @media screen and (max-width: 400px){
                    .selectedWB{
                        position: relative;
                        padding-bottom: 40px;
                    }
                    .selectedWB .spinWB{
                        position: absolute;
                        height: 25px;
                        right: 5px;
                        bottom: 5px;
                    }
                    .selectedWB .quantity-wb-input{
                        height: 25px;
                    }
                }
            `;
        }
        //We hve to move the price and quantity to the right of the offer for that layout
        var elemsUnit = document.querySelectorAll('.new-form-option .first-unit-WB');
        for (var i = 0; i < elemsUnit.length; i++) {
            if (!elemsUnit[i].closest(".value-right")) continue;

            offerNode = elemsUnit[i].parentNode.parentNode;
            offerNode.appendChild(elemsUnit[i]);
        }

        var elems = document.querySelectorAll('.new-form-option .price-new-form');
        for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

            offerNode = elems[i].parentNode.parentNode;
            offerNode.appendChild(elems[i]);
            if (wideBundle.settings.display_quantity == 1) {
                quantityElem = document.querySelectorAll('.spinWB')[i];
                offerNode.appendChild(quantityElem);
            }
        }
        addStyleToPage(style, attribute);
    }
    else if (structure == 3) { //For royal layout
        var style = `
            .new-form-option .price-new-form, .new-form-option .first-unit-WB{
                ${wideBundle.settings.rtl == 1 ? 'margin-right: auto;' : 'margin-left: auto;'}
                ${wideBundle.settings.rtl == 1 ? 'text-align: left;' : 'text-align: right;'}
                margin-bottom: 0px;
                padding-left: 10px;
                ${wideBundle.settings.rtl == 1 ? 'padding-right: 10px;' : ''}
            }

            .new-form-option .first-unit-WB{
                text-align: center;
                display: flex;
                flex-direction: column;
            }

            span.money.first-price-WB, .first-price-WB{
                margin-right: 0px;
                white-space: nowrap;
                overflow: hidden;
            }
            span.money.second-price-WB, .second-price-WB{
                margin-left: 5px;
                white-space: nowrap;
                overflow: hidden;
            }
            .new-form-option{
                position: relative;
                padding: 5px 10px 5px 0px;
            }
            .offer-with-gift-flex-wrapper{
                position: relative;
            }
            .with-message .div-select2{
                margin-top: 10px;
            }
            .with-message .title-variant{
                margin-bottom: -5px;
            }
            .economic-wb{
                margin-top: 0px;
                margin-bottom: 0px;
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translate(-50%, 50%);
                background-color: ${wideBundle.settings.border_color};
                padding: 3px 40px 3px 40px;
                border-radius: 5px;
                white-space: nowrap;
                overflow: hidden;
                z-index: 1;
            }
            .with-economic-text{
                padding-bottom: 20px;
                margin-bottom: 18px;
            }
            .value-right.with-message{
                padding-bottom: 20px;
            }

            .diagonal-offer{
                padding-right: 40px !important;
            }

            @media screen and (max-width: 600px){
                .title-option-wb{
                    margin-bottom: 0px;
                }
                .has-double-select .title-option-wb{
                    width: 100%;
                }
                .has-double-select.div-discount-system .title-option-wb{
                    width: auto;
                }
                .offer-image img{
                    width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "30px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "40px" : "60px")};
                }
                .selectedWB .offer-image img{
                    width: ${wideBundle.settings.thumbnail_size == "s" ? "30px" : (wideBundle.settings.thumbnail_size == "m" ? "40px" : "60px")};
                }
                .offer-image{
                    min-width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "80px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "90px" : "110px")};
                }
                .selectedWB .offer-image{
                    min-width: ${wideBundle.settings.thumbnail_size == "s" ? "80px" : (wideBundle.settings.thumbnail_size == "m" ? "90px" : "110px")};
                }
                .selectedWB .title-variant{
                    font-size: ${(parseFloat(wideBundle.settings.selected_title_fontsize) -0.2) + 'em' };
                }
                .selectable .title-variant{
                    font-size: ${(parseFloat(wideBundle.settings.unselected_title_fontsize) -0.2) + 'em' };
                }
            }

            @media screen and (max-width: 400px){
                #new-form .select-option-third, .new-wb-form .select-option-third{
                    margin-top: 2px;
                    margin-left: 0px;
                }
                #new-form .div-discount-system .select-option-third, .new-wb-form .div-discount-system .select-option-third{
                    margin-top: 0px;
                }
                #new-form .select-option-second, .new-wb-form .select-option-second{
                    float: none;
                }
                #new-form .div-discount-system .select-option-second, .new-wb-form .div-discount-system .select-option-second{
                    float: left;
                }
            }
        `;
        if (wideBundle.settings.display_quantity == 1) {
            style += `
                .spinWB{
                    margin-top: 5px;
                    margin-bottom: 5px;
                    margin-left: 10px;
                }
                .selectedWB{
                    position: relative;
                    padding-bottom: 5px;
                }
                .selectedWB.with-economic-text{
                  padding-bottom: 20px;
                }
                .selectedWB .spinWB{
                    position: static;
                    height: 30px;
                    right: 5px;
                    bottom: 5px;
                    margin: 0px;
                    margin-left: 5px;
                }
                .selectedWB .quantity-wb-input{
                    height: 30px;
                }
                .selectable{
                    padding-bottom: 5px;
                }
                .selectable.with-economic-text{
                    padding-bottom: 20px;
                }
                @media screen and (max-width: 400px){
                    .selectedWB{
                        position: relative;
                        padding-bottom: 40px;
                    }
                    .selectedWB.with-economic-text{
                      padding-bottom: 40px;
                    }
                    .selectedWB .spinWB{
                        position: absolute;
                        height: 25px;
                        right: 5px;
                        bottom: 20px;
                    }
                    .selectedWB .quantity-wb-input{
                        height: 25px;
                    }
                }
            `;
        }
        //We have to move the price and quantity to the right of the offer for that layout
        var elemsUnit = document.querySelectorAll('.new-form-option .first-unit-WB');
        for (var i = 0; i < elemsUnit.length; i++) {
            if (!elemsUnit[i].closest(".value-right")) continue;

            offerNode = elemsUnit[i].parentNode.parentNode;
            offerNode.appendChild(elemsUnit[i]);
        }

        var elems = document.querySelectorAll('.new-form-option .price-new-form');
        for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

            offerNode = elems[i].parentNode.parentNode;
            offerNode.appendChild(elems[i]);
            if (wideBundle.settings.display_quantity == 1) {
                quantityElem = document.querySelectorAll('.spinWB')[i];
                offerNode.appendChild(quantityElem);
            }
        }
        //We have to move the economic price
        var elems = document.querySelectorAll('.new-form-option .economic-wb');
        for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

            elems[i].closest('.new-form-option').appendChild(elems[i]);
        }
        addStyleToPage(style, attribute);
    }

    else if (structure == 4) { //For elegant layout
        var style = `
            .new-form-option .price-new-form, .new-form-option .first-unit-WB{
                ${wideBundle.settings.rtl == 1 ? 'margin-right: auto;' : 'margin-left: auto;'}
                ${wideBundle.settings.rtl == 1 ? 'text-align: left;' : 'text-align: right;'}
                margin-bottom: 0px;
                padding-left: 20px;
                ${wideBundle.settings.rtl == 1 ? 'padding-right: 10px;' : ''}
                display: flex;
                flex-direction: column;
            }
            .new-form-option .first-unit-WB{
                text-align: center;
                display: flex;
                flex-direction: column;
            }
            span.money.first-price-WB, .first-price-WB{
                margin-right: 0px;
                white-space: nowrap;
                overflow: hidden;
            }
            span.money.second-price-WB, .second-price-WB{
                margin-left: 5px;
                white-space: nowrap;
                overflow: hidden;
            }
            .new-form-option{
                position: relative;
                padding: 10px 10px 10px 0px;
                margin-bottom: 0px;
                border-radius: 0px;
                border-top: 0px !important;
                border-color: ${wideBundle.settings.border_color} !important;
            }
            .offer-with-gift-flex-wrapper{
               position:relative;
            }
            .with-message .div-select2{
                margin-top: 10px;
            }
            .with-message .title-variant{
                margin-bottom: -5px;
            }
            .checkedWB {
                box-shadow: 0 0 0 2px ${wideBundle.settings.border_color};
                border: 2px solid #f4f4f4;
                border-radius: 5px;
                width: 15px;
                height: 15px;
            }
            .economic-wb{
                position: absolute;
                bottom: 0;
                right: 0;
                border-top-left-radius: 5px;
                background-color: ${wideBundle.settings.border_color};
                padding: 3px 40px 3px 40px;
                white-space: nowrap;
                overflow: hidden;
            }
            .selectable .economic-wb {
                padding: ${parseInt(wideBundle.settings.unselected_border_size) + 3}px 8px 3px ${parseInt(wideBundle.settings.unselected_border_size) + 8}px;
            }
            .selectedWB .economic-wb {
                padding: ${parseInt(wideBundle.settings.border_size) + 3}px 8px 3px ${parseInt(wideBundle.settings.border_size) + 8}px;
            }
            .selectable.with-economic-text:not(.offer-free-gift.selectable.with-economic-text){
                padding-bottom: ${(parseInt(wideBundle.settings.unselected_border_size) / 2) + 30}px !important;
            }
            .offer-free-gift.selectable.with-economic-text .wb-gift-product-wrapper{
                padding-bottom: 20px;
            }
            .offer-free-gift.selectedWB.with-economic-text .wb-gift-product-wrapper{
                padding-bottom: 20px;
            }
            .selectedWB.with-economic-text:not(.offer-free-gift.selectedWB.with-economic-text){
                padding-bottom: ${(parseInt(wideBundle.settings.border_size) / 2) + 30}px !important;
            }
            .p-title-WB{
                background-color: ${wideBundle.settings.border_color};
                margin: 0px;
                padding: 8px 0px;
                overflow: unset;
                border-radius: 5px 5px 0px 0px;
            }

            .p-title-WB__content {
                ${wideBundle.settings.preview_heading_position == 'left' ? 'margin: 0 auto 0 10px;' : ''}
                ${wideBundle.settings.preview_heading_position == 'center' ? 'margin: 0 auto;' : ''}
                ${wideBundle.settings.preview_heading_position == 'right' ? 'margin: 0 10px 0 auto;' : ''}
             }
            .p-title-WB__arrow{
                z-index: 1;
            }
            .p-title-WB__arrow::before{
                content: '';
                position: absolute;
                top: 100%;
                left: calc(50% - 10px);
                background-color: ${wideBundle.settings.border_color};
                width: 20px;
                height: 10px;
                clip-path: polygon(0 0, 100% 0, 50% 100%);
            }
            .corner-offer-container{
                margin-top: 0px;
            }
            .diagonal-offer{
                padding-right: 40px !important;
            }
            #new-form-atc, .new-form-atc{
                border-radius: 5px;
            }
            .settings-preview-main-wrapper{
                margin-top: 15px !important;
            }
            .best-title{
                display: inline-block;
            }
            #new-form .selectable, .new-wb-form .selectable, #new-form .selectedWB, .new-wb-form .selectedWB{
                border-radius: 0px;
            }

            #new-form .selectable .wb-offer-timer,
            #new-form .selectedWB .wb-offer-timer,
            .new-wb-form .selectable .wb-offer-timer,
            .new-wb-form .selectedWB .wb-offer-timer {
                border-radius: 0px;
            }

            #new-form .selectable .wb-gift-product-wrapper,
            #new-form .selectedWB .wb-gift-product-wrapper,
            .new-wb-form .selectable .wb-gift-product-wrapper,
            .new-wb-form .selectedWB .wb-gift-product-wrapper {
                border-bottom-left-radius: 0px;
                border-bottom-right-radius: 0px;
            }

            @media screen and (max-width: 600px){
                .title-option-wb{
                    margin-bottom: 0px;
                }
                .has-double-select .title-option-wb{
                    width: 100%;
                }
                .has-double-select.div-discount-system .title-option-wb{
                    width: auto;
                }
                .offer-image img{
                    width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "30px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "40px" : "60px")};
                }
                .selectedWB .offer-image img{
                    width: ${wideBundle.settings.thumbnail_size == "s" ? "30px" : (wideBundle.settings.thumbnail_size == "m" ? "40px" : "60px")};
                }
                .offer-image{
                    min-width: ${wideBundle.settings.unselected_thumbnail_size == "s" ? "80px" : (wideBundle.settings.unselected_thumbnail_size == "m" ? "90px" : "110px")};
                }
                .selectedWB .offer-image{
                    min-width: ${wideBundle.settings.thumbnail_size == "s" ? "80px" : (wideBundle.settings.thumbnail_size == "m" ? "90px" : "110px")};
                }
                .selectedWB .title-variant{
                    font-size: ${(parseFloat(wideBundle.settings.selected_title_fontsize) -0.2) + 'em' };
                }
                .selectable .title-variant{
                    font-size: ${(parseFloat(wideBundle.settings.unselected_title_fontsize) -0.2) + 'em' };
                }
            }

            @media screen and (max-width: 400px){
                .select-option-third{
                    margin-top: 2px;
                    margin-left: 0px;
                }
                .select-option-second{
                    float: none;
                }
            }
        `;
        if (wideBundle.settings.display_quantity == 1) {
            style += `
                .spinWB{
                    margin-top: 5px;
                    margin-bottom: 5px;
                    margin-left: 10px;
                }
                .selectedWB{
                    position: relative;
                    padding-bottom: 5px;
                }
                .selectedWB.with-economic-text{
                  padding-bottom: 20px;
                }
                .selectedWB .spinWB{
                    position: static;
                    height: 30px;
                    right: 5px;
                    bottom: 5px;
                    margin: 0px;
                    margin-left: 5px;
                }
                .selectedWB .quantity-wb-input{
                    height: 30px;
                }
                .selectable{
                    padding-bottom: 10px;
                }
                .selectable.with-economic-text{
                    padding-bottom: 20px;
                }
                @media screen and (max-width: 400px){
                    .selectedWB{
                        position: relative;
                        padding-bottom: 40px;
                    }
                    .selectedWB.with-economic-text{
                      padding-bottom: 40px;
                    }
                    .selectedWB .spinWB{
                        position: absolute;
                        height: 25px;
                        right: 5px;
                        bottom: 40px;
                    }
                    .selectedWB .quantity-wb-input{
                        height: 25px;
                    }
                }
            `;
        }
        //We have to move the price and quantity to the right of the offer for that layout
        var elemsUnit = document.querySelectorAll('.new-form-option .first-unit-WB');
        for (var i = 0; i < elemsUnit.length; i++) {
            if (!elemsUnit[i].closest(".value-right")) continue;

            offerNode = elemsUnit[i].parentNode.parentNode;
            offerNode.appendChild(elemsUnit[i]);
        }

        //We have to move the price and quantity to the right of the offer for that layout
        var elems = document.querySelectorAll('.new-form-option .price-new-form');
        for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

            offerNode = elems[i].parentNode.parentNode;
            offerNode.appendChild(elems[i]);
            if (wideBundle.settings.display_quantity == 1) {
                quantityElem = document.querySelectorAll('.spinWB')[i];
                offerNode.appendChild(quantityElem);
            }
        }

        //We have to add round corners to last offer for elegant design
        var elems = document.querySelectorAll('#new-form, .new-wb-form ');
        for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

            formOffers = elems[i].querySelectorAll(".new-form-option");
            lastOffer = formOffers[formOffers.length - 1]
            lastOffer.style.borderRadius = '0px 0px 5px 5px';
        }

        //We have to move the economic price
        var elems = document.querySelectorAll('.new-form-option .economic-wb');
        for (var i = 0; i < elems.length; i++) {
            elems[i].closest('.new-form-option').appendChild(elems[i]);
        }
        addStyleToPage(style, attribute);
    }

    else if (structure == 5) { //For solid layout
        var style = `
            .selectedWB .title-variant{
                margin-top: 10px;
                font-size: ${(parseFloat(wideBundle.settings.selected_title_fontsize) -0.2) + 'em' };
            }
            .selectable .title-variant{
                margin-top: 10px;
                font-size: ${(parseFloat(wideBundle.settings.unselected_title_fontsize) -0.2) + 'em' };
            }
            .best-title{
                width: auto;
                display: block;
                margin-top: 10px;
            }
            .economic-wb{
                margin: 0px auto;
                position: absolute;
                background-color: white;
                padding: 4px 8px;
                overflow: hidden;
                //max-width: 80%;
                rotate: -3deg;
                left: 50%;
                transform: translateX(-50%);
                white-space: nowrap;
                z-index: 1;
            }
            .selectable .economic-wb{
                bottom: ${-10 - parseInt(wideBundle.settings.unselected_border_size)}px;
                border: 3px solid ${wideBundle.settings.background_color};
            }
            .selectedWB .economic-wb{
                bottom: -18px;
                border: 3px solid ${wideBundle.settings.background_color};

            }
            .with-economic-text{
                position: relative;
                padding-bottom: 20px;
                margin-bottom: 18px;
            }
            .p-title-WB{
                width: 100%;
                flex-basis: 100%;
            }
            .selectable.corner-offer-container{
                padding-top: 10px !important;
            }
            .selectedWB.corner-offer-container{
                padding-top: 0px !important;
            }
            #new-form, .new-wb-form{
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;
            }
            .new-form-option{
                display: block;
                padding: 0px;
                margin: 7px 1px;
                flex: 1;
                border-radius: 0px;
                padding-bottom: 30px;
            }
            .offer-with-gift-flex-wrapper{
                display: block;
                width: 100%;
            }
            .selectedWB .best-title {
                width: auto;
            }
            .value-right{
                max-width: 100%;
                display: flex;
                flex-direction: column;
            }
            .offer-free-gift .value-right{
                width: 100%;
            }
            .offer-free-gift{
                display: flex;
                flex-direction: column;
                flex-wrap: wrap;
            }
            .offer-free-gift .wb-gift-product-wrapper{
                margin-top: auto;
                flex-basis: auto;
            }
            .value-right > *{
                margin-right: 10px !important;
                margin-left: 10px !important;
            }
            .value-right .price-new-form, .value-right .first-unit-WB{
                margin: 0px !important;
                padding-left: 8px;
                padding-bottom: 5px;
            }
            .value-left{
                display: block;
            }
            .value-left img{
                margin: 5px 0px;
            }
            .selectedWB .price-new-form, .selectedWB .first-unit-WB{
                margin: 0px 0px 10px 0px !important;
                top: 10px;
                position: relative;
                border-bottom: 1px solid white;
            }
            .selectedWB .value-left{
                top: 10px;
                position: relative;
            }
            .selectable .price-new-form, .selectable .first-unit-WB{
                border-bottom: 1px solid ${wideBundle.settings.unselected_border_color};
            }
            .checkedWB{
                display: none;
            }
            #new-form .select-class-second.discount_system_select_wb, .new-wb-form .select-class-second.discount_system_select_wb{
                margin: 0px 0px 0px 0px;
            }
            #new-form .select-class-second, .new-wb-form .select-class-second{
                margin: 2px 0px 0px 0px;
            }
                #new-form .select-class-first.discount_system_select_wb, .new-wb-form .select-class-first.discount_system_select_wb{
                margin: 0px 0px 0px 0px;
            }
            #new-form .select-class-first, .new-wb-form .select-class-first{
                margin: 2px 0px 0px 0px;
            }
            .selectedWB .div-select2{
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                margin-bottom: 5px;
                justify-content: center;
            }
            .selectedWB.offer-discount-system .div-select2{
                flex-direction: row;
                align-items: flex-start;
                margin-bottom: 0px;
                justify-content: normal;
            }
            .selectedWB .div-select2 p{
                margin-top: 7px;
                margin-bottom: 3px;
            }
            .selectable{
                border: ${wideBundle.settings.unselected_border_size} solid ${wideBundle.settings.unselected_border_color};
                margin-top: 20px;
            }
            .selectedWB{
                border: 0px !important;
                border-bottom: 8px solid ${wideBundle.settings.border_color} !important;
            }
            .new-form-option .value-left{
                flex-direction: column;
            }

            .selectable.offer-discount-system.selectedWB.with-economic-text{
                display: flex;
                flex-direction: column;
                flex-wrap: wrap;
            }

            .offer-free-gift .value-right{
                margin-bottom: 10px;
            }
            #new-form .selectable, .new-wb-form .selectable, #new-form .selectedWB, .new-wb-form .selectedWB{
                border-radius: 0px;
            }
            .wb-user-text-wrapper {
                margin-left: 0;
                width: 100%;
            }

            #new-form .selectable .wb-offer-timer,
            #new-form .selectedWB .wb-offer-timer,
            .new-wb-form .selectable .wb-offer-timer,
            .new-wb-form .selectedWB .wb-offer-timer {
                border-radius: 0px;
            }

            #new-form .selectable .wb-gift-product-wrapper,
            #new-form .selectedWB .wb-gift-product-wrapper,
            .new-wb-form .selectable .wb-gift-product-wrapper,
            .new-wb-form .selectedWB .wb-gift-product-wrapper {
                border-bottom-left-radius: 0px;
                border-bottom-right-radius: 0px;
            }
        `;
        if (wideBundle.settings.display_quantity == 1) {
            style += `
                .selectedWB{
                    position: relative;
                }
                .selectedWB .spinWB{
                    position: static;
                    height: 30px;
                    right: 5px;
                    bottom: 5px;
                    margin: auto;
                    margin-top: 10px;
                }
                .selectedWB .quantity-wb-input{
                    height: 30px;
                    line-height: 30px;
                }
            `;
        }

         //We have to move the price under thumbnail
         var elems = document.querySelectorAll('.new-form-option .price-new-form');
         for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

             elems[i].parentNode.insertBefore(elems[i], elems[i].parentNode.firstChild);
         }

         //We have to move the unit price under thumbnail
         var elems = document.querySelectorAll('.new-form-option .first-unit-WB');
         for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

             elems[i].parentNode.insertBefore(elems[i], elems[i].parentNode.firstChild);
         }
         
        //We have to move the economic price
        var elems = document.querySelectorAll('.new-form-option .economic-wb');
        for (var i = 0; i < elems.length; i++) {
            if (!elems[i].closest(".value-right")) continue;

            elems[i].closest('.new-form-option').appendChild(elems[i]);
        }
        addStyleToPage(style, attribute);

        //We have to add a padding at end of offer depends on economic text height
        /*var elems = document.querySelectorAll('.new-form-option .economic-wb');
        for (var i = 0; i < elems.length; i++) {
            if(elems[i].clientHeight !== 0){
                elems[i].parentNode.setAttribute('style', "padding-bottom:" + elems[i].clientHeight + "px !important");
            }
            if(elems[i].clientWidth !== 0){
                elems[i].setAttribute('style', "margin-left: -" + elems[i].offsetWidth /2 + "px !important");
                elems[i].style.left =  "50%";
            }

        }*/
    }
}

//Declare some variables  needed
wideBundle.declareVariables = function(){
    wideBundle.locationWebsite = encodeURI(decodeURI(window.location.href));
    wideBundle.settings.currency = wideBundle.settings.currency.replace(/<\/?span.*?>/gm, '');
    wideBundle.widgetContainers = [];
    wideBundle.currencyCodes = {
        USD: 'US$',
        EUR: '€',
        GBP: '£',
        AUD: 'AU$',
        NZD: 'NZ$',
        CAD: 'CA$',
        JPY: '¥',
        DKK: 'DKK',
        NOK: 'NOK',
        SEK: 'SEK',
        BAM: 'KM',
        BGN: 'лв.',
        CHF: 'CHF',
        DKK: 'kr.',
        ILS: '₪',
        ISK: 'ISK',
        LBP: 'ل.ل',
        LRD: 'LRD $',
        PLN: 'zł',
        RON: 'Lei',
        TRY: '₺',
        MXN: '$',
        HKD: '$',
        KRW: '₩',
        MYR: 'RM',
        SGD: '$',
        TWD: '$',
        TND: 'د.ت',
        EGP: 'ج.م',
        DZD: 'دج',
        MAD: 'dh',
        BRL: 'R$',
        CLP: 'CLP',
        INR: '₹',
        UAE: 'د.إ',
        AED: 'د.إ',
        ARS: 'ARS',
        PEN: 'S/',
        SAR: 'SAR',
        CNY: '¥',
        RUB: '₽',
        ZAR: 'R',
        IDR: 'Rp',
        PHP: '₱',
        THB: '฿',
        VND: '₫',
        KES: 'KSh',
        PKR: 'Rs',
        EGP: 'EGP',
        IQD: 'IQD',
        KWD: 'KWD',
        OMR: 'OMR',
        QAR: 'QAR',
        JOD: 'JOD',
        LYD: 'LYD',
        SYP: 'SYP',
        BHD: 'BHD',
        JMD: 'JMD',
        BDT: 'BDT',
        NPR: 'NPR',
        LKR: 'LKR',
        KHR: 'KHR',
        MMK: 'MMK',
        LAK: 'LAK',
        VEF: 'VEF',
        COP: 'COP',
        UYU: 'UYU',
        PYG: 'PYG',
        BOB: 'BOB',
        TZS: 'TZS',
        GTQ: 'GTQ',
        NGN: 'NGN',
        MUR: 'MUR',
        MGA: 'MGA',
        XOF: 'XOF',
        RWF: 'RWF',
        HUF: 'HUF',
        UGX: 'UGX',
        TND: 'TND',
        SDG: 'SDG',
        SLL: 'SLL',
        SCR: 'SCR',
        PGK: "PGK",
        CZK: 'CZK',
        UAH: 'UAH'
    };

    wideBundle.currencySymbols = {
        USD: '$',
        EUR: '€',
        GBP: '£',
        AUD: '$',
        NZD: '$',
        CAD: '$',
        JPY: '¥',
        DKK: 'kr.',
        NOK: 'kr.',
        SEK: 'kr.',
        BAM: 'KM',
        BGN: 'лв.',
        CHF: '₣',
        ILS: '₪',
        ISK: 'kr',
        LBP: 'ل.ل',
        LRD: '$',
        PLN: 'zł',
        RON: 'lei',
        TRY: '₺',
        MXN: '$',
        HKD: '$',
        KRW: '₩',
        MYR: 'RM',
        SGD: '$',
        TWD: '$',
        TND: 'د.ت',
        EGP: '£',
        DZD: 'د.ج',
        MAD: 'د.م.',
        BRL: '$',
        CLP: '$',
        INR: '₹',
        UAE: 'د.إ',
        AED: 'د.إ',
        ARS: '$',
        PEN: 'S/.',
        SAR: 'ر.س',
        CNY: '¥',
        RUB: '₽',
        ZAR: 'R',
        IDR: 'Rp',
        PHP: '₱',
        THB: '฿',
        VND: '₫',
        KES: 'KSh',
        PKR: '₨',
        IQD: 'ع.د',
        KWD: 'د.ك',
        OMR: 'ر.ع.',
        QAR: 'ر.ق',
        JOD: 'د.ا',
        LYD: 'ل.د',
        SYP: 'ل.س',
        BHD: 'د.ب',
        JMD: '$',
        BDT: '৳',
        NPR: '₨',
        LKR: '₨',
        KHR: '៛',
        MMK: 'K',
        LAK: '₭',
        VEF: 'Bs',
        COP: '$',
        UYU: '$',
        PYG: '₲',
        BOB: 'Bs',
        TZS: 'TSh',
        GTQ: 'Q',
        NGN: '₦',
        MUR: '₨',
        MGA: 'Ar',
        XOF: 'CFA',
        RWF: 'RF',
        HUF: 'Ft',
        UGX: 'USh',
        SDG: '£',
        SLL: 'Le',
        SCR: '₨',
        PGK: 'K',
        CZK: 'Kč',
        UAH: '₴',
        AFN : "؋",
        ALL : "Lek",
        XCD : "$",
        AMD : "AMD",
        AWG : "Afl",
        SHP : "£",
        AZN : "m.",
        BSD : "BS$",
        BBD : "$",
        BZD : "BZ$",
        BWP : "P",
        BND : "$",
        BIF : "FBu.",
        XAF : "FCFA",
        CVE : "$",
        KYD : "$",
        KMF : "CF",
        CDF : "FC",
        CRC : "₡",
        ANG : "ƒ;",
        DJF : "Fdj",
        DOP : "RD$",
        ETB : "Br",
        FKP : "£",
        FJD : "$",
        XPF : "XPF",
        GMD : "D",
        GNF : "FG",
        GYD : "G$",
        HNL : "L",
        KZT : "₸",
        KGS : "лв",
        MOP : "MOP$",
        MWK : "Mk",
        MVR : "Rf",
        MDL : "MDL",
        MNT : "₮",
        NIO : "C$",
        MKD : "ден",
        WST : "WS$",
        STD : "Db",
        RSD : "RSD",
        SBD : "$",
        TJS : "TJS",
        TOP : "$",
        TTD : "$",
        UZS : "som",
        VUV : "$",
        YER : "YER"
      };
}

//Function to detect and get the product form node in the page
wideBundle.getFormNode = function(){

    //Don't select the form if the element is the same as one element below
    formsSameElementException = [
        '.checkout-x-buy-now-btn', '.price-descriptors .shopify-product-form'
    ];

    //Unwanted forms as child/parent/form
    wideBundle.formsException = [
        ".sticky-cart-form", "#form-sticky", ".container-sticky_addtocart", ".sticky-barre-content", "#shopify-section-header",
        ".product-recommendations-placeholder", ".sticky-atc-title:not(.wb-false-positive-exception)", ".search-form", ".sticky-dropdownvar", "header.site-header", "#popUps .cart_upsell_popup",
        "#popUps .cart_downsell_popup", '.product-upsell-holder', '#product-form-installment', '.sticky_addcart', '.product-upsell__holder', '#ShippingModal',
        ".collection .card-wrapper .card__content", '#featured-product-scroll .product--variant', 'product-sticky-form', '#rio-upsell', '.t4s-product-tabs-wrapper',
        'div[data-extraclass="sticky-atc"]', '#shopify-section-pr_description', '.cu-upsell', '#CartDrawer', 'cart-drawer.cart-drawer','#product-form-main-sticky-atc',
        'gp-sticky','.pupsdreams_popup_sticky-product-details-container','.product-item--has-quick-add','.related_products', 'mini-cart .minicart-content',
        '.dbtfy-sticky-addtocart__bar .dbtfy-sticky-addtocart__container', '.card .dbtfy-collection-addtocart',  '.tabs__recommendation quick-add-product .quick-add__holder',
        "main .shopify-section > #sticky-add-to-cart", "product-recommendations motion-list .quick-add", ".swiper-wrapper div[class*='ss_shoppable_video']",
        ".product-recommendations .product-loop .js-product-listing", ".cart-upsell-wrapper #cart-upsell", "section#sticky-atc.fixed-bottom .container",
        ".product--addtocart--sticky .right-side",  "div[id$='__cart-upsell'] .dbtfy-cart-upsell .dbtfy-cart-upsell-item", ".cart-flyout .cart-drawer-products", "#cart-drawer .cart-upselling",
        "div[hidden] .dbtfy-upsell-bundles__form-wrapper", ".product-grid-item.carousel__item .product__media__container .product-grid-item__quick-buy",
        ".product-section + .product-sticky-add-cart-new.custom-sticky-form", "#shopify-section-minicart .cart .minicart-footer", "cart-recommendation recommendation-carousel",
        ".product__block .carousel.swiper .carousel__slide.swiper-slide", ".container .splide .splide__track .splide__list .splide__slide", "tabs-component .tabs__panel .tabs__content grid-list .product-card__image-wrapper",
        "#cart-drawer-upsell-wrapper #cart-drawer-upsell .cart-drawer-upsell-list", "dbtfy-addtocart-sticky.dbtfy-addtocart-sticky", "deployer-cart-drawer#DeployerCartDrawer",
        ".header__navigation nav.header__menu .mega-menu__container", ".sticky-btn__container.sticky-atc-btn__active .sticky-atc__inner-wrapper", ".sticky-btn__container .sticky-atc__inner-wrapper",
        "product-info-upsell.upsell .upsell__container", "body[id*=skincare-for-breakouts-expert-] .smi-buy-btn.cursor-none-buy-gr", 'product-grid-item-variant.product-grid-item__content .product-grid-item__container',
        'product-recommendations product-complementary', "slider-element motion-list.card-grid", "recently-viewed quick-add-product", "external-searchcontent", ".gbgbgb", ".resource-list .resource-list__item product-card quick-add-component", "results-list product-card quick-add-component"
    ];

    //Elements we want to hide
    hidingElements = [
        ".shg-product-selector-wrapper", ".tt-swatches-container", ".tt-option-block", ".dbtfy-color_swatches", ".pt-swatches-container",
        ".product-form__item--submit", ".pg__option--single", ".gt_product-swatches.gt_flex.gt_variant_product", ".button_add_to_cart.gt_product-addtocart",
        ".gt_flex.gt_variant_product"
    ];

    //Forms we want to check
    forms = [
        ".w-commerce-commerceaddtocartform.default-state-2", ".product-form", ".productForm", 'product-form form[data-type="add-to-cart-form"]', ".product-form__buy-buttons .shopify-product-form", ".shopify-product-form:not(.wb--not-psuedo)", "#addToCartFormId1",
        ".t4s-product__info-wrapper form.t4s-form__product", "#AddToCartForm--product-template", ".product-form-product-template", ".product-form.hidedropdown", ".addToCartForm", ".product-single__meta .product-single__meta-info .product-single__form", ".ProductForm",
        ".product-single__form", ".prod_form", "#addToCartForm-product-template-optimised", ".shg-product-atc-btn-wrapper", 'form[data-type="add-to-cart-form"].form', "form[action=\'/cart/add\']",
        "#addToCartForm", ".form-vertical", "#prodForm", "form[data-product-form]", "#add-to-cart-form", "form[action$='/cart/add']", ".product-single__form:nth-child(2)", "form[action^='/cart/add']"
    ];

    allForms = 0

    forms.forEach(form => {
        allForms +=  document.querySelectorAll(form).length;
    })

    //To detect and get the product form node in the page
    form:
    for(var i=0; i < forms.length; i++){
        formLength = document.querySelectorAll(forms[i]).length;
        // console.log("form length: " + formLength + " for: " + forms[i]);
        //For all the forms found in the page
        formNumber:
        for(let j=0; j<formLength; j++){
            form = document.querySelectorAll(forms[i])[j];
            formID = forms[i];
            //If the form is found and is not .product-form (because we can't use it)
            if(typeof form !== 'undefined' && form != null && formID != ".product-form") {
                console.log('form found:');
                console.log(form);
                //For all the exceptions classes
                for(var x=0; x < wideBundle.formsException.length; x++){
                    exceptionAll = document.querySelectorAll(wideBundle.formsException[x]);
                    for(var z=0; z < exceptionAll.length; z++){
                        exception = exceptionAll[z];
                        //If the form is an exception then check next form found in the page
                        if(exception == form || isDescendant(exception, form) || isDescendant(form, exception)){
                            console.log('form is an exception...');
                            continue formNumber;
                        }
                    }
                }
                //For all exceptions that are the same element
                for(var x=0; x < formsSameElementException.length; x++){
                    exceptionAll = document.querySelectorAll(formsSameElementException[x]);
                    for(var z=0; z < exceptionAll.length; z++){
                        exception = exceptionAll[z];
                        //If the form is an exception then check next form found in the page
                        if(exception != undefined && exception == form){
                            console.log('form is an exception...');
                            continue formNumber;
                        }
                    }
                }
                //Check forms we don't wants (those with only hidden elements)
                childElementsWB = form.querySelectorAll('*');
                good = 0;
                for(var x=0; x<childElementsWB.length; x++){
                    if(typeof childElementsWB[x] == "object" && typeof childElementsWB[x].type != "undefined" && childElementsWB[x].type != "hidden"){
                        good = 1;
                    }
                }
                if(good == 0 && (allForms >= 2 || childElementsWB.length == 0 || form.tagName == "BUTTON") ){
                    console.log('form is another exception');
                    continue formNumber;
                }
                //If form exists and has passed the exceptions then we can choose it to display the Widget
                if(form !== 'undefined' && form != null){
                    console.log("chosen form:" + formID);
                    return {
                        element: form,
                        id: formID
                    }
                }
            }
        }
    };
    console.log('form not found');
    return {
        element: null,
        id: null
    };
}

//Function to detect and get the price node below the title in the page
wideBundle.getPriceNode = function(){
    updatePrice = wideBundle.settings.update_price;
    //Don't do anything if the user doesn't want to update price design
    if(updatePrice == 0){
        var priceID = 'not checked';
        var http = new XMLHttpRequest();
        var url = wideBundle.domain+'AJAX/GetPrice.php';
        var params = 'price='+priceID+'&shop='+wideBundle.shop;
        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        http.send(params);
        return {
            element: [],
            id: null
        };
    }

    //Selectors for price nodes
    pricesWB = [
        ".product-item-caption-price", ".ProductMeta__PriceList", "#price_ppr", ".product-single__prices", ".product-featured__price-text", ".product__price",
        ".gf_product-prices", "#productPrice-product-template", ".productTemplatePrice", ".product-price", "div[data-product-type=price]", ".modal_price",
        ".featured-product-section .product-single .box .product-wrapper .product-details .product-single__meta .price-wrapper", ":not(.wb_hidden_prices_element) .price", ".product-meta h1",
        ".price-wrapper", ".product-single__meta .product-single__meta-list", ".product-single__price", ".tt-price", ".gt_flex.price_product", ".pt-price", ".gt-product-price", 'span[data-zp-product-discount-price]',
        '.t4s-product-price', '.z-main-product__price', '.product-single__price--on-sale', '.product-info .product-info__price', ".main-product__block-price .product-block-group--price .m-price",
        ".product-cont-header2 [id*='productPrice-template--'].h1", "[id*='ProductInfo-template--'] .product__price .price .price__container", "product-form gp-product-price", ".product-info__block-list price-list.price-list"
    ];
    //We don't want the price to be updated in these selectors
    pricesExceptionWB = [
        ".upsells .upsell-info", "#new-form", ".new-wb-form", "#mini-cart", '[id^="cross-sell-"]', "#CollectionSection", "#CartDrawer-CartItems",
        ".section--products-recommendations", '.featured-collections', ".header-drawer .menu-drawer"
    ];
    //Specific blocs to get prices
    blocsToGetPricesWB = [
        ".featured_product_se"
    ];

    //Get the price node from selectors list
    priceWB:
    for(var i=0; i < pricesWB.length; i++){
        //Find the price node in specific blocs
        for(var x=0; x <blocsToGetPricesWB.length; x++){
            var blocToGetPrice = document.querySelector(blocsToGetPricesWB[x]);
            if(blocToGetPrice){
                price = blocToGetPrice.querySelectorAll(pricesWB[i]);
                if(price.length){
                    return {
                        element: blocToGetPrice.querySelectorAll(pricesWB[i]),
                        id: pricesWB[i]
                    }
                }
            }
        }
        var price = Array.from(document.querySelectorAll(pricesWB[i]));
        // console.log("price length: " + price.length + " for: " + pricesWB[i]);
        if(price.length){
            for(var y=0; y<pricesExceptionWB.length; y++){
                allExcepClassPrices = document.querySelectorAll(`${pricesExceptionWB[y]}`)
                for(var z=0; z<allExcepClassPrices.length; z++){
                    price = price.filter(element => !isDescendant(allExcepClassPrices[z], element));
                }
            }
            if(!price.length){
              continue priceWB;
            }
            console.log("price " + pricesWB[i] + " found:");
            console.log(price);
            return {
                element: price,
                id: pricesWB[i]
            }
        }
    }
    console.log("No price found");
    return {
        element: [],
        id: null
    };
}

//Function to hide prices that are duplicated or unwanted when we update the price design under the title
wideBundle.hideUnwantedPrices = function(){

    var productSinglePriceWrapper = document.querySelector('.product-single__price--wrapper');
    if (productSinglePriceWrapper) {
        productSinglePriceWrapper.style.display = 'none';
    }

    var productPrice = document.getElementById('ProductPrice');
    var comparePrice = document.getElementById('ComparePrice');
    var priceNode = document.querySelector('.price');
    if (productPrice && comparePrice && !priceNode) {
        //wideBundle.priceInfo.element[0].style.display = "none";
        var salePrice = document.querySelector('.sale_price');
        var price = document.querySelector('.price');
        if (price && price.innerHTML.trim() == '' && salePrice) {
            productPrice.style.display = 'none';
            comparePrice.style.display = 'none';
            comparePrice.style.fontSize = '0px';
            productPrice.style.Size = '0px';
            salePrice.style.display = 'none';
        }
    }

    if(wideBundle.priceInfo.element.length > 0){
      if(wideBundle.priceInfo.id == ".product-single__price--on-sale"){
        let compareAtPriceToHide = document.querySelector('.product-single__price--compare-at');
        if(compareAtPriceToHide){
          compareAtPriceToHide.style.display = "none";
        }
      }
    }

    var productPriceCompare = document.querySelectorAll('.product__price--compare');
    for (var i = 0; i < productPriceCompare.length; i++) {
        productPriceCompare[i].style.display = 'none';
    }

    if(wideBundle.priceInfo.id == ".gt-product-price"){
        var gtProductComparePrice = document.querySelectorAll(".gt-product-compare-price");
        if (gtProductComparePrice[0]) {
            gtProductComparePrice[0].style.display = "none";
        }
    }

    var productAction = document.querySelector('.product-action');
    if (productAction) {
        productAction.style.display = 'none';
    }

    var compareAtPrice = document.querySelector('div[data-product-type="compare_at_price"][data-pf-type="ProductPrice"]');
    if (compareAtPrice) {
        compareAtPrice.style.display = "none";
    }

    if(wideBundle.priceInfo.id == ".product-single__price"){
        priceContainer = wideBundle.priceInfo.element[0].closest('.price-container');
        if(priceContainer){
            comparePrice = priceContainer.querySelector('#ComparePrice.product-single__price--compare-at');
            if(comparePrice !== null && comparePrice != wideBundle.priceInfo.element[0]){
                comparePrice.style.display = "none";
            }
        }
    }
}

//For some exceptions we replace the price detected by WideBundle
wideBundle.replaceSelectedPrice = function(){
    if(wideBundle.priceInfo.element[0]){
        comparePrice = document.querySelector('#ComparePrice-product-template');
        if(comparePrice){
            priceSinglePrice = document.querySelector('.product-single__price product-single__price-product-template');
            if(priceSinglePrice){
                wideBundle.priceInfo = {
                    element: document.querySelectorAll('.product-single__price'),
                    id: '.product-single__price'
                };
            }
        }

        if(wideBundle.priceInfo.element[0].offsetParent === null && wideBundle.priceInfo.id == ".product__price"){
            productPriceCompare = document.querySelector('.product__price--compare');
            if(productPriceCompare && productPriceCompare.offsetParent === null){
                productPriceSale = document.querySelector('.product__price.on-sale');
                if(productPriceSale){
                    wideBundle.priceInfo = {
                        element: document.querySelectorAll('.product__price.on-sale'),
                        id: '.product__price on-sale'
                    };
                }
            }
        }

        if(wideBundle.priceInfo.id == ".product__price"){
            productPriceSalePrice = document.querySelector('.product__price.sale-price');
            if(wideBundle.priceInfo.element[0].classList.contains("product__price--compare") && productPriceSale){
                wideBundle.priceInfo = {
                    element: document.querySelectorAll('.product__price.sale-price'),
                    id: '.product__price sale-price'
                };
            }
        }

        if(wideBundle.priceInfo.id == ".product-single__price"){
            productSinglePrice = document.querySelector('.product-single__price.product-single__price--compare');
            if(productSinglePrice && wideBundle.priceInfo.element[0].classList.contains('product__price--compare') == false){
                productSingleMeta = document.querySelector('.product-single__meta-list');
                if(productSingleMeta){
                    wideBundle.priceInfo.element[0].style.fontSize = '1.2em';
                    wideBundle.priceInfo = {
                        element: document.querySelectorAll('.product-single__meta-list'),
                        id: '.product-single__meta-list'
                    };
                }
            }
        }
    }
}

//Replace the price id value in the Database
wideBundle.replacePriceIdInDB = function(){
    if(wideBundle.settings.price_id != wideBundle.priceInfo.id){
        var http = new XMLHttpRequest();
        var url = wideBundle.domain+'AJAX/GetPrice.php';
        var params = 'price='+wideBundle.priceInfo.id+'&shop='+wideBundle.shop;
        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        http.send(params);
        wideBundle.settings.price_id = wideBundle.priceInfo.id;
    }
}

//Replace the form id value in the Database
wideBundle.replaceFormIdInDB = function(){
    if(wideBundle.settings.form_id != wideBundle.formInfo.id){
        var http = new XMLHttpRequest();
        var url = wideBundle.domain+'AJAX/GetForm.php';
        var params = 'form='+wideBundle.formInfo.id+'&shop='+wideBundle.shop;
        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        http.send(params);
        wideBundle.settings.form_id = wideBundle.formInfo.id;
    }
}

//Find WideBundle widget added manually (usually for page builders)
wideBundle.getManualWidget = function(){
    var formWidebundle = document.querySelector("#new-form");
    if(formWidebundle){
        wideBundle.formInfo.id = 'page builder';
        console.log("we found form for page builder");
        //Hide variants from Gempages
        if(formWidebundle.closest(".AddToCartForm")){
            gfVariantsWrapper = formWidebundle.closest(".AddToCartForm").querySelector('gf_variants-wrapper');
            if(gfVariantsWrapper){
                gfVariantsWrapper.style.display = "none";
            }
        }
        return formWidebundle;
    }
    else{
        return null;
    }
}

//Get the secondary widgets that were placed manually using .new-wb-form
wideBundle.getSecondaryWidgets = function(){
    var multipleFormsWB = document.querySelectorAll('.new-wb-form');
    if(multipleFormsWB.length){
      console.log("using form class");
      return multipleFormsWB;
    }
    else{
      return null;
    }
}

//For some exceptions we replace the form detected by WideBundle
wideBundle.replaceSelectedForm = function(){
    var formWB = wideBundle.formInfo;
    if(formWB.id == "form[action='/cart/add']"){
        if(formWB.element.querySelector('h2[itemprop="name"]') != null &&
        formWB.element.querySelector('.product__price-container') != null){
            if(formWB.element.querySelector('.product-details .add-to-cart-btn') != null){
                wideBundle.formInfo.element = formWB.element.querySelector('.product-details');
            }
        }
    }
}

//Replo Page builder need special treatment
wideBundle.hideReplo = function(){
    if(wideBundle.manualWidget){
        if(document.querySelector('div[data-replo-variant-select]')){
            document.querySelector('div[data-replo-variant-select]').style.display = "none";
            document.querySelector('div[data-replo-variant-select]').classList.add('hide-unwanted-widebundle');
        }
        if(document.querySelector("select[data-replo-variant-select-dropdown]")){
            if(wideBundle.manualWidget){
                if(document.querySelector("select[data-replo-variant-select-dropdown]").parentElement.tagName == "DIV"){
                    document.querySelector("select[data-replo-variant-select-dropdown]").parentElement.style.display = "none";
                    document.querySelector("select[data-replo-variant-select-dropdown]").parentElement.classList.add('hide-unwanted-widebundle');
                }
            }
        }
        var increaseButton = document.querySelector('div[data-replo-increase-product-quantity]');
        var decreaseButton = document.querySelector('div[data-replo-decrease-product-quantity]');
        if(increaseButton && decreaseButton){
            if(increaseButton.parentNode){
                increaseButton.parentNode.style.display = "none";
                increaseButton.parentNode.classList.add('hide-unwanted-widebundle');
            }
        }
        var atcReplo = document.querySelector('button[data-replo-add-product-variant-to-cart]');
        if(atcReplo){
            atcReplo.style.display = "none";
            atcReplo.classList.add('hide-unwanted-widebundle');
        }
    }
}

//Hide elements we don't want from the product form found by WideBundle
wideBundle.hideElementsOutsideProductForm = function(){

    if(wideBundle.manualWidget){
        getProductSwatches = document.querySelector('.gt_product-swatches.gt_flex.gt_variant_product');
        if(getProductSwatches){
            getProductSwatches.style.display = 'none';
            getProductSwatches.classList.add('hide-unwanted-widebundle');
            buttonGtProduct = document.querySelector('.button_add_to_cart.gt_product-addtocart');
            if(buttonGtProduct){
                buttonGtProduct.style.display = 'none';
                buttonGtProduct.classList.add('hide-unwanted-widebundle');
            }
            gtFlexVariant = document.querySelector('.gt_flex.gt_variant_product');
            if(gtFlexVariant){
                gtFlexVariant.style.display = 'none';
                gtFlexVariant.classList.add('hide-unwanted-widebundle');
            }
        }
        gtProductContent = document.querySelector('.gt_product-content button[data-name="Product Button"]');
        if(gtProductContent){
            gtProductContent.style.display = "none";
            gtProductContent.classList.add('hide-unwanted-widebundle');
            style = '.gt_product-content button[data-name="Product Button"]{display:none !important;}';
            addStyleToPage(style, 'hide-elements-1');
        }
    }

    const firstArrayOfSelectors = [
        'div[data-pf-type="ProductVariant"]',
        'div[data-pf-type="ProductVariantSwatches"]',
        'div[data-label="(P) Quantity"]',
        'button.gt_button--product',
        '.gt_product-variant.gt_product-swatches',
        'div[data-pf-type="ProductQuantity"]',
        '.qty_near_atc_wrapper',
        'button[data-pf-type="ProductATC"]',
        'button[data-pf-type="ProductATC2"]',
        'div[data-label="(P) Variants"]',
        'div[data-label="(P) Cart Button"]',
        'div[data-label="(P) Swatches"]',
        "gp-product-button button",
        'gp-product-quantity',
        "gp-product-variants",
        "x-buy-button.x-product-buy-button[type='submit']",
        "x-variant-picker.x-variant-picker .x-variant-picker__field-wrapper",
        "x-variant-picker.x-variant-picker",
        ".x-quantity-input",
        ".f\\:product-single__block-quantity-selector",
        ".f\\:product-single__block-buy-buttons"
    ];
    const hideElementWithSelectorFromFirstArray = function(array) {
        array.forEach(el => {
            if(wideBundle.manualWidget){
                if(document.querySelector(el) != null){
                    forms = document.querySelectorAll('form');
                    for(i = 0; i < forms.length; i++){
                        if(isDescendant(forms[i], wideBundle.manualWidget)){
                            variants = forms[i].querySelector(el);
                            if(variants != null){
                                variants.style.display = "none";
                                variants.classList.add('hide-unwanted-widebundle');
                            }
                        }
                        if(wideBundle.secondaryWidgets){
                          for(var y = 0; y<wideBundle.secondaryWidgets.length; y++){
                            if(isDescendant(forms[i], wideBundle.secondaryWidgets[y])){
                                variants = forms[i].querySelector(el);
                                if(variants != null){
                                    variants.style.display = "none";
                                    variants.classList.add('hide-unwanted-widebundle');
                                }
                            }
                          }
                        }
                    }
                }
            }
        })
    };
    hideElementWithSelectorFromFirstArray(firstArrayOfSelectors);

    const arrayForHideElementWithParentNodeOneLevel = [
        'div[data-pf-type="ProductVariantSwatches"]',
        'button[data-pf-type="ProductATC"]',
        'div[data-label="(P) Variants"]',
        'div[data-label="(P) Cart Button"]',
        'div[data-label="(P) Swatches"]'
    ];
    const hideElementWithParentNodeOneLevel= function (array) {
        array.forEach(el => {
            if(wideBundle.manualWidget){
                if(document.querySelector(el) != null){
                    if(document.querySelector(el).parentNode != null){
                        if(isDescendant(document.querySelector(el).parentNode, wideBundle.manualWidget)){
                            document.querySelector(el).style.display = "none";
                            document.querySelector(el).classList.add('hide-unwanted-widebundle');
                        }
                        if(wideBundle.secondaryWidgets){
                          for(var y = 0; y<wideBundle.secondaryWidgets.length; y++){
                            if(isDescendant(document.querySelector(el).parentNode, wideBundle.secondaryWidgets[y])){
                                document.querySelector(el).style.display = "none";
                                document.querySelector(el).classList.add('hide-unwanted-widebundle');
                            }
                          }
                        }
                    }
                }
            }
        })
    };
    hideElementWithParentNodeOneLevel(arrayForHideElementWithParentNodeOneLevel);

    const arrayForHideElementWithParentNodeTwoLevel = [
        '.zpa-add-to-cart-btn',
        '.zpa-selector-wrapper',
        '.ecom-product-single__quantity[deep="2"]',
        '.ecom-product-single__variant-picker[deep="2"]'
    ];
    const hideElementWithParentNodeTwoLevel= function (array) {
        array.forEach(el => {
            if(wideBundle.manualWidget){
                if(document.querySelector(el) != null){
                    if(document.querySelector(el).parentNode != null){
                        if(isDescendant(document.querySelector(el).parentNode.parentNode, wideBundle.manualWidget)){
                            document.querySelector(el).style.display = "none";
                            document.querySelector(el).classList.add('hide-unwanted-widebundle');
                        }
                    }
                }
            }
        })
    };
    hideElementWithParentNodeTwoLevel(arrayForHideElementWithParentNodeTwoLevel);

    const thirdArrayOfSelectors = [
        '.gt_product-swatches',
        '.gt_product-variant',
        '.gt_product-quantity',
        '.gt_product-addtocart',
        '.gt_button-atc',
        ".shg-product-selector-wrapper", //shogun variant selector to hide
        ".shg-product-atc-btn-wrapper", //shogun add to cart button to hide
    ];
    const hideElementWithSelectorFromThirdArray = function (array) {
        array.forEach(el => {
            if(wideBundle.manualWidget){
                if(document.querySelector(el) != null){
                    document.querySelector(el).style.display = "none";
                    document.querySelector(el).classList.add('hide-unwanted-widebundle');
                }
            }
        })
    };
    hideElementWithSelectorFromThirdArray(thirdArrayOfSelectors);

    const fourthArrayOfSelectors = [
        '.dbtfy-color_swatches',
        '.product-layout-grid__detail .product-detail__options',
        '.product__info-wrapper variant-radios',
        'div[data-variant-picker]',
        '.product-detail__form__options.product-detail__gap-lg.product-detail__form__options--underlined',
        '.product-block-container .product-block.product-block-variant-picker:not(.pb-card-shadow)',
        '.product-block-container .product-block.product-block-quantity-selector:not(.pb-card-shadow)',
        '.product-form__quantity',
        '.product-block-item.atc-wrapper',
        '.product__quantity',
        '.product-form product-variants',
        '.tt-swatches-container',
        '.product__quantity',
        '.product-info__quantity-selector',
        'variant-picker',
        'product-page product-variants',
        '.product__variants-wrapper.product__block',
        '.product__controls-group-quantity.product__block',
        '.product-options--root',
        'variant-radios',
        '.quantity_selector',
        '.productView-subtotal',
        '.productView-options',
        'f-variant-picker',
        '[data-product-variants]',
        '.product__controls-group-quanity',
        '.yv-product-quantity',
        '.product-block--buy-button .button--sold-out',
        '.container .product__meta[itemscope] div div.row.gy-3',
        ".product__grid__item .product__content .product__selector[id^='ProductSelector-template--']",
        "variant-dropdown .product-variant__option__item",
         ".shopify-section.featured-product .container-fluid .product__meta[itemscope].sticky div div.row.gy-3",
         '.pagepilot-wrapper [id*="pp-quantity-form-template--"]',
         '.pagepilot-wrapper [id*="variant-selects-template--"]',
         'hybrid-variant-picker[id*="variant-picker-template--"]',
         'loess-variant-picker loess-variant-selects.input-group',
         '.wt-product__options variant-options .wt-product__option',
         'variant-selects .product-form-input',
        ".shopify-product-form .product-variants.product-variants--only",
        ".simple-variant-picker .simple-variant-picker__container",
        "variant-selects[id*='variant-selects-template-']",
        "dm-variant-selects fieldset",
        "[data-product-options] product-swatch"

    ];
    const addCssInHeaderToHideElements = (array) => {
        let style = document.createElement('style');
        style.type = 'text/css';
        
        let css = ':root { --widebundle-element-visibility: none; }';
        
        array.forEach((el, index) => {
                css += `${el} { display: var(--widebundle-element-visibility) !important; } `;
        });
        
        style.appendChild(document.createTextNode(css));
        document.head.appendChild(style);

        document.documentElement.style.setProperty('--widebundle-element-visibility', 'none');
    }
    const hideElementWithSelectorFromFourthArray = function (array) {
        let elementsToHideWithCssInHead = []
        array.forEach(el => {
            let element = document.querySelector(el);
            if(element != null && !element.classList.contains("do-not-hide-wb")){
                elementsToHideWithCssInHead.push(el);
                element.style.display = "none";
                element.classList.add('hide-unwanted-widebundle');
            }
        });
        addCssInHeaderToHideElements(elementsToHideWithCssInHead)
        
    };
    hideElementWithSelectorFromFourthArray(fourthArrayOfSelectors);

    const fifthArrayOfSelectors = [
        '.product-block .variant-wrapper',
        '.product__info-container variant-radios',
        '.pt-swatches-container.pt-swatches-container-js',
        '.product__info-container variant-selects',
        '.product__info-wrapper variant-selects',
        '.product-page-section variant-selects',
        '.pg__option--single',
        '.product-option-selector'
    ];
    const hideElementWithSelectorFromFifthArray = function (array) {
        let style = document.createElement('style');
        style.type = 'text/css';
        
        let css = ':root { --widebundle-element-visibility: none; }';
        
        array.forEach((el, index) => {
            if (index >= 3 && index <= 5) {
                // Use CSS custom property for 4th, 5th, and 6th elements
                css += `${el} { display: var(--widebundle-element-visibility) !important; } `;
            }
        });
        
        style.appendChild(document.createTextNode(css));
        document.head.appendChild(style);

        document.documentElement.style.setProperty('--widebundle-element-visibility', 'none');

        array.forEach(el => {
            if(document.querySelector(el) != null){
                for(var i = 0; i<document.querySelectorAll(el).length; i++){
                    document.querySelectorAll(el)[i].style.display = "none";
                    document.querySelectorAll(el)[i].classList.add('hide-unwanted-widebundle');
                }
            }
        })
    }
    hideElementWithSelectorFromFifthArray(fifthArrayOfSelectors);

    const sixthArrayOfSelectors = [
        'fieldset.product-form__input:not(.product-form__input--siblings)'
    ];
    const hideElementWithSelectorFromSixthArray = function (array) {
        array.forEach(el => {
            if(document.querySelector(el) != null){
                if(!isDescendant(wideBundle.formInfo.element, document.querySelector(el))){
                    document.querySelector(el).style.display = "none";
                    document.querySelector(el).classList.add('hide-unwanted-widebundle');
                }
            }
        })
    }
    hideElementWithSelectorFromSixthArray(sixthArrayOfSelectors);

    const seventhArrayOfSelectors = [
        'button[data-replo-repeated-index][role="button"]',
        'select[data-replo-repeated-index][role="listbox"]'
    ];
    const hideElementWithSelectorFromSeventhArray = function (array) {
        array.forEach(el => {
            elements = document.querySelectorAll(el);
            if(document.querySelector(el) != null){
                if(wideBundle.manualWidget){
                    for(var y = 0 ; y < elements.length; y++){
                        elements[y].style.display = "none";
                        elements[y].classList.add('hide-unwanted-widebundle');
                    }
                }
            }
        })
    }
    hideElementWithSelectorFromSeventhArray(seventhArrayOfSelectors);

    if(wideBundle.manualWidget){
        if(document.querySelector('div[data-pf-type="ProductQuantity"]') != null){
            layouts = document.querySelectorAll('div[data-pf-type="Layout"]');
            for(i=0; i<layouts.length; i++){
                if(isDescendant(layouts[i], wideBundle.manualWidget)){
                    variants = layouts[i].querySelector('div[data-pf-type="ProductQuantity"]');
                    if(variants != null){
                        variants.style.display = "none";
                        variants.classList.add('hide-unwanted-widebundle');
                        break;
                    }
                }
            }
        }
    }
      if(document.querySelector('.product-form__buy-buttons product-payment-container .product-form__add-button') != null){
        document.querySelector('.product-form__buy-buttons product-payment-container').style.visibility = "hidden";
        document.querySelector('.product-form__buy-buttons product-payment-container').style.display = "block";
        document.querySelector('.product-form__buy-buttons product-payment-container').classList.add('hide-unwanted-widebundle');
        addStyleToPage('.product-form__buy-buttons product-payment-container{display: block !important;}', 'hide-elements-2');
      }
      if(document.querySelector('.product-single__meta .variant-wrapper--button') != null){
        document.querySelector('.product-single__meta .variant-wrapper--button').style.visibility = "hidden";
        document.querySelector('.product-single__meta .variant-wrapper--button').style.height = "0px";
        document.querySelector('.product-single__meta .variant-wrapper--button').style.width = "0px";
        document.querySelector('.product-single__meta .variant-wrapper--button').classList.add('hide-unwanted-widebundle');
      }

      if(formID == 'form[data-type="add-to-cart-form"].form'){
        style = ".product-form__input{display:none;}"
        addStyleToPage(style, 'hide-elements-3');
      }
      var styles = '#product-sticky__btn-sticky-wrapper, .product-sticky__btn-button-container { display: none !important; }';
      addStyleToPage(styles, 'hide-elements-4');
}

//Show hidden elements by WideBundle that were inside the form (put out elements)
wideBundle.showElementsFromProductForm = function(){
    addToCartButton = wideBundle.getAddToCartButton();
    variantsSelector = wideBundle.getVariantsSelector();
 
    //Element's selectors we want to show outside the product form
    var elementsToShow = [
        '.main-product__block-title', '.main-product__block-price', '.main-product__block-custom_liquid', '.main-product__block-collapsible_tab', '.main-product__block-description',
        '.prod_secure_img', '.editor_line_wrap_s_content_below_atc', '.editor_line_wrap_content_below_atc', '#pretty-product-pages', ".product-description-header",
        ".product-page--pricing", ".product-description-wrapper", "#w3-product-accessories", '.product-single__description_page', '.product-block-item .timer_wrapper',
        '.faq-container', '.webyzeProductColorsLabel', '.webyzeProductColors', '#ZlistWishlist', '.product-block-item .under_cta_atc', '.product-meta__description', '.product-meta__text',
        '.shopify-block.shopify-app-block', '.product-single__description', '.collapsibles-wrapper', '.Footer__PaymentListt', '.additional-checkout-text', '#cubynDeliveryBadge', '.product-meta__title',
        'a[href="#looxReviews"]', '.ProductMeta(.ProductMeta__Title)', '.product-block-item(.tabsWrapper)', '.product-block-item(.product-single__desc)', '.size_guide__link_above',
        '.product-block-item(.product-single__title)', '.product-block-item(.product-single__stars)', '.product-block-item(.price-container)', '.slick-testi-product(.testi-review)',
        '.product-information-social-proof','.product-information-text','.product-information-title','.product-information-price',

        '.icon-benefits(.cv-icon-benefit)', 'product__title', 'product__price--holder', 'product__description', '.product__title', '.product__price--holder', '.product__description', 'h2.product-price',
        '.product-description', '.product-tabs', '.product-block-item .product-single__stars', '.product-block-item .product-single__desc',
        'lh-content-title', 'lh-review', 'lh-price-block', 'lh-product-introduce', '.product__title--ppTitle', '.loox-rating', '.product__price--ppPrice', '.product__urgency',
        '.product__countdown--holder', '.short-info', '.ProductMeta__Rating', '.colors-list-wrap .colors-list', '.storeFeatures', '.nm-easyorder-custom-button', '.review-widget', '.htusb-placeholder-countdown', '#alireview-review-widget-badge',
        'product-single__description', '.ProductMeta .ProductMeta__Title', '.ProductMeta .ProductMeta__PriceList', '.ProductMeta .ProductMeta__UnitPriceMeasurement', '.ProductMeta .ProductMeta__TaxNotice', '.ProductMeta__Description',
        '.ProductMeta_Description', 'product-single__description_page', '.product-meta__label-list',".product-details-product-title", ".widereview-rate","#ProductPrice",'.description','.restock-alerts-branding-text','.restock-alerts-notify-button',

        '.icon-benefits(.cv-icon-benefit)', '.product-short-description', '.product-price-container', '.alr-display-review-badge', '.product_title', '.sale-point', '.visitor-counter-content-box-carecartbysalespop-2020',
        '.Footer__PaymentList', '.Product__Tabs(.Collapsible__Content)', '.product-block-item(.fa-box-check)', '.product-block-item(h3)', '.product-page-info__title', '.product-page-info__price', '.product-page-info__reviews','.best-fit-size-chart',
        '#ImageUploaderContainer', '#paypal-button-container', '.price_container .modal_price', "#product-price", '.html-cart(.fa)',
        '.main-product__block.main-product__block-text', '.main-product__block.main-product__block-custom_text', '.main-product__block.main-product__block-shipping', '.main-product__block.main-product__block-short_description',
        'h1#product-title', '.bundle-aggregated_reviews', '#product-description', '.Vtl-SizeChartButtonWrapper', '.vtl-pl-main-widget','.product-block-accordion',
        '.product-price','.title.text-start','.product-tax','.payment-list','#product-delivery-info','.product-block-trust-badges','.jdgm-widget', 'div[class^="countdown_timer_wrapper_"]', '#delivery_timer_wrapper1', ".tab-menu", '.desc-tab',
        '.product-block-scrolling-text(.title)', '#inventory-bar(.title)', '.btn-wishlist-add-remove', '#product-live-visitors', "[class^='ss-tabs-icon-insert-block-template--']", "div ul.inline-list.payment-icons(svg)", ".collapsible-tab-container(summary)",
        "div.ec_trust-badges(div.ec_badge)", ".product-page__policies.rte(a)", "div.unit-price(span.unit-price__price)", "stock-level-indicator.stock-indicator-animations(span.stock-level-message)", ".image-offer-container(a.image-offer-container--is-link)",
        "form.shopify-product-form h1.title(div.h2_svg)", "form.shopify-product-form .product-block-subtitle(p.subtitle)", ".product__block.product__accordion(div.accordion)",
        ".product-block-item.pbi-2(i.fa-solid)", ".product-block-item.pbi-4 > .point(svg)", ".product-block-item.pbi-7(div.img-w-txt)",
        ".wb-custom-html-2-zameer", ".wb-custom-html-1-zameer", ".wb-product-title-zameer",
        ".product-actions__checkout-image picture img", ".product__main .product-info h1.product-info__title", ".product-delivery-estimate.js-product-delivery-estimate(span.product-delivery-estimate__time)",
        "div.button__extra(div.button__extra--rating p.button__extra--text)", "h1.title", "#product-testimonials(.description)", '.product-details--form-wrapper .marketing-badges-container(.marketing-badge)',
        ".prod_delivery-times(div.content p)", ".prod_shipping-text(div.content p)", "h1.product-name", "shopify-payment-terms", ".star-rating(.shopify-product-reviews-badge)", ".compare-wishlist(a.wishlist-button)",
        "div.product__badges(img.lazyload)", ".accordion.product__accordion(label.accordion__item span.accordion__item--title)",
        ".product-option-wrapper button.btn-primary[data-bs-target='#size-chart-modal']", ".product-block-testimonial(p.product-block-testimonial-author)",
        ".wb-force-show-element", "#product-estimated-delivery(#livraison-estime)", ".product-collapsible-content(.no-click-highlight)",
        ".ProductForm__Advantages(.ProductForm__Advantage--cell .ProductForm__Advantage)", ".ProductForm--payicons(.StorePay--payicons)",
        "div.stp-star[data-rating-stp](span.spt-badge-caption)", ".product-block-liquid-code(span.stock)", ".product-block-text(.description.rte)",
        "[id*='product-block-animated-stories-animated_stories'](ul.stories-list)", ".product-block-rating-natif(svg)",
        ".product-reviews-dummy(.product-reviews-dummy-stars)", "p(span#current-date)",
        ".product-block-liquid-code(.choco_produit_soustitre3 .choco_produit_soustitre)", ".product-block-text(h2.title.h5)", ".choco_container_info_livraison_paiement(.choco_paiement_secure)", ".product-block-liquid-code(.choco_infos_charlideliss h4)", ".product-block-liquid-code(.choco_bandeau_icones img)",
        ".votre_cure(p span.prix_votre_cure)", "h2.title(div.h2_svg span svg)",".product-meta(h1.product-meta__title.h1)", ".product-block-liquid-code(ul.checkmark-list > li.checkmark-item > meta)",
        ".product-block-liquid-code(.container-trustpilot > span.excellent > b)", "#product-estimated-delivery(.delivery-message)", "#breadcrumbs(nav.breadcrumb a)", ".product-block-tabs ([id*='nav-tabs-tabs_'].nav.nav-pills)",
        "#bought-product-together (.product-listing.list-unstyled h3.product-item-title)", "button[data-bs-target='#size-chart-modal'](div svg)",
        ".product__button__meta .variant__countdown[data-remaining-wrapper](span[data-remaining-count])", ".ccpc.ccpc-display.product-information-social-proof", "[class*='__ss_trust_badges_3_'] [class*='__ss_trust_badges_3_']",
        "[id*='marquee-scrolling_text_'].product-block-scrolling-text", ".product-block-liquid-code .product-benefits", ".product-block-media video[playsinline='playsinline']", "[id*='marquee-marquee_'].product-block-marquee",
        "#product-limited-offer (div.block-icon svg)", ".productView-groupBottom(.productView-groupItem .productView-payment #gokwik-buy-now)", ".product-block-liquid-code .varino-story-videos(video.story-video)", ".product-block-liquid-code .nalovea-checklist-section(.nalovea-check-item)",
         ".widereview-mini", "[class*='_ss_product_reviews_'][id*='_ss_product_reviews_']", "ul.ss-payment-list[id*='_ss_payments_icons_']", '.product-block-text h2.title.h4', "[id*='product-block-testimonials-testimonials_'].product-block-testimonials(.carousel-indicators)", ".mm-title .mm-title", 
        ".mm-product-form-description(p strong)", ".mm-product-form-keypoints(.mm-product-form-keypoint img)", ".mm-product-form-component.mm-pf-infos-product-container", "[class*='__ss_scrolling_annoucement_bar_']",
        ".product-title-wrapper h1.product-title", ".product-text-wrapper.rte p", ".product--breadcrumbs(ul.breadcrumbs--root)",
        ".product-block-testimonials(.carousel-inner)", "kaching-subscriptions", ".product-block-liquid-code(.made-in-france)", ".product-block-liquid-code(.kit-container)", "section.features(.feature span.pill)", "h1.product-single__title", ".product__price(.price)", ".product-block-media(img)"
    ];

      var parentsToExcept = ['.cross-sell-block', '.accordion-item'];

    //Show elements if we found add to cart of variants selector
    if(variantsSelector || addToCartButton){
        //Get position of at least one of the elements
        if(variantsSelector?.element[0]?.getBoundingClientRect()?.top > 0){
            elementPosition = variantsSelector.element[0].getBoundingClientRect().top;
        }
        else if(addToCartButton?.element?.getBoundingClientRect()?.top > 0){
            elementPosition = addToCartButton.element.getBoundingClientRect().top;
        }
        //If the elements are visible and we have a position
        if(typeof elementPosition != "undefined" && elementPosition != ""){
            elementsAboveVariants = [];
            elementsBelowVariants = [];

            for(var y=0; y<elementsToShow.length; y++){
                //Check if the element needs to have a specific child to be shown. Specific children are inside parenthesis -> .elem(.child)
                testHasChild = elementsToShow[y].split('(');
                hasChild = "";
                if(testHasChild.length > 1 && !elementsToShow[y].includes(":not")){
                    theElementToShow = testHasChild[0];
                    hasChild = testHasChild[1].split(')')[0];
                }
                else{
                    theElementToShow = elementsToShow[y];
                }
                //Search for the hidden element
                var newNodeToShow = wideBundle.formInfo.element.querySelectorAll(theElementToShow);
                newNodeToShowLength = newNodeToShow.length;
                if(newNodeToShowLength){
                    checkAllElementsFound:
                    for(i=0; i<newNodeToShowLength; i++){
                        console.log(newNodeToShow[i].getBoundingClientRect().top);
                        if(hasChild == "" || (newNodeToShow[i].querySelector(hasChild) != null && !newNodeToShow[i].querySelector(theElementToShow))){
                            //Check if the element is not a child of an exception
                            for(var j=0; j<parentsToExcept.length; j++){
                                var allParentsFound = document.querySelectorAll(parentsToExcept[j]);
                                for(var k=0; k<allParentsFound.length; k++){
                                  var parentToCheck = allParentsFound[k];
                                  if(isDescendant(parentToCheck, newNodeToShow[i])){
                                      continue checkAllElementsFound;
                                  }
                                }
                            }

                            //If hidden element is above the variants selector, add it to the array of elements above variants
                            if(newNodeToShow[i].getBoundingClientRect().top < elementPosition){
                                elementsAboveVariants.push(newNodeToShow[i]);
                            }
                            //If hidden element is below the variants selector, add it to the array of elements below variants
                            else{
                                elementsBelowVariants.push(newNodeToShow[i]);
                            }
                        }
                    }
                }
            }


            function removeChildElements(arrOfAllElements){
                let resultArray = [];
                for(let i=0;i<arrOfAllElements.length; i++){ // loop all the elements to check if each element is child of any other element
                  let isChild = arrOfAllElements.some((element, index) => index != i && isDescendant(element, arrOfAllElements[i]));
                  //if the current element is not child of any other element in the array, we add it to the result array
                  if(!isChild){
                    resultArray.push(arrOfAllElements[i])
                  } else {
                    console.log("Child, not adding in the result array: ", arrOfAllElements[i])
                  }
                }
                return resultArray
              }
              
              elementsAboveVariants = removeChildElements(elementsAboveVariants)
              elementsBelowVariants = removeChildElements(elementsBelowVariants)


            //Show hidden elements above or below the product form
            if(elementsAboveVariants.length || elementsBelowVariants.length ){
                elementsAboveVariants.sort(function(a, b) {
                    return a.getBoundingClientRect().top - b.getBoundingClientRect().top;
                });
                elementsBelowVariants.sort(function(a, b) {
                    return b.getBoundingClientRect().top - a.getBoundingClientRect().top;
                });

                var parentDiv = wideBundle.formInfo.element.parentNode;
                for(i=0; i<elementsAboveVariants.length; i++){
                    parentDiv.insertBefore(elementsAboveVariants[i], wideBundle.formInfo.element);
                }
                for(i=0; i<elementsBelowVariants.length; i++){
                    parentDiv.insertBefore(elementsBelowVariants[i], wideBundle.formInfo.element.nextSibling);
                }
            }
        }
    }
}

//Some elements need to be shown and hide using a different method
wideBundle.showAndHideElementsWithInterval = function(){

    if(!wideBundle.formInfo.element){
        return;
    }
    formWide = wideBundle.formInfo.element;

    var newNode1 = formWide.querySelector('.fastlane-faq-a2');
    if(newNode1 != null){
        newNode1 = formWide.querySelector('.fastlane-faq-a2').parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
        if(newNode1 != null && newNode1.classList.contains('editor_line_wrap_content_below_atc')){
            var parentDiv = formWide.parentNode;
            parentDiv.insertBefore(newNode1, formWide.nextSibling);
        }
    }

    if(wideBundle.formInfo.id == ".ProductForm"){
        var titleNode = formWide.querySelector('.ProductMeta .ProductMeta__Title');
        var priceNode = formWide.querySelector('.ProductMeta .ProductMeta__PriceList');
        var priceUniteNode = formWide.querySelector('.ProductMeta .ProductMeta__UnitPriceMeasurement');
        var taxNode = formWide.querySelector('.ProductMeta .ProductMeta__TaxNotice');
        var availableNode = formWide.querySelector('.ProductForm--Available');
        var descNode = formWide.querySelector('.ProductMeta__Description');

        if(titleNode != null && priceNode != null && priceUniteNode != null){
          var parentDiv = formWide.parentNode;
          priceNode.style.display = "block";
          parentDiv.insertBefore(titleNode, formWide);
          parentDiv.insertBefore(priceNode, formWide);
          parentDiv.insertBefore(priceUniteNode, formWide);
        }

        if(taxNode != null){
            var parentDiv = formWide.parentNode;
            parentDiv.insertBefore(taxNode, formWide);
        }
        if(availableNode != null){
            var parentDiv = formWide.parentNode;
            parentDiv.insertBefore(availableNode, formWide);
        }

        if(descNode != null){
          var parentDiv = formWide.parentNode;
          parentDiv.insertBefore(descNode, formWide.nextSibling);
        }
    }

    //Elements to show that load after WideBundle (addEventListener)
    var SHOW_BEFORE_WB = [
        ".sc-link", ".webyzeProductColors", ".jdgm-preview-badge", '.z-main-product__wrap-title', '.z-main-product__wrap-price-qty-reviews', '.z-main-product__description',
        ".ProductForm--Available2",".product-information-bullet-points"
    ];
    var SHOW_AFTER_WB = [
        ".best-fit-size-chart", "#easysell", "#es-popup-button", "afterpay-placement", ".htusb-ui-prod-boost-trust-wrapper", ".htusb-ui-prod-boost-generic-under-form",
        "._rsi-buy-now-button._rsi-buy-now-button-product", ".pbp-points", ".QuickPurchaseTop", "#ultimateTrustBadgeswidgetDiv",'.sealsubs-target-element:not(.no_move_wb)',
        ".visitor-counter-content-box-carecartbysalespop-2020", '.tempofrete', ".fretefundo", "#sizefox",'.payment-providers', '.cbb-frequently-bought-container',
        "a.klaviyo-bis-trigger[href='#']", '.ot-estimated-shipping'
    ];
    var SHOW_BEFORE_WB_ATC = [
        ".delivery-time", '.product-information-shipping-information',
    ];
    var SHOW_BEFORE_WB_ATC_NOT_FORM = [
        '.axe-checkbox'
    ];
    var SHOW_AFTER_WB_STYLE = [
        "#cpb-button"
    ];

    var DISPLAY_FLEX = [
        ".fretefundo"
    ];
    //Show element if it exists with setInterval iteration to catch it the moment it appears
    loopCount = 0;
    intervalFunction = setInterval(function() {
        if(wideBundle.formInfo.id != "page builder"){
          for(var i=0; i<SHOW_BEFORE_WB.length; i++){
              elementNode = formWide.querySelector(SHOW_BEFORE_WB[i]);
              if(elementNode){
                  var parentDiv = formWide.parentNode;
                  parentDiv.insertBefore(elementNode, formWide);
              }
          }
        }
        for(var i=0; i<SHOW_BEFORE_WB_ATC.length; i++){
            elementNode = formWide.querySelector(SHOW_BEFORE_WB_ATC[i]);
            if(elementNode){
                buttonWB = document.querySelector('.new-form-atc');
                if(buttonWB){
                    buttonWB.parentNode.insertBefore(elementNode, buttonWB);
                    elementNode.style.display = "block";
                }
            }
        }
        for(var i=0; i<SHOW_BEFORE_WB_ATC_NOT_FORM.length; i++){
            elementNode = document.querySelector(SHOW_BEFORE_WB_ATC_NOT_FORM[i]);
            if(elementNode){
                buttonWB = document.querySelector('.new-form-atc');
                if(buttonWB){
                    buttonWB.parentNode.insertBefore(elementNode, buttonWB);
                    elementNode.style.display = "block";
                }
            }
        }
        if(wideBundle.formInfo.id != "page builder"){
            for(var i=0; i<SHOW_AFTER_WB.length; i++){
                elementNode = formWide.querySelector(SHOW_AFTER_WB[i]);
                alreadyDoneElement = document.querySelector(SHOW_AFTER_WB[i]+".moved_wb_element"); //Check if the same element hasn't already been moved
                if(elementNode && !alreadyDoneElement){
                    buttonWB = document.querySelector('.new-form-atc');
                    if(buttonWB.nextSibling){
                        buttonWB.parentNode.insertBefore(elementNode, buttonWB.nextSibling);
                        elementNode.style.display = "block";
                        elementNode.classList.add('moved_wb_element');
                    }
                    else{
                        buttonWB.parentNode.appendChild(elementNode);
                        elementNode.classList.add('moved_wb_element');
                    }
                }
            }
        }
        for(var i=0; i<SHOW_AFTER_WB_STYLE.length; i++){
            elementNode = formWide.querySelector(SHOW_AFTER_WB_STYLE[i]);
            if(elementNode){
                const styles = window.getComputedStyle(elementNode);
                let cssText = styles.cssText;
                if (!cssText) {
                    cssText = Array.from(styles).reduce((str, property) => {
                        return `${str}${property}:${styles.getPropertyValue(property)};`;
                    }, '');
                }
                elementNode.style.cssText = cssText;
                buttonWB = document.querySelector('.new-form-atc');
                if(buttonWB.nextSibling){
                    buttonWB.parentNode.insertBefore(elementNode, buttonWB.nextSibling);
                    elementNode.style.display = "block";
                }
                else{
                    buttonWB.parentNode.appendChild(elementNode);
                }
            }
        }

        for(var i=0; i<DISPLAY_FLEX.length; i++){
            elementNode = document.querySelector(DISPLAY_FLEX[i]);
            if(elementNode){
                elementNode.style.display = "flex";
            }
        }

        //To show Dynamic buttons and create the environment so they can work outside the product form
        wideBundle.manageDynamicButton();

        loopCount++;
        if(loopCount >= 50){
            clearInterval(intervalFunction);
        }
    }, 300);



    //Elements to hide that load after WideBundle (addEventListener)
    var elementsToHideWithEventListener = [
        ".product-detail .product-form.theme-init .option-selectors", 'variant-swatch-king'
    ];
    //Hide element if it exists with setInterval iteration to catch it the moment it appears
    loopCountHide = 0;
    intervalFunctionHide = setInterval(function() {
        elementsToHideWithEventListenerLength = elementsToHideWithEventListener.length;
        for(var y=0; y<elementsToHideWithEventListenerLength; y++){
            elementNodeHide = document.querySelector(elementsToHideWithEventListener[y]);
            if(elementNodeHide){
                elementNodeHide.style.display = "none";
                elementNodeHide.classList.add("hide-unwanted-widebundle");
            }
        }
        loopCountHide++;
        if(loopCountHide >= 50){
            clearInterval(intervalFunctionHide);
        }
    }, 300);
}

//Manage the dynamic button to show
wideBundle.manageDynamicButton = function(){
    if(wideBundle.formInfo.id != "page builder" && !document.querySelector('.dynamic_button_wb_form') ){
        let dynamicButtonSelectors = [
            'div.shopify-payment-button[data-shopify="payment-button"] div', 
            'div.shopify-payment-button[data-shopify="payment-button"] shopify-buy-it-now-button',
            'div.shopify-payment-button[data-shopify="payment-button"] shopify-accelerated-checkout',
        ]
        for(i=0; i<dynamicButtonSelectors.length; i++){
            elementNode = formWide.querySelector(dynamicButtonSelectors[i]);
            if(elementNode){
                break;
            }
        }

        if(elementNode && !elementNode.classList.contains('cloned')){
            elementNode.classList.add('cloned');
            elementNodeParent = formWide.querySelector('div.shopify-payment-button[data-shopify="payment-button"]');
            buttonWB = document.querySelector('.new-form-atc');

            var newFormCreated = document.createElement('form');
            
            if(wideBundle.formInfo.element.hasAttribute('action')){
                newFormCreated.setAttribute('action', wideBundle.formInfo.element.getAttribute('action'));
            }
            else{
                newFormCreated.setAttribute('action', '/cart/add');
            }
            newFormCreated.classList.add('dynamic_button_wb_form');

            var originalHiddenInput = wideBundle.formInfo.element.querySelector('[name="id"]');
            if (originalHiddenInput) {
                idValue = originalHiddenInput.value;
            }
            else{
                idValue = wideBundle.getSelectedVariantId()[0];
            }
            // Create a new hidden input with the same value
            var newHiddenInput = document.createElement('input');
            newHiddenInput.setAttribute('type', 'hidden');
            newHiddenInput.setAttribute('name', 'id');
            newHiddenInput.value = idValue;

            // Append the hidden input to the new form
            newFormCreated.appendChild(newHiddenInput);

            // Append the duplicated button to the new form
            newFormCreated.appendChild(elementNodeParent);

            if(buttonWB.nextSibling){
                buttonWB.parentNode.insertBefore(newFormCreated, buttonWB.nextSibling);
                elementNodeParent.style.display = "block";
            }
            else{
                buttonWB.parentNode.appendChild(newFormCreated);
            }
            console.log(document.querySelector('#new-form div.shopify-payment-button[data-shopify="payment-button"] button'));
        }
    }
}

//To Update the variant ID selected in the form we created for the dynamic button
wideBundle.manageSelectedVariantForDynamicButton = function(){
    idInput = document.querySelector('.dynamic_button_wb_form [name="id"]');
    if(idInput){
        var originalHiddenInput = wideBundle.formInfo.element.querySelector('[name="id"]');
        if (originalHiddenInput) {
            idValue = originalHiddenInput.value;
        }
        else{
            idValue = wideBundle.getSelectedVariantId()[0];
        }
        idInput.value = idValue;
    }
}

//Preselect one offer so one is selected by default
wideBundle.preselectOffer = function(){
    var preselectedOffer = 0; //Check if the user preselected an offer
    for(var i = 0; i<wideBundle.offers.length; i++){
        if(wideBundle.offers[i][0].preselected == 1){
            preselectedOffer = i;
            break;
        }
    }

    //Check if a variant is in the URL so we use it
    hasVariant = new URLSearchParams(window.location.search.toLowerCase()).get('variant');
    if(hasVariant){
        offersLoop: for(var i = 0; i<wideBundle.offers.length; i++){
            offer = wideBundle.offers[i][0];
            for(var j = 0; j<offer.variants.length; j++){
                variant = offer.variants[j];
                if(variant.id == hasVariant){
                    preselectedOffer = i;
                    break offersLoop;
                }
            }
        }
        var offerValues = wideBundle.getOfferValuesForVariant(hasVariant);
    }

    //Add the class to show the offer is selected
    document.querySelectorAll('#new-form .new-form-option')[preselectedOffer].classList.add("selectedWB");
    document.querySelectorAll('#new-form .new-form-option')[preselectedOffer].classList.remove("selectable");
    for(var i=0; i<document.querySelectorAll('.new-wb-form').length; i++){
        var secondaryWidget = document.querySelectorAll('.new-wb-form')[i];
        secondaryWidget.querySelectorAll('.new-form-option')[preselectedOffer].classList.add('selectedWB');
        secondaryWidget.querySelectorAll('.new-form-option')[preselectedOffer].classList.remove('selectable');
    }

    wideBundle.updateMainPrice(); //Update price under the title

    if(hasVariant && offerValues){ //Select the right values on WideBundle based on the variant in the URL
        for(var i = 0; i<offerValues.option1.length; i++){
            // document.querySelectorAll('.selectedWB .select-option-second')[i].value = offerValues.option1[i];
            let j = i + 1;
            let selects = document.querySelectorAll('.selectedWB .select-option-second-' + j);
            selects.forEach(function (element) {
                let optionExists = Array.from(element.options).some(option => option.value === offerValues.option1[i]);
                if (optionExists) {
                    element.value = offerValues.option1[i];
                }
            });
            // Preselect swatches if any

            let escapedValue = wbEscapeSwatchValue(offerValues.option1[i]);
            let radios = document.querySelectorAll(`.selectedWB .swatch-2-radio-${j}[value="${escapedValue}"]`);
            radios.forEach(function(element) {
                element.checked = true;
            });
        }
        for(var i = 0; i<offerValues.option2.length; i++){
            // document.querySelectorAll('.selectedWB .select-option-third')[i].value = offerValues.option2[i];
            let j = i + 1;
            let selects = document.querySelectorAll('.selectedWB .select-option-third-' + j);
            selects.forEach(function (element) {
                let optionExists = Array.from(element.options).some(option => option.value === offerValues.option2[i]);
                if (optionExists) {
                    element.value = offerValues.option2[i];
                }
            });

            // Preselect swatches if any
            let escapedValue = wbEscapeSwatchValue(offerValues.option2[i]);
            let radios = document.querySelectorAll(`.selectedWB .swatch-3-radio-${j}[value="${escapedValue}"]`);
            radios.forEach(function(element) {
                element.checked = true;
            });
        }
        for(var i = 0; i<offerValues.option3.length; i++){
            // document.querySelectorAll('.selectedWB .select-option-third')[i].value = offerValues.option2[i];
            let j = i + 1;
            let selects = document.querySelectorAll('.selectedWB .select-option-first-' + j);
            selects.forEach(function (element) {
                let optionExists = Array.from(element.options).some(option => option.value === offerValues.option3[i]);
                if (optionExists) {
                    element.value = offerValues.option3[i];
                }
            });

            // Preselect swatches if any
            let escapedValue = wbEscapeSwatchValue(offerValues.option3[i]);
            let radios = document.querySelectorAll(`.selectedWB .swatch-1-radio-${j}[value="${escapedValue}"]`);
            radios.forEach(function(element) {
                element.checked = true;
            });
        }
    }
}

//Create the blinking effect for the custom sentences
wideBundle.addBlinkingEffect = function(){
    if(document.querySelector('.best-title-blink')){
        setInterval(function(){
            for(var wb=0; wb<document.querySelectorAll('.best-title-blink').length; wb++){
                var blinker = document.querySelectorAll('.best-title-blink')[wb];
                if(blinker.style.opacity == 0){
                    blinker.style.opacity = 1;
                }else{
                    blinker.style.opacity = 0;
                }
            }
        }, 800);
    }
}

//Take out apps and complex elements from the form to show them on WideBundle directly such as apps for custom products or subscription or dynamic buttons
wideBundle.takeAppsOut = function(){

  //Function to clone and add inputs in hidden form
  function cloneAndHidePropertiesElements(element) {
    var elementsToDuplicate = document.querySelectorAll(`${element} [name^="properties"]`);
    elementsToDuplicate.forEach((elementToDuplicate) => {
      var newNode = elementToDuplicate.cloneNode();
      newNode.style.display = "none";
      newNode.classList.add('wb-duplicated');
      form.appendChild(newNode);
    });
  }
  //Remove all duplicated elements
  function removeDuplicatedElementsFromForm() {
    const duplicatedElementsInForm = form.querySelectorAll('.wb-duplicated');
    duplicatedElementsInForm.forEach((duplicatedElementInForm) => duplicatedElementInForm.remove());
  }

  if(!wideBundle.manualWidget){
    //For Some Apps
    var elementsToDuplicate = [".uploadkit-injected", ".upload-container", ".gpo-container", ".upload-container", "#textfieldapp"]; //Apps for custom elements
    var elementsToDuplicateSellingPlan = [".appstle_sub_widget"];
    let counterDuplicationWB = 0;
    let functionToUpdateInputs = {};
    let functionToUpdateInputsSellingPlan = {};
    var functionToCheckHiddenComplexElement = setInterval(() => {
      if (typeof form !== 'undefined' && form !== null) {
        var widebundle = document.querySelector('#new-form-atc');

        for(var i=0; i<elementsToDuplicate.length; i++){ //For each app to take out
          var elementClass = elementsToDuplicate[i];
          var elementToDuplicate = form.querySelector(elementClass);
          if (widebundle !== null && elementToDuplicate !== null) {
            var extraParent = widebundle.parentNode;
            extraParent.insertBefore(elementToDuplicate, widebundle);
            elementToDuplicate.style.display = "block";
            (function(i){
              functionToUpdateInputs[elementClass] = setInterval(() => { //Duplicate elements we want to put them in the product form
                elementClass = elementsToDuplicate[i];
                removeDuplicatedElementsFromForm();
                cloneAndHidePropertiesElements(elementClass);
              }, 200);
            })(i);
          }
        }


      }
      counterDuplicationWB++;
      if (counterDuplicationWB >= 50) {
        clearInterval(functionToCheckHiddenComplexElement);
      }
    }, 300);

  }

    //For Subscription App Recurpay - The goal is to show the widget without removing it from the form by using CSS and place it
    //before the add to cart button of WB

    function getAbsolutePosition(element) {
        var rect = element.getBoundingClientRect();
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
        return { top: rect.top + scrollTop, left: rect.left + scrollLeft };
    }
    function setButtonMargin(margin) {
        // Remove previous rule if it exists
        if(sheet.cssRules.length > 0) {
            sheet.deleteRule(0);
        }
        // Add new rule
        sheet.insertRule(`#new-form-atc { margin-top: ${margin}px !important; }`, 0);
    }
    // Create a style sheet
 var sheet = (function() {
    var style = document.createElement("style");
    style.appendChild(document.createTextNode("")); // WebKit hack
    document.head.appendChild(style);
    return style.sheet;
  })();
 
  // Position function for Recurpay
  function positionRecurpayWidget(widget) {
    if (widget) {
      var button = document.querySelector('#new-form-atc');
      // Set initial styles
      widget.style.display = 'block';
      widget.style.position = 'absolute';
      widget.style.top = '0';
      widget.style.zIndex = '1000';
      
      var buttonPos = getAbsolutePosition(button);
      var widgetPos = getAbsolutePosition(widget);
      widget.style.top = buttonPos.top - widgetPos.top + 'px';
      setButtonMargin(widget.offsetHeight + 10);
 
      // Update position and margin periodically (original behavior)
      const checkSubifyWidgetInterval = setInterval(function() {
     var subifySubs = wideBundle.formInfo.element.querySelector('.subify-widget-container');
     if(!subifySubs){
         setButtonMargin(0);
         widget.style.top = '0';
         var buttonPos = getAbsolutePosition(button);
         var widgetPos = getAbsolutePosition(widget);
         widget.style.top = buttonPos.top - widgetPos.top + 'px';
         setButtonMargin(widget.offsetHeight + 10);
     } else {
         clearInterval(checkSubifyWidgetInterval);
     }
 }, 100);
    }
  }
 
  // Position function for Subify
  function positionSubifyWidget(widget) {
    if (widget) {
      var button = document.querySelector('#new-form-atc');
      // Set initial styles
      widget.style.display = 'block';
      widget.style.position = 'absolute';
      widget.style.top = '0';
      widget.style.zIndex = '1000';
 
        var titleElement = widget.querySelector('#subify-widget-title');
      if(titleElement) {
        titleElement.style.marginTop = '0px';
      }
      
      var buttonPos = getAbsolutePosition(button);
      var widgetPos = getAbsolutePosition(widget);
      widget.style.top = buttonPos.top - widgetPos.top + 'px';
      setButtonMargin(widget.offsetHeight + 20);
 
      // Update position and margin periodically
      setInterval(function() {
        if(widget.offsetHeight != 0){
          setButtonMargin(0);
          widget.style.top = '0';
          var buttonPos = getAbsolutePosition(button);
          var widgetPos = getAbsolutePosition(widget);
          widget.style.top = buttonPos.top - widgetPos.top + 'px';
          setButtonMargin(widget.offsetHeight + 20);
        }
      }, 50);
    }
  }
 
  // Handle Recurpay Widget
  function handleRecurpayWidget() {
    var retryCount = 0;
    var maxRetries = 20;
    
    var formCheckIntervalRecurpay = setInterval(function() {
      retryCount++;
 
      if (typeof form != "undefined" && form) {
        var recurpaySubs = wideBundle.formInfo.element.querySelector('.recurpay-pdp-widget');
          var subifySubs = wideBundle.formInfo.element.querySelector('.subify-widget-container');
          if(subifySubs){
              clearInterval(formCheckIntervalRecurpay);
          }
        else if(recurpaySubs){
          clearInterval(formCheckIntervalRecurpay);
          positionRecurpayWidget(recurpaySubs);
        }
      }
      if(retryCount >= maxRetries){
        clearInterval(formCheckIntervalRecurpay);
      }
    }, 300);
  }
 
  // Handle Subify Widget  
  function handleSubifyWidget() {
    var retryCount = 0;
    var maxRetries = 20;
    
    var formCheckIntervalSubify = setInterval(function() {
      retryCount++;
 
      if (typeof form != "undefined" && form) {
        var subifySubs = wideBundle.formInfo.element.querySelector('.subify-widget-container');
        if(subifySubs){
          clearInterval(formCheckIntervalSubify);
          positionSubifyWidget(subifySubs);
        }
      }
      if(retryCount >= maxRetries){
        clearInterval(formCheckIntervalSubify);
      }
    }, 300);
  }
 
  // Initialize both widgets
  handleRecurpayWidget();
  handleSubifyWidget();
}

//Show an error if the user is using a page builder but not using manual widget placement
wideBundle.handleErrorsPageBuilders = function(){
    //For GemPages
    if(!wideBundle.manualWidget &&
        ((document.querySelector(".gf_row") && document.querySelector('body.gempage') && document.querySelector("div[data-label='Product']")) ||
        (document.querySelector('div[label="Block"]') && document.querySelector('gp-product')))
    ){
        wideBundle.createError("You have to use WideBundle's module from GemPages.", "https://help.widebundle.com/en/article/how-to-use-widebundle-with-gempages-qywl1/#2-3-add-the-widebundle-module")
    }

    //For PageFly
    if(!wideBundle.manualWidget && document.querySelector("div[data-pf-type='Body']") && document.querySelector('[data-pf-type="ProductBox"]') && isDescendant(document.querySelector('[data-pf-type="ProductBox"]'), document.querySelector('#new-form'))){
        wideBundle.createError("You have to use WideBundle's module from PageFly.", "https://help.widebundle.com/en/article/how-to-use-widebundle-with-pagefly-suqsj9/#2-add-the-widebundle-module")
    }
}

//Create a main widget if we only have secondary widgets
wideBundle.transformMainElement = function(){
    // Check if there's no element with the ID 'new-form'
    if (!document.getElementById('new-form')) {
        // Get the first '<widebundle-module>' element
        let widget = document.querySelector('widebundle-module');
        if (widget) {
            // Set the ID to 'new-form'
            widget.id = 'new-form';
        }
    }

    // Add .new-wb-form class to all <widebundle-module> elements except the one with #new-form
    let widgets = document.querySelectorAll('widebundle-module:not(#new-form)');
    widgets.forEach(widget => {
        widget.classList.add('new-wb-form');
    });
}

//Retrieve random variant for A/B tests from localstorage (or generate using customer id/ip address)
wideBundle.retrieveAbTestVariant = function() {
    const localStorageKey = "widebundle-ab-test-variant";
    const availableChoices = ["A", "B"];
    const fallbackChoice = availableChoices[Math.ceil(Math.random() * 1023) % availableChoices.length];

    try {
        const storedChoice = window.localStorage.getItem(localStorageKey);
        if (storedChoice === "A" || storedChoice === "B") {
            console.log("Widebundle: a/b test variant from localStorage:", storedChoice);
            return storedChoice;
        } else {
            let generatedChoice;
            if (window.hasOwnProperty("wideBundle_shopifyCustomerId") && window?.wideBundle_shopifyCustomerId > 0) {
                generatedChoice = availableChoices[window.wideBundle_shopifyCustomerId % availableChoices.length];
                console.log("Widebundle: generate a/b test variant from customer id:", window.wideBundle_shopifyCustomerId, generatedChoice);
            } else if (window.wideBundle.hasOwnProperty("ipHash") && window?.wideBundle?.ipHash > 0) {
                generatedChoice = availableChoices[parseInt(window.wideBundle.ipHash) % availableChoices.length];
                console.log("Widebundle: generate a/b test variant from ip hash:", window.wideBundle.ipHash, generatedChoice);
            } else {
                generatedChoice = fallbackChoice;
                console.log("Widebundle: failed to generate a/b test variant: no cid/ip available");
                console.log("Widebundle: taking random variant:", generatedChoice);
            }
            
            window.localStorage.setItem(localStorageKey, generatedChoice);
            return generatedChoice;
        }
    } catch (error) {
        console.log("Widebundle: failed to generate a/b test variant:", error);
        console.log("Widebundle: taking random variant:", fallbackChoice);
        window.localStorage.setItem(localStorageKey, fallbackChoice);
        return fallbackChoice;
    }
}



//Get Variants of the product from Shopify
wideBundle.getVariantsOnShopify = function(){

    //We can then check if ideBundle?.variantsOnShopify exists
    var variantsFromJson = wideBundle.getVariantsFromJson(wideBundle.getSelectedVariantId()[0]);
    if(variantsFromJson){
        wideBundle.variantsOnShopify = variantsFromJson;
        if (wideBundle.getSelectedOffer().automatic_discount) {
            const selectedVariants = wideBundle.getSelectedVariantId();
            selectedVariants.forEach((selectedVariant, _idx) => {
                if (_idx == 0) return;

                wideBundle.variantsOnShopify = [...wideBundle.variantsOnShopify, ...wideBundle.getVariantsFromJson(selectedVariant)];
            });
        }
    }
    else{
        if (window.hasOwnProperty("wideBundlePreviewMode") && window?.wideBundlePreviewMode === true) {
            return;
        }

        var urlProductAPI = `${window.Shopify.routes.root}products/${wideBundle.currentHandle}.js`;
          fetch(urlProductAPI)
          .then(response => response.json())
          .then(product => {
            wideBundle.variantsOnShopify = product.variants;
            if (wideBundle.getSelectedOffer().automatic_discount) {
                const selectedOfferProducts = wideBundle.offers[wideBundle.getSelectedOffer().offersPointer];
                for (const product of selectedOfferProducts) {
                    if (product.product_handle == wideBundle.currentHandle || encodeURI(product.product_handle) == wideBundle.currentHandle) continue;
                    if (product.dynamicGroupUuid !== null && product.dynamicGroupSelected === null) {
                        continue;
                    }
    
                    const urlProductAPI = `${window.Shopify.routes.root}products/${product.product_handle}.js`;
                    fetch(urlProductAPI)
                        .then(response => response.json())
                        .then(product => {
                            wideBundle.variantsOnShopify = [...wideBundle.variantsOnShopify, ...product.variants];
                        })
                        .catch(error => console.error(error));
                }
            }
          })
          .catch(error => console.error(error));
    }
}

//Get Variants of the offer from DB
wideBundle.getVariantsInventory = async function(){
    wideBundle.variantsInventory = {};
    if (!wideBundle.isAutomaticDiscount) return;
    
    const allProductIds = [];
    wideBundle.offers.forEach((offerGroup) => {
        offerGroup.forEach((offer) => {
            const productId = parseInt(offer.product_id);
            if (!allProductIds.includes(productId) && !offer.all_products) {
                allProductIds.push(productId);
            }
        });
    });

    if (window.hasOwnProperty("wideBundlePreviewMode") && window?.wideBundlePreviewMode === true) {
        allProductIds.forEach(variant_id => {
            wideBundle.variantsInventory[variant_id] = {
                inventory_quantity: 999999,
                add_to_cart_btn_enable: '1'
            };
        });
        return;
    }

    const fetchUrl = new URL(wideBundle.domain + 'storefront/getvariantinventory');
    fetchUrl.searchParams.set('shop', wideBundle.shop);
    fetchUrl.searchParams.set('product_ids', allProductIds.join(','));
    const response = await window.originalFetch(fetchUrl.toString(), { mode: 'cors' });
    const fetchData = await response.json();
    wideBundle.variantsInventory = Array.isArray(fetchData) ? {} : fetchData;

    if (window.hasOwnProperty("wideBundle_targetProduct")) {
        window.wideBundle_targetProduct.variants.forEach((variant) => {
            const inventoryManagement = variant.inventory_management ?? '';
            const inventoryPolicy = (variant.inventory_policy ?? '').toLowerCase();

            // Set inventory quantity to 999999 if inventory policy is 'continue' or inventory management is empty
            let inventoryQuantity;
            if (inventoryPolicy === 'continue' || !inventoryManagement) {
                inventoryQuantity = 999999;
            } else {
                inventoryQuantity = variant.inventory_quantity ?? 0;
            }

            let addToCartBtnEnable = '1'; // Default to enabled
            if (inventoryManagement && inventoryPolicy !== 'continue' && inventoryQuantity <= 0) {
                addToCartBtnEnable = '0';
            }

            wideBundle.variantsInventory[variant.id] = {
                inventory_quantity: inventoryQuantity,
                add_to_cart_btn_enable: addToCartBtnEnable
            };
        });
    }
}
//Create the widget container
wideBundle.createWidgetContainer = function(){
    var container = document.createElement('div');
    container.id = 'new-form';
    var formWB = wideBundle.formInfo.element;
    formWB.parentNode.insertBefore(container, formWB.nextSibling); //We place the container after product form found
    wideBundle.hideOrShowProductForm("hide"); //We hide the product form so it's not duplicated with WideBundle

    setInterval(() => { //We hide the product form with delay for some themes
        if (wideBundle.formVisible === 0) {
            wideBundle.hideOrShowProductForm("hide");
        }
    }, 1000);

    return container; //We return the container we created
}

//Create the offers variable to get the information we have to display
wideBundle.getOffersData = function(data) {
    const offerMap = new Map();
    let dataLength = data.length;
    
    // Precompute function references
    const formatPrice = wideBundle.formatPrice;
    const getPricesFromJson = wideBundle.getPricesFromJson;
    const getAmountFromPrice = wideBundle.getAmountFromPrice;

    let offersPointer = 0;

    for (let i = 0; i < dataLength; i++) {
        const variant = data[i];
        const offerTitle = variant.variant_option1;
        let offer = offerMap.get(offerTitle);
        
        if (!offer) {
            offer = [wideBundle_prepareOfferVariantData(variant, offersPointer)];
            if (variant.products_amount > 1) {
                data.forEach((additionalVariant) => {
                    if (additionalVariant.product_id == variant.product_id && additionalVariant?.product_is_gift == variant?.product_is_gift) return;
                    if (additionalVariant.variant_option1 !== variant.variant_option1) return;
                    if (offer.findIndex(newOfferItem => newOfferItem.product_id == additionalVariant.product_id && newOfferItem?.product_is_gift == additionalVariant?.product_is_gift) > -1) return;

                    offer.push(wideBundle_prepareOfferVariantData(additionalVariant, offersPointer));
                });
            }
            offerMap.set(offerTitle, offer);
            offersPointer += 1;

            // Update option values and variants for each product in the offer
            offer.forEach(product => {
                data.forEach(variantData => {
                    if (variantData.product_id === product.product_id && variantData.variant_option1 === offerTitle) {
                        if (variantData.variant_option2) {
                            (variantData.automatic_discount ? variantData.variant_option2.split('|') : variantData.variant_option2.split(','))
                                .forEach(v => product.option2_values.add(v.trim()));
                        }
                        if (variantData.variant_option3) {
                            (variantData.automatic_discount ? variantData.variant_option3.split('|') : variantData.variant_option3.split(','))
                                .forEach(v => product.option3_values.add(v.trim()));
                        }
                        if (variantData.variant_option4 && variantData.automatic_discount) {
                            variantData.variant_option4.split('|').forEach(v => product.option4_values.add(v.trim()));
                        }
                        
                        // Add variant
                        const pricesFound = getPricesFromJson(variantData.variant_id);
                        const convertedPrice = (Math.round(variantData.variant_price * parseFloat(Shopify.currency.rate) * 100) / 100).toFixed(2);
                        const convertedComparedPrice = (Math.round(variantData.variant_compared * parseFloat(Shopify.currency.rate) * 100) / 100).toFixed(2);
                        const price = pricesFound ? pricesFound.price : formatPrice(convertedPrice);
                        product.variants.push({
                            id: parseInt(variantData.variant_id),
                            price: price,
                            compare_at_price: pricesFound ? pricesFound.compare_at_price : formatPrice(convertedComparedPrice),
                            option1: variantData.variant_option1,
                            option2: variantData.variant_option2 == "" ? null : variantData.variant_option2,
                            option3: variantData.variant_option3 == "" ? null : variantData.variant_option3,
                            option4: variantData.variant_option4,
                            conversion_rate: variantData.variant_price / getAmountFromPrice(price)
                        });
                    }
                });
            });
        }

        
    }

    wideBundle.offers = Array.from(offerMap.values());
    
    // Convert Sets to Arrays
    wideBundle.offers = wideBundle.offers.map(offer => {
        return offer.map(product => {
            product.product_id = product.product_id?.toString()?.split(":::")?.[0] ?? product.product_id;
            product.option2_values = Array.from(product.option2_values || []);
            product.option3_values = Array.from(product.option3_values || []);
            product.option4_values = Array.from(product.option4_values || []);
            return product;
        });
    });

    wideBundle.heading = wideBundle.offers[0]?.[0]?.heading || '';
};

function wideBundle_prepareOfferVariantData(variant, offersPointer) {
    const automatic_discount = Boolean(variant?.automatic_discount);
    const all_products = Boolean(variant?.all_products);
    return {
        automatic_discount,
        all_products,
        offersPointer,
        offer_title: variant.variant_option1,
        variants: [],
        message: variant.blinking_text,
        message_effect: variant.blinking_effect,
        message_position: variant.blinking_position,
        unit: variant.unit,
        unit_price: variant.unit_price,
        unit_text: variant.unit_text,
        product_id: variant.product_id,
        product_handle: variant.handle,
        product_qty: variant.product_qty ? variant.product_qty : 1,
        options_number: variant.variant_option3 ? 3 : variant.variant_option2 ? 2 : 1,
        offer_position: variant.position_offer,
        enabled: variant.enabled,
        image: variant.image,
        product_title: variant.title,
        preselected: variant.selected_offer,
        heading: variant.title_option1,
        options_labels: variant.title_option2,
        option1_title: variant.variant_option1_title,
        option2_title: variant.variant_option2_title,
        option3_title: variant.variant_option3_title,
        option4_title: variant.variant_option4_title,
        option2_is_color: variant.variant_option2_is_color,
        option3_is_color: variant.variant_option3_is_color,
        option4_is_color: variant?.variant_option4_is_color ?? false,
        price_in_offer: variant.variant_price,
        dropdowns_amount: automatic_discount ? variant.product_qty : (variant.variant_option2 ? variant.variant_option2.split(",").length : 0),
        option2_values: new Set(),
        option3_values: new Set(),
        option4_values: new Set(),
        swatch_options: variant.swatch_options ? variant.swatch_options : [],
        timer_type: variant?.timer_type ?? null,
        timer_duration: variant?.timer_duration ?? null,
        timer_end_date: variant?.timer_end_date ?? null,
        timer_text: variant?.timer_text ?? '',
        timer_text_color: variant?.timer_text_color ?? '',
        timer_text_style: variant?.timer_text_style ?? '',
        timer_text_size: variant?.timer_text_size ?? '',
        timer_background_color: variant?.timer_background_color ?? '',
        options_color_values: variant.options_color_values ? variant.options_color_values : [],
        discount_type: variant.discount_type ? variant.discount_type : null,
        discount_value: variant.discount_value ? variant.discount_value : null,
        gift_product: variant.gift_product ? variant.gift_product : null,
        gift_image: variant.gift_image ? variant.gift_image : "",
        gift_text: variant.gift_text ? variant.gift_text : "null",
        product_is_gift: variant?.product_is_gift === "1" ? true : false,
        product_is_upsell: variant?.product_is_upsell === "1" ? true : false,
        has_gift_products: variant?.has_gift_products ? true : false,
        has_upsell_products: variant?.has_upsell_products ? true : false,
        upsell_image: variant.upsell_image ? variant.upsell_image : "",
        upsell_text: variant.upsell_text ? variant.upsell_text : "",
        upsell_discount: variant.upsell_discount ? variant.upsell_discount : 0,
        offer_db_id: variant?.id ?? "",
        index: variant?.index ?? "",
        offer_uuid: variant?.offer_uuid ?? "",
        ab_test_variant: variant?.ab_test_variant ?? "",
        gift_placement: variant?.gift_placement || "bundle", // Add gift placement field
        text_above_gifts: variant?.text_above_gifts || "", // Add text above gifts field
        template_id: variant?.template_id ?? "default",
        dynamicGroups: variant?.dynamicGroups ?? [],
        dynamicGroupUuid: variant?.dynamicGroupUuid ?? null,
        dynamicGroupSelected: null,
        dynamicGroupSelectedImage: null,
        user_text_enabled: variant?.user_text_enabled ?? false,
        user_text_required: variant?.user_text_required ?? false,
        user_text_label: variant?.user_text_label || "",
        user_text_property: variant?.user_text_property || "",
        user_text_size: variant?.user_text_size || "1em",
        user_text_style: variant?.user_text_style || "none",
        user_text_color: variant?.user_text_color || "#000000",
    };
}

//Hide the product form or show it (action = "hide" or action = "show")
wideBundle.hideOrShowProductForm = function(action = "hide"){
    var cssProperties = {
        "width": action === "hide" ? "1px" : "auto",
        "height": action === "hide" ? "0px" : "auto",
        "overflow": action === "hide" ? "hidden" : "visible",
        "margin": action === "hide" ? "0px" : "auto",
        "marginTop": action === "hide" ? "0px" : "auto",
        "marginBottom": action === "hide" ? "0px" : "auto",
        "paddingTop": action === "hide" ? "0px" : "auto",
        "paddingBottom": action === "hide" ? "0px" : "auto"
      };
      //"display": action === "show" ? "block" : "none"

    var formWB = wideBundle.formInfo.element;
    for (var property in cssProperties) {
        formWB.style[property] = cssProperties[property];
    }

    wideBundle.formVisible = action === "show" ? 1 : 0;
    var displayValue = action === "show" ? "block" : "none";
    document.querySelectorAll('.hide-unwanted-widebundle').forEach(element => element.style.display = displayValue);
    document.documentElement.style.setProperty('--widebundle-element-visibility', displayValue); //For some elements using CSS where we applied a variable
}
showFormWB = function(){
    wideBundle.hideOrShowProductForm("show");
}

// Function to collect all free gifts from all offers
// Function to collect all free gifts from all offers
wideBundle.collectFreeGifts = function() {
    var allGifts = [];
    var productIdToOffers = {}; // Map product ID to an array of offers it appears in
    var hasUnderPlacement = false; // Flag to track if any gift has "under" placement
    
    // Loop through all offers to collect gift products
    for (var i = 0; i < wideBundle.offers.length; i++) {
        var offerGroup = wideBundle.offers[i];
        for (var j = 0; j < offerGroup.length; j++) {
            var offer = offerGroup[j];
            
            // Check if this offer has gift_placement set to "under"
            if (offer.gift_placement === "under") {
                hasUnderPlacement = true;
            }
            
            if (offer.product_is_gift) {
                // Skip gifts that should be displayed in the bundle
                if (offer.gift_placement !== "under") {
                    continue;
                }
                
                // If we haven't seen this product yet, create a new entry
                if (!productIdToOffers[offer.product_id]) {
                    productIdToOffers[offer.product_id] = [];
                    
                    // Add the gift to our collection
                    allGifts.push({
                        productId: offer.product_id,
                        productTitle: offer.product_title,
                        image: offer.gift_image || offer.image,
                        giftText: offer.gift_text || "Free Gift",
                        offerPointers: [offer.offersPointer], // Store array of offer pointers
                        productPointer: j,
                        option2Values: offer.option2_values,
                        option3Values: offer.option3_values,
                        option4Values: offer.option4_values,  // Make sure we collect option4Values
                        option2Title: offer.option2_title,
                        option3Title: offer.option3_title,
                        option4Title: offer.option4_title,    // Make sure we collect option4Title
                        option2IsColor: offer.option2_is_color,
                        option3IsColor: offer.option3_is_color,
                        option4IsColor: offer.option4_is_color, // Make sure we collect option4IsColor
                        optionsColorValues: offer.options_color_values,
                        variants: offer.variants,
                        giftPlacement: offer.gift_placement || "bundle" // Default to "bundle" if not specified
                    });
                } else {
                    // If we've seen this product before, just add the offer pointer
                    var existingGift = allGifts.find(g => g.productId === offer.product_id);
                    if (existingGift && !existingGift.offerPointers.includes(offer.offersPointer)) {
                        existingGift.offerPointers.push(offer.offersPointer);
                    }
                }
                
                // Add this offer to the product's list of offers
                if (!productIdToOffers[offer.product_id].includes(offer.offersPointer)) {
                    productIdToOffers[offer.product_id].push(offer.offersPointer);
                }
            }
        }
    }
    
    // Only return gifts if at least one has "under" placement
    return hasUnderPlacement ? allGifts : [];
};
// Function to create variant selectors for a gift
// Function to create variant selectors for a gift
wideBundle.createGiftVariantSelectors = function(gift, giftContent, offersPointer, productPointer) {
    // Create a unique ID for the swatches
    var swatchId = Math.floor(Math.random() * 898) + 101;
    
    // Create a container for the variant selectors
    var variantSelectorsContainer = document.createElement('div');
    variantSelectorsContainer.classList.add('wb-gift-variant-selectors');
    
    // Add label for the variant selectors if needed
    var optionsName = '';
    if (gift.option2Values && gift.option2Values.length > 1) {
        optionsName += gift.option2Title || 'Option';
    }
    if (gift.option3Values && gift.option3Values.length > 1) {
        if (optionsName) optionsName += ', ';
        optionsName += gift.option3Title || 'Option';
    }
    if (gift.option4Values && gift.option4Values.length > 1) {
        if (optionsName) optionsName += ', ';
        optionsName += gift.option4Title || 'Option';
    }
    
    if (optionsName) {
        var optionsLabel = document.createElement('p');
        optionsLabel.classList.add('wb-gift-options-label');
        optionsLabel.textContent = wideBundle.getTranslatedText(optionsName);
        variantSelectorsContainer.appendChild(optionsLabel);
    }
    
    // Create selectors/swatches for option2 if it has multiple values
    if (gift.option2Values && gift.option2Values.length > 1) {
        var option2Container = document.createElement('div');
        option2Container.classList.add('wb-gift-option-container');
        
        // Create the dropdown or swatch container
        if (gift.option2IsColor === "1" && wideBundle.settings.plan !== "monthly") {
            // Create swatches for color option
            var swatchBox = document.createElement('div');
            swatchBox.classList.add('wb-color-swatch-box', 'wb-gift-swatch-box');
            
            gift.option2Values.forEach(function(value, index) {
                var color_hex = gift.optionsColorValues[value];
                var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) 
                    ? `background-color: ${color_hex}` 
                    : `background-image: url(${color_hex})`;
                
                var swatchLabel = document.createElement('label');
                swatchLabel.classList.add('wb-color-swatch');
                
                var radioInput = document.createElement('input');
                radioInput.type = 'radio';
                radioInput.name = `GiftVariants2Swatch-${swatchId}-${offersPointer}-${productPointer}`;
                radioInput.classList.add('swatch-2-radio');
                radioInput.dataset.productId = gift.productId;
                radioInput.dataset.variantId = "2";
                radioInput.dataset.offersPointer = offersPointer;
                radioInput.dataset.productPointer = productPointer;
                radioInput.value = value;
                if (index === 0) radioInput.checked = "checked";
                
                radioInput.addEventListener('change', function() {
                    wideBundle.updateGiftVariantSelection(this);
                });
                
                var swatchDisplay = document.createElement('div');
                swatchDisplay.classList.add('wb-color-swatch-radio');
                swatchDisplay.title = wideBundle.getTranslatedText(value);
                swatchDisplay.style = style;
                
                swatchLabel.appendChild(radioInput);
                swatchLabel.appendChild(swatchDisplay);
                swatchBox.appendChild(swatchLabel);
            });
            
            option2Container.appendChild(swatchBox);
        } else {
            // Create dropdown for non-color option
            var select = document.createElement('select');
            select.classList.add('wb-gift-select');
            select.dataset.productId = gift.productId;
            select.dataset.optionNumber = "2";
            select.dataset.offersPointer = offersPointer;
            select.dataset.productPointer = productPointer;
            
            gift.option2Values.forEach(function(value, index) {
                var option = document.createElement('option');
                option.value = value;
                option.textContent = wideBundle.getTranslatedText(value);
                select.appendChild(option);
            });
            
            select.addEventListener('change', function() {
                wideBundle.updateGiftVariantSelection(this);
            });
            
            option2Container.appendChild(select);
        }
        
        variantSelectorsContainer.appendChild(option2Container);
    }
    
    // Create selectors/swatches for option3 if it has multiple values
    if (gift.option3Values && gift.option3Values.length > 1) {
        var option3Container = document.createElement('div');
        option3Container.classList.add('wb-gift-option-container');
        
        // Create the dropdown or swatch container
        if (gift.option3IsColor === "1" && wideBundle.settings.plan !== "monthly") {
            // Create swatches for color option
            var swatchBox = document.createElement('div');
            swatchBox.classList.add('wb-color-swatch-box', 'wb-gift-swatch-box');
            
            gift.option3Values.forEach(function(value, index) {
                var color_hex = gift.optionsColorValues[value];
                var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) 
                    ? `background-color: ${color_hex}` 
                    : `background-image: url(${color_hex})`;
                
                var swatchLabel = document.createElement('label');
                swatchLabel.classList.add('wb-color-swatch');
                
                var radioInput = document.createElement('input');
                radioInput.type = 'radio';
                radioInput.name = `GiftVariants3Swatch-${swatchId}-${offersPointer}-${productPointer}`;
                radioInput.classList.add('swatch-3-radio');
                radioInput.dataset.productId = gift.productId;
                radioInput.dataset.variantId = "3";
                radioInput.dataset.offersPointer = offersPointer;
                radioInput.dataset.productPointer = productPointer;
                radioInput.value = value;
                if (index === 0) radioInput.checked = "checked";
                
                radioInput.addEventListener('change', function() {
                    wideBundle.updateGiftVariantSelection(this);
                });
                
                var swatchDisplay = document.createElement('div');
                swatchDisplay.classList.add('wb-color-swatch-radio');
                swatchDisplay.title = wideBundle.getTranslatedText(value);
                swatchDisplay.style = style;
                
                swatchLabel.appendChild(radioInput);
                swatchLabel.appendChild(swatchDisplay);
                swatchBox.appendChild(swatchLabel);
            });
            
            option3Container.appendChild(swatchBox);
        } else {
            // Create dropdown for non-color option
            var select = document.createElement('select');
            select.classList.add('wb-gift-select');
            select.dataset.productId = gift.productId;
            select.dataset.optionNumber = "3";
            select.dataset.offersPointer = offersPointer;
            select.dataset.productPointer = productPointer;
            
            gift.option3Values.forEach(function(value, index) {
                var option = document.createElement('option');
                option.value = value;
                option.textContent = wideBundle.getTranslatedText(value);
                select.appendChild(option);
            });
            
            select.addEventListener('change', function() {
                wideBundle.updateGiftVariantSelection(this);
            });
            
            option3Container.appendChild(select);
        }
        
        variantSelectorsContainer.appendChild(option3Container);
    }
    
    // ADD SUPPORT FOR OPTION4 (the 3rd option)
    if (gift.option4Values && gift.option4Values.length > 1) {
        var option4Container = document.createElement('div');
        option4Container.classList.add('wb-gift-option-container');
        
        // Create the dropdown or swatch container
        if (gift.option4IsColor === "1" && wideBundle.settings.plan !== "monthly") {
            // Create swatches for color option
            var swatchBox = document.createElement('div');
            swatchBox.classList.add('wb-color-swatch-box', 'wb-gift-swatch-box');
            
            gift.option4Values.forEach(function(value, index) {
                var color_hex = gift.optionsColorValues[value];
                var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) 
                    ? `background-color: ${color_hex}` 
                    : `background-image: url(${color_hex})`;
                
                var swatchLabel = document.createElement('label');
                swatchLabel.classList.add('wb-color-swatch');
                
                var radioInput = document.createElement('input');
                radioInput.type = 'radio';
                radioInput.name = `GiftVariants4Swatch-${swatchId}-${offersPointer}-${productPointer}`;
                radioInput.classList.add('swatch-4-radio');
                radioInput.dataset.productId = gift.productId;
                radioInput.dataset.variantId = "4";
                radioInput.dataset.offersPointer = offersPointer;
                radioInput.dataset.productPointer = productPointer;
                radioInput.value = value;
                if (index === 0) radioInput.checked = "checked";
                
                radioInput.addEventListener('change', function() {
                    wideBundle.updateGiftVariantSelection(this);
                });
                
                var swatchDisplay = document.createElement('div');
                swatchDisplay.classList.add('wb-color-swatch-radio');
                swatchDisplay.title = wideBundle.getTranslatedText(value);
                swatchDisplay.style = style;
                
                swatchLabel.appendChild(radioInput);
                swatchLabel.appendChild(swatchDisplay);
                swatchBox.appendChild(swatchLabel);
            });
            
            option4Container.appendChild(swatchBox);
        } else {
            // Create dropdown for non-color option
            var select = document.createElement('select');
            select.classList.add('wb-gift-select');
            select.dataset.productId = gift.productId;
            select.dataset.optionNumber = "4";
            select.dataset.offersPointer = offersPointer;
            select.dataset.productPointer = productPointer;
            
            gift.option4Values.forEach(function(value, index) {
                var option = document.createElement('option');
                option.value = value;
                option.textContent = wideBundle.getTranslatedText(value);
                select.appendChild(option);
            });
            
            select.addEventListener('change', function() {
                wideBundle.updateGiftVariantSelection(this);
            });
            
            option4Container.appendChild(select);
        }
        
        variantSelectorsContainer.appendChild(option4Container);
    }
    
    giftContent.appendChild(variantSelectorsContainer);
};

// Function to handle variant selection changes correctly for all dropdowns
wideBundle.updateGiftVariantSelection = function(element) {
    // Get the identifying information
    var offersPointer = element.dataset.offersPointer;
    var productPointer = element.dataset.productPointer;
    var productId = element.dataset.productId;
    
    // Find the proper gift wrapper
    var giftWrapper = document.querySelector(`.selectedWB .wb-gift-product-wrapper[data-g-product-id="${productId}"]`);
    
    if (!giftWrapper) {
        // If not found directly, try finding by product ID
        var allWrappers = document.querySelectorAll(`.wb-gift-product-wrapper[data-g-offers-pointer="${offersPointer}"]`);
        for (var i = 0; i < allWrappers.length; i++) {
            if (allWrappers[i].getAttribute('data-g-product-id') == productId) {
                giftWrapper = allWrappers[i];
                break;
            }
        }
    }
    
    if (giftWrapper) {
        // Handle radio buttons (swatches)
        if (element.type === 'radio') {
            var optionNumber = element.dataset.variantId;
            
            // For option2
            if (optionNumber === "2") {
                // Try different selectors to find the right dropdown
                var selectorsToTry = [
                    'select.select-option-second', 
                    'select.select-class-second',
                    'select.select-bundle:not(.select-option-third):not(.select-option-first)'
                ];
                
                for (var i = 0; i < selectorsToTry.length; i++) {
                    var select = giftWrapper.querySelector(selectorsToTry[i]);
                    if (select && select.querySelector(`option[value="${element.value}"]`)) {
                        select.value = element.value;
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                        break;
                    }
                }
            }
            // For option3
            else if (optionNumber === "3") {
                // Try different selectors to find the right dropdown
                var selectorsToTry = [
                    'select.select-option-third', 
                    'select.select-class-third',
                    'select.select-bundle:not(.select-option-second):not(.select-option-first)'
                ];
                
                for (var i = 0; i < selectorsToTry.length; i++) {
                    var select = giftWrapper.querySelector(selectorsToTry[i]);
                    if (select && select.querySelector(`option[value="${element.value}"]`)) {
                        select.value = element.value;
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                        break;
                    }
                }
            }
            // For option4 (added support for the third option)
            else if (optionNumber === "4") {
                // Try different selectors to find the right dropdown
                var selectorsToTry = [
                    'select.select-option-first', 
                    'select.select-class-first',
                    'select.select-bundle:not(.select-option-second):not(.select-option-third)'
                ];
                
                for (var i = 0; i < selectorsToTry.length; i++) {
                    var select = giftWrapper.querySelector(selectorsToTry[i]);
                    if (select && select.querySelector(`option[value="${element.value}"]`)) {
                        select.value = element.value;
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                        break;
                    }
                }
            }
        }
        // Handle select dropdowns
        else if (element.tagName === 'SELECT') {
            var optionNumber = element.dataset.optionNumber;
            
            // For option2
            if (optionNumber === "2") {
                var selectorsToTry = [
                    'select.select-option-second', 
                    'select.select-class-second',
                    'select.select-bundle:not(.select-option-third):not(.select-option-first)'
                ];
                
                for (var i = 0; i < selectorsToTry.length; i++) {
                    var select = giftWrapper.querySelector(selectorsToTry[i]);
                    if (select && select.querySelector(`option[value="${element.value}"]`)) {
                        select.value = element.value;
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                        break;
                    }
                }
            }
            // For option3
            else if (optionNumber === "3") {
                var selectorsToTry = [
                    'select.select-option-third', 
                    'select.select-class-third',
                    'select.select-bundle:not(.select-option-second):not(.select-option-first)'
                ];
                
                for (var i = 0; i < selectorsToTry.length; i++) {
                    var select = giftWrapper.querySelector(selectorsToTry[i]);
                    if (select && select.querySelector(`option[value="${element.value}"]`)) {
                        select.value = element.value;
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                        break;
                    }
                }
            }
            // For option4 (added support for the third option)
            else if (optionNumber === "4") {
                var selectorsToTry = [
                    'select.select-option-first', 
                    'select.select-class-first',
                    'select.select-bundle:not(.select-option-second):not(.select-option-third)'
                ];
                
                for (var i = 0; i < selectorsToTry.length; i++) {
                    var select = giftWrapper.querySelector(selectorsToTry[i]);
                    if (select && select.querySelector(`option[value="${element.value}"]`)) {
                        select.value = element.value;
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                        break;
                    }
                }
            }
        }
    }
};

// We should also modify the createFreeGiftsDisplay function to make it easier to update the unlock message text
wideBundle.createFreeGiftsDisplay = function(widgetContainer) {
    var gifts = wideBundle.collectFreeGifts();
    
    // If no gifts with "under" placement, return early
    if (gifts.length === 0) {
        return null;
    }
    
    // Create the free gifts container
    var giftsContainer = document.createElement('div');
    giftsContainer.id = 'wb-all-free-gifts-container';
    giftsContainer.classList.add('wb-all-free-gifts-container');
    
    // Add "Unlock free gifts" message
    var unlockMessage = document.createElement('p');
    unlockMessage.classList.add('wb-gifts-unlock-message');
    
    // Get text from the first offer that has gifts with "under" placement
    var textAboveGifts = "";
    
    // Check if there's a preselected offer first
    var preselectedOffer = null;
    for (var i = 0; i < wideBundle.offers.length; i++) {
        if (wideBundle.offers[i][0].preselected == 1) {
            preselectedOffer = wideBundle.offers[i][0];
            // If the preselected offer has under free gifts with text, use it
            if (preselectedOffer.gift_placement === "under" && preselectedOffer.text_above_gifts) {
                textAboveGifts = preselectedOffer.text_above_gifts;
                break;
            }
        }
    }
    
    // If no preselected offer with under free gifts was found,
    // find the first offer that has gifts with "under" placement and text
    if (!textAboveGifts) {
        for (var i = 0; i < wideBundle.offers.length; i++) {
            var offerGroup = wideBundle.offers[i];
            for (var j = 0; j < offerGroup.length; j++) {
                var offer = offerGroup[j];
                if (offer.gift_placement === "under" && offer.text_above_gifts) {
                    textAboveGifts = offer.text_above_gifts;
                    break;
                }
            }
            if (textAboveGifts) break;
        }
    }
    
    // Use custom text if available, otherwise default message
    unlockMessage.innerHTML = wideBundle.getTranslatedText(textAboveGifts || '');
    giftsContainer.appendChild(unlockMessage);
    
    // Create a container for the gift cards
    var giftsCardsContainer = document.createElement('div');
    giftsCardsContainer.classList.add('wb-gifts-cards-container');
    
    // Create cards for each gift
    gifts.forEach(function(gift) {
        var giftCard = document.createElement('div');
        giftCard.classList.add('wb-gift-card');
        giftCard.setAttribute('data-product-id', gift.productId);
        giftCard.setAttribute('data-offer-pointers', gift.offerPointers.join(',')); // Store all offer pointers
        giftCard.setAttribute('data-product-pointer', gift.productPointer);
        
        // Add plus icon at the top (starts as X for locked)
        var plusIcon = document.createElement('div');
        plusIcon.classList.add('wb-gift-plus-icon');
        plusIcon.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 2L2 10" stroke="white" stroke-width="2" stroke-linecap="round"/><path d="M2 2L10 10" stroke="white" stroke-width="2" stroke-linecap="round"/></svg>';
        giftCard.appendChild(plusIcon);
        
        // Create gift content container
        var giftContent = document.createElement('div');
        giftContent.classList.add('wb-gift-card-content');
        
        // Create gift image wrapper to allow full-width images
        var imageWrapper = document.createElement('div');
        imageWrapper.classList.add('wb-gift-image-wrapper');
        
        // Get the appropriate image - first check preselected offer
        var imageSource = gift.image;
        var giftText = gift.giftText;
        
        // If we have a preselected offer that contains this gift, use its image and text
        var preselectedOffer = null;
        for (var i = 0; i < wideBundle.offers.length; i++) {
            if (wideBundle.offers[i][0].preselected == 1 && gift.offerPointers.includes(i.toString())) {
                preselectedOffer = i;
                break;
            }
        }
        
        if (preselectedOffer !== null) {
            // Find this gift in the preselected offer
            var offerGroup = wideBundle.offers[preselectedOffer];
            for (var j = 0; j < offerGroup.length; j++) {
                var offer = offerGroup[j];
                if (offer.product_id === gift.productId && offer.product_is_gift) {
                    imageSource = offer.gift_image || offer.image || imageSource;
                    giftText = offer.gift_text || giftText;
                    break;
                }
            }
        }
        
        // Create gift image if available
        if (imageSource && imageSource !== "") {
            var giftImage = document.createElement('img');
            giftImage.classList.add('wb-gift-card-image');
            giftImage.src = imageSource;
            giftImage.alt = wideBundle.getTranslatedText(giftText);
            imageWrapper.appendChild(giftImage);
        }
        
        // Add image wrapper to content
        giftContent.appendChild(imageWrapper);
        
        // Add content to card
        giftCard.appendChild(giftContent);
        
        // Create container for text that will be placed OUTSIDE the card
        var giftTextContainer = document.createElement('div');
        giftTextContainer.classList.add('wb-gift-text-container');

        // Add price display for gift product
        var priceElement = document.createElement('p');
        priceElement.classList.add('wb-gift-price-display');
        
        var variantId = gift.variants[0]?.id;
        if (variantId) {
            var price = document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantId}"]`)?.innerHTML || "";
            var compareAtPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantId}"]`)?.innerHTML || "";
            
            var priceToShow = compareAtPrice && compareAtPrice !== "" ? compareAtPrice : price;
            
            var priceHtml = `
                <span class='wb-gift-price-WB notranslate money conversion-bear-money transcy-money'>${wideBundle.replaceCurrencyForMarket ? wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator("0.00")))) : "FREE"}</span>
                <span class='wb-gift-compare-at-price-WB notranslate money transcy-money conversion-bear-money'><s class="crossed-price-WB">${wideBundle.replaceCurrencyForMarket ? wideBundle.replaceCurrencyForMarket(priceToShow) : priceToShow}</s></span>
            `;
            priceElement.innerHTML = priceHtml;
            giftTextContainer.appendChild(priceElement);
        }
        
        // Add gift text to the outside container
        var giftTextElement = document.createElement('p');
        giftTextElement.classList.add('wb-gift-card-text');
        giftTextElement.textContent = wideBundle.getTranslatedText(giftText);
        giftTextContainer.appendChild(giftTextElement);

        // Move variant selectors here, before the text
        if ((gift.option2Values && gift.option2Values.length > 1) || 
            (gift.option3Values && gift.option3Values.length > 1)) {
            // Create a container for variant selectors outside the card
            var variantSelectorsOutside = document.createElement('div');
            variantSelectorsOutside.classList.add('wb-gift-variant-selectors-outside');
            wideBundle.createGiftVariantSelectors(gift, variantSelectorsOutside, gift.offerPointers[0], gift.productPointer);
            giftTextContainer.appendChild(variantSelectorsOutside);
        }
        
        // Create a wrapper for both the card and its text
        var giftCardWrapper = document.createElement('div');
        giftCardWrapper.classList.add('wb-gift-card-wrapper');
        giftCardWrapper.appendChild(giftCard);
        giftCardWrapper.appendChild(giftTextContainer);
        
        // Add wrapper to container
        giftsCardsContainer.appendChild(giftCardWrapper);
    });
    
    // Add cards container to main container
    giftsContainer.appendChild(giftsCardsContainer);
    
    // Hide the corresponding gift wrappers in their parent offers based on placement
    document.querySelectorAll('.wb-gift-product-wrapper').forEach(function(wrapper) {
        // Get the offer pointer from the wrapper
        const offersPointer = wrapper.getAttribute('data-g-offers-pointer');
        if (offersPointer) {
            // Find the corresponding offer to check its gift_placement value
            const offer = wideBundle.offers[parseInt(offersPointer)][0];
            // Only hide the wrapper if the gift_placement is explicitly set to "under"
            if (offer && offer.gift_placement === "under") {
                wrapper.style.display = 'none';
            }
        }
    });
    
    // Return the container to be added to the widget
    return giftsContainer;
};


// First, let's modify the updateGiftsDisplay function to also update the unlock message text
wideBundle.updateGiftsDisplay = function(selectedOfferPointer) {
    var giftCards = document.querySelectorAll('.wb-gift-card');
    
    // Get the selected offer to retrieve its custom text
    var selectedOffer = wideBundle.offers[selectedOfferPointer][0];
    var textAboveGifts = "";
    
    // Check if the selected offer has custom text for gifts
    if (selectedOffer.gift_placement === "under" && selectedOffer.text_above_gifts) {
        textAboveGifts = selectedOffer.text_above_gifts;
    } else {
        // If the selected offer doesn't have "under" gifts or custom text,
        // find the first offer with "under" placement and text_above_gifts
        for (var i = 0; i < wideBundle.offers.length; i++) {
            var offerGroup = wideBundle.offers[i];
            for (var j = 0; j < offerGroup.length; j++) {
                var offer = offerGroup[j];
                if (offer.gift_placement === "under" && offer.text_above_gifts) {
                    textAboveGifts = offer.text_above_gifts;
                    break;
                }
            }
            if (textAboveGifts) break;
        }
    }
    
    // Update the unlock message text with the text from the first offer with "under" gifts
    // or the default message if no custom text is found
    var unlockMessage = document.querySelector('.wb-gifts-unlock-message');
    if (unlockMessage) {
        unlockMessage.innerHTML = wideBundle.getTranslatedText(textAboveGifts || '');
    }

    var selectedOfferGroup = wideBundle.offers[selectedOfferPointer];
    
    giftCards.forEach(function(card) {
        var cardOfferPointers = card.getAttribute('data-offer-pointers');
        if (cardOfferPointers) {
            // Convert the string to an array
            var offerPointers = cardOfferPointers.split(',');
            var productId = card.getAttribute('data-product-id');
            var cardWrapper = card.closest('.wb-gift-card-wrapper');
            
            // Check if the selected offer is in this gift's offers
            if (offerPointers.includes(selectedOfferPointer)) {
                // Check if this gift was previously locked
                var wasLocked = card.classList.contains('wb-gift-locked');
                
                // This gift is available in the selected offer
                card.classList.remove('wb-gift-locked');
                card.classList.add('wb-gift-available');

                if (cardWrapper) {
                    cardWrapper.classList.remove('wb-gift-card-wrapper-locked');
                }
                // Update the gift image, text and other attributes from the selected offer
                var giftInSelectedOffer = null;
                for (var j = 0; j < selectedOfferGroup.length; j++) {
                    if (selectedOfferGroup[j].product_id == productId && selectedOfferGroup[j].product_is_gift) {
                        giftInSelectedOffer = selectedOfferGroup[j];
                        break;
                    }
                }
                
                if (giftInSelectedOffer) {
                    // Update the image
                    var giftImage = card.querySelector('.wb-gift-card-image');
                    if (giftImage) {
                        giftImage.src = giftInSelectedOffer.gift_image || giftInSelectedOffer.image || "";
                        giftImage.alt = wideBundle.getTranslatedText(giftInSelectedOffer.gift_text || "Free Gift");
                    }
                    
                    // Update the text
                    var textContainer = card.nextElementSibling;
                    if (textContainer && textContainer.classList.contains('wb-gift-text-container')) {
                        var giftTextElement = textContainer.querySelector('.wb-gift-card-text');
                        if (giftTextElement) {
                            giftTextElement.textContent = wideBundle.getTranslatedText(giftInSelectedOffer.gift_text || "Free Gift");
                        }
                    }
                }
                
                // Show the content when unlocked
                var content = card.querySelector('.wb-gift-card-content');
                if (content) {
                    content.style.display = 'flex';
                }
                
                // Show the variant selectors for this gift
                var textContainer = card.nextElementSibling;
                if (textContainer && textContainer.classList.contains('wb-gift-text-container')) {
                    var variantSelectors = textContainer.querySelector('.wb-gift-variant-selectors-outside');
                    if (variantSelectors) {
                        variantSelectors.style.display = 'flex';
                    }
                    
                    // Show price for available gifts
                    var priceDisplay = textContainer.querySelector('.wb-gift-price-display');
                    if (priceDisplay) {
                        priceDisplay.style.opacity = '1';
                    }
                }
                
                // Remove lock icon if it exists
                var lockIcon = card.querySelector('.wb-gift-lock-container');
                if (lockIcon) {
                    lockIcon.remove();
                }
                
                // Update the background color according to selected offer's style
                var selectedOffer = document.querySelector('.selectedWB');
                if (selectedOffer) {
                    // Use the same background color as the selected offer
                    card.style.backgroundColor = wideBundle.settings.selected_free_gift_background_color || wideBundle.settings.background_color;
                    
                    // Update the plus icon to checkmark for available gifts
                    var plusIcon = card.querySelector('.wb-gift-plus-icon');
                    if (plusIcon) {
                        plusIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff" height="10" width="10" version="1.1" id="Capa_1" viewBox="0 0 128.411 128.411" xml:space="preserve"><g><g><polygon points="127.526,15.294 45.665,78.216 0.863,42.861 0,59.255 44.479,113.117 128.411,31.666"></polygon></g></g></svg>';
                    }
                }
                
                // If the gift was previously locked, just add a simple bounce animation
                if (wasLocked) {
                    // Add a simple bounce effect
                    card.classList.add('wb-gift-bounce');
                    setTimeout(function() {
                        card.classList.remove('wb-gift-bounce');
                    }, 500);
                }
                
                // Enable variant selectors for ALL options (including option4)
                var selectors = textContainer.querySelectorAll('select, input[type="radio"]');
                selectors.forEach(function(selector) {
                    selector.disabled = false;
                });
            } else {
                // This gift is not available in the selected offer
                card.classList.add('wb-gift-locked');
                card.classList.remove('wb-gift-available');

                // Also update the wrapper class
                if (cardWrapper) {
                    cardWrapper.classList.add('wb-gift-card-wrapper-locked');
                }
                
                // Hide the content when locked
                var content = card.querySelector('.wb-gift-card-content');
                if (content) {
                    content.style.display = 'none';
                }
                
                // Hide the variant selectors for this gift
                var textContainer = card.nextElementSibling;
                if (textContainer && textContainer.classList.contains('wb-gift-text-container')) {
                    var variantSelectors = textContainer.querySelector('.wb-gift-variant-selectors-outside');
                    if (variantSelectors) {
                        variantSelectors.style.display = 'none';
                    }
                    
                    // Fade out price for locked gifts
                    var priceDisplay = textContainer.querySelector('.wb-gift-price-display');
                    if (priceDisplay) {
                        priceDisplay.style.opacity = '1';
                    }
                }
                
                // Reset background color
                card.style.backgroundColor = wideBundle.settings.unselected_free_gift_background_color || "#d5d5d5";
                
                // Reset plus icon to X symbol for locked gifts
                var plusIcon = card.querySelector('.wb-gift-plus-icon');
                if (plusIcon) {
                    plusIcon.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 2L2 10" stroke="white" stroke-width="2" stroke-linecap="round"/><path d="M2 2L10 10" stroke="white" stroke-width="2" stroke-linecap="round"/></svg>';
                }
                
                // Disable ALL variant selectors (including option4)
                var selectors = textContainer.querySelectorAll('select, input[type="radio"]');
                selectors.forEach(function(selector) {
                    selector.disabled = true;
                });
                
                // Add gift icon if it doesn't exist
                if (!card.querySelector('.wb-gift-lock-container')) {
                    var lockContainer = document.createElement('div');
                    lockContainer.classList.add('wb-gift-lock-container');
                    
                    var giftIcon = document.createElement('div');
                    giftIcon.classList.add('wb-gift-lock-icon');
                    giftIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#888888" width="34" height="34" version="1.1" viewBox="0 0 512 512" xml:space="preserve"><g><g><rect x="272.696" y="280.342" width="183.118" height="231.658"/></g></g><g><g><rect x="56.186" y="280.342" width="183.118" height="231.658"/></g></g><g><g><path d="M398.762,94.432c4.953-9.075,7.772-19.474,7.772-30.521C406.535,28.67,377.864,0,342.624,0    c-26.065,0-52.735,13.468-73.168,36.951c-5.057,5.811-9.561,12.056-13.456,18.56c-3.895-6.504-8.399-12.749-13.456-18.56    C222.111,13.468,195.442,0,169.376,0c-35.24,0-63.911,28.671-63.911,63.911c0,11.046,2.818,21.446,7.772,30.521H26.2v152.519    h213.104V94.432h33.391v152.519H485.8V94.432H398.762z M169.376,94.432c-16.828,0-30.52-13.692-30.52-30.521    c0-16.829,13.692-30.52,30.52-30.52c30.299,0,59.106,30.993,67.489,61.04H169.376z M342.624,94.432h-67.489    c8.383-30.048,37.19-61.04,67.489-61.04c16.828,0,30.52,13.692,30.52,30.52C373.143,80.741,359.452,94.432,342.624,94.432z"/></g></g></svg>';
                    
                    lockContainer.appendChild(giftIcon);
                    
                    card.appendChild(lockContainer);
                }
            }
        }
    });
};

// Update the createWidgetContent function to use our new free gifts display
wideBundle.createWidgetContent = function (widgetContainer) {
    wideBundle.createHeading(widgetContainer); //Create the heading above the widget
    for(var i = 0; i<wideBundle.offers.length; i++){ //Create each offer in the widget
        var offer = wideBundle.offers[i][0];
        var offersPointer = i;
        offerContainer = wideBundle.createOfferContainer(widgetContainer, offer, offersPointer); //Create the container
        offerContentLeft = wideBundle.createOfferContentLeft(offerContainer, offer); //Create the content left
        offerContentRight = wideBundle.createOfferContentRight(offerContainer, offer, offersPointer); //Create the content right
        if (offer.user_text_enabled) {
            wideBundle.createOfferContentUserText(offerContainer, offer); //Create the content user text
        }

        //We need an additional div for all the elements if we have a gift offer for the flex wrap
        if (offerContainer.classList.contains('offer-free-gift') || offerContainer.classList.contains('offer-upsell-product')) {
            const flexContainer = document.createElement('div');
            flexContainer.classList.add('offer-with-gift-flex-wrapper');
            
            Array.from(offerContainer.children)
                .filter(child => !child.classList.contains('wb-gift-product-wrapper') && !child.classList.contains('wb-upsell-product-wrapper') && !child.classList.contains('wb-user-text-wrapper') && !child.classList.contains('wb-offer-timer'))
                .forEach(child => flexContainer.appendChild(child));
            
            offerContainer.prepend(flexContainer);
        }

        widgetContainer.appendChild(offerContainer);
    }
    
    // Add our free gifts display before the Add to Cart button only if we have gifts with "under" placement
    var giftsContainer = wideBundle.createFreeGiftsDisplay(widgetContainer);
    if (giftsContainer) {
        widgetContainer.appendChild(giftsContainer);
        
        // Find initially selected offer for gifts display initialization
        // Add a small delay to ensure offers are rendered and selected
        setTimeout(function() {
            var selectedElement = document.querySelector('.selectedWB');
            if (selectedElement) {
                var selectedOfferPointer = selectedElement.getAttribute('data-offers-pointer');
                wideBundle.updateGiftsDisplay(selectedOfferPointer);
            }
        }, 10);
    }
    
    wideBundle.addCodeBeforeOrAfterButton(widgetContainer, "before"); //Add html code before the button if the user added some
    wideBundle.createAddToCartButton(widgetContainer); //Create the add to cart button
    wideBundle.createTrustBadges(widgetContainer); //Create the add to cart button
    wideBundle.addCodeBeforeOrAfterButton(widgetContainer, "after"); //Add html code after the button if the user added some
    document.body.click();
    
    // Only create the dynamic group popup if there are offers with dynamic groups
    const hasDynamicGroups = wideBundle.offers.some(offerGroup => 
        offerGroup.some(offer => offer.dynamicGroupUuid !== null)
    );
    if (hasDynamicGroups) {
        ensureDynamicGroupPopup();
    }
}

//Add Trust badges image if the user added one
wideBundle.createTrustBadges = function(widgetContainer){
    if(wideBundle.settings.trustbadge != '' && wideBundle.settings.trustbadge != null){ //If they added an image url in the settings to show it below widebundle
        trustBadgeContainer = document.createElement('div');
        if(widgetContainer.hasAttribute('id')) {
            trustBadgeContainer.id = 'cont-trustbadge-wb';
        }
        trustBadgeContainer.classList.add('cont-trustbadge-wb');
        trustBadgeImg = document.createElement('img');
        trustBadgeImg.setAttribute('src', wideBundle.settings.trustbadge);
        trustBadgeContainer.appendChild(trustBadgeImg);
        widgetContainer.appendChild(trustBadgeContainer);
    }
}

//Create the add to cart button for WideBundle
wideBundle.createAddToCartButton = function(widgetContainer){
    var buttonAtc = document.createElement('div'); //Create the element
    var atcText = wideBundle.getTranslatedText(wideBundle.settings.atc_text);
    if(atcText && (atcText.includes('{{price}}') || atcText.includes('{{compare-price}}'))){
        var priceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.first-price-WB') : null;
        var comparePriceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.second-price-WB') : null;
        var price = priceEl ? priceEl.outerHTML : '';
        var comparePrice = comparePriceEl ? comparePriceEl.outerHTML : '';
        atcText = atcText.replace(/{{price}}/g, price);
        atcText = atcText.replace(/{{compare-price}}/g, comparePrice);
    }
    buttonAtc.innerHTML = AddSVG()+atcText;
    buttonAtc.setAttribute('data-add-to-cart', '');
    if(widgetContainer.hasAttribute('id')){ //Add an id if we're on the main widget
        buttonAtc.id = "new-form-atc";
    }
    buttonAtc.classList.add('new-form-atc', 'addCart');

    buttonAtc.addEventListener("click", wideBundle.addToCart); //Add the event listener to add the offer to the cart

    widgetContainer.appendChild(buttonAtc); //Add the button to the container

    wideBundle.copyAddToCartDesign(buttonAtc); //If the user enabled the feature to automatically copy the design of the add-to-cart button of the theme

    if(wideBundle.settings.atc_animation == 'shaking'){ //If they added the settings to make the add to cart button shake
        var headWB = document.getElementsByTagName('head')[0],
        styleWB = document.createElement('style'),
        animName = 'shakeWB',
        rulesWB = document.createTextNode('@-webkit-keyframes ' + animName + '{ 0% { transform:translate(0,0);-webkit-transform:translate(0,0) } 2% { transform:translate(5px,0) scale(1.05);-webkit-transform:translate(5px,0) scale(1.05)} 4% { transform:translate(0,0) scale(1.1);-webkit-transform:translate(0,0) scale(1.1) } 6% { transform:translate(5px,0) scale(1.05);-webkit-transform:translate(5px,0) scale(1.05) } 8% { transform:translate(0,0) scale(1);-webkit-transform:translate(0,0)  scale(1)} 10% { transform:translate(5px,0);-webkit-transform:translate(5px,0) } 12% { transform:translate(0,0);-webkit-transform:translate(0,0) } 100% { transform:translate(0,0);-webkit-transform:translate(0,0) } } #new-form-atc{ -webkit-animation: '+animName+' 4s ease infinite; }');
        styleWB.type = 'text/css';
        if(styleWB.styleSheet)
            styleWB.styleSheet.cssText = rulesWB.nodeValue;
        else styleWB.appendChild(rulesWB);
        headWB.appendChild(styleWB);
        window.addEventListener('load', animateButton, false);
        function animateButton(){
          if(document.querySelector('#new-form-atc') != null){
            document.querySelector('#new-form-atc').style.webkitAnimationName = animName;
          }
          for(var i=0; i<document.querySelectorAll('.new-form-atc').length; i++){
            document.querySelectorAll('.new-form-atc')[i].style.webkitAnimationName = animName;
          }
        }
      }
}

wideBundle.copyAddToCartDesign = function(buttonAtc){
    let addToCartButtonOfTheme = wideBundle.getAddToCartButton();
    if(addToCartButtonOfTheme){
        //copyStyle(addToCartButtonOfTheme.element, buttonAtc);
    }
}

//Add HTML code before the Add to Cart button
wideBundle.addCodeBeforeOrAfterButton = function(widgetContainer, position = "before"){
    position == "before" ? content = wideBundle.settings.before_code : content = wideBundle.settings.after_code;

    if(content != ''){ //Add html code before or after button if the user added some
        CodeContainer = document.createElement('div');
        CodeContainer.innerHTML = content;
        CodeContainer.classList.add(`${position}-code-wb`);
        widgetContainer.appendChild(CodeContainer);
    }
}

wideBundle.addHiddenPrices = function(){
    var divHiddenPrices = document.createElement("div");
    divHiddenPrices.classList.add("wb_hidden_prices");
    divHiddenPrices.style.display = "none";
    
    var htmlContent = "";
    // Keep track of variants we've already added
    var processedVariants = new Set();

    for (var i = 0; i < wideBundle.offers.length; i++) {
        var offerGroup = wideBundle.offers[i];
        htmlContent += wideBundle.addOfferHiddenPrices(offerGroup[0], processedVariants);

        if (offerGroup[0].automatic_discount) {
            let discountValueConverted = Number(offerGroup[0].discount_value);
            if (offerGroup[0].discount_type !== "percent") {
                discountValueConverted = discountValueConverted * parseFloat(Shopify.currency.rate);
            }
            htmlContent += `
                <p class="wb_hidden_prices_element" data-discount-type>
                    <span class="wb_hidden_price notranslate money conversion-bear-money  transcy-money" offer-idx="${i}" offer-discount="${offerGroup[0].discount_type}">${wideBundle.removeDecimal(wideBundle.updatePriceSeparator(discountValueConverted.toString()))}</span>
                </p>
            `;

            const variantIdsSelected = offerGroup.filter((offer) => !offer.product_is_upsell).reduce((ids, offer) => {
                const variantId = offer.variants[0].id;
                return [...ids, ...(new Array(offer.product_qty).fill(variantId))];
            }, []);
            const variantPrices = offerGroup.filter((offer) => !offer.product_is_upsell).reduce((prices, offer) => {
                let variantPrice = 0;
                variantPrice = Number(wideBundle.getAmountFromPrice(offer.variants[0].price));
                if (offer.product_is_gift) variantPrice = 0;
                if (offer.product_is_upsell) variantPrice = 0;
                if (offer.dynamicGroupUuid !== null && offer.dynamicGroupSelected === null) variantPrice = 0;
                return [...prices, ...(new Array(offer.product_qty).fill(variantPrice))];
            }, []);
            const variantCompareAtPrices = offerGroup.filter((offer) => !offer.product_is_upsell).reduce((prices, offer) => {
                let variantCompareAtPrice = 0;
                if (offer.variants[0].compare_at_price && offer.variants[0].compare_at_price !== "") {
                    variantCompareAtPrice = Number(wideBundle.getAmountFromPrice(offer.variants[0].compare_at_price));
                    if (variantCompareAtPrice === 0) {
                        variantCompareAtPrice = Number(wideBundle.getAmountFromPrice(offer.variants[0].price));
                    }
                } else {
                    variantCompareAtPrice = Number(wideBundle.getAmountFromPrice(offer.variants[0].price));
                }
                return [...prices, ...(new Array(offer.product_qty).fill(variantCompareAtPrice))];
            }, []);
            htmlContent += wideBundle.addOfferCalculatedPrices(offerGroup[0], variantIdsSelected, variantPrices, variantCompareAtPrices);
        }

        if (offerGroup[1] && offerGroup[1].automatic_discount) {
            for (var o = 1; o < offerGroup.length; o++) {
                htmlContent += wideBundle.addOfferHiddenPrices(offerGroup[o], processedVariants);
            }
        }
    }

    divHiddenPrices.innerHTML = htmlContent;
    wideBundle.widgetContainers[0].appendChild(divHiddenPrices); //Add hidden prices to first container

    // Store the divHiddenPrices element for later use
    wideBundle.hiddenPricesDiv = divHiddenPrices;
}

wideBundle.addOfferHiddenPrices = function(offer, processedVariants){
    var htmlContent = "";

    var variants = offer.variants;
    for (var j = 0; j < variants.length; j++) {
        var variant = variants[j];
        if (!processedVariants.has(variant.id)) {
            variant.compare_at_price = parseFloat(wideBundle.getAmountFromPrice(variant.price)) >= parseFloat(wideBundle.getAmountFromPrice(variant.compare_at_price)) ? "" : variant.compare_at_price;

            htmlContent += `
                <p class="wb_hidden_prices_element">
                    <span class="wb_hidden_price notranslate money conversion-bear-money  transcy-money" variant-id="${variant.id}" product-id="${offer.product_id}">${wideBundle.removeDecimal(wideBundle.updatePriceSeparator(variant.price))}</span>
                    <span class="wb_hidden_compared_price notranslate money conversion-bear-money transcy-money" variant-id="${variant.id}" product-id="${offer.product_id}">${wideBundle.removeDecimal(wideBundle.updatePriceSeparator(variant.compare_at_price))}</span>
                </p>
            `;
            processedVariants.add(variant.id);
        }
    }
    return htmlContent;
}

wideBundle.addOfferCalculatedPrices = function(offerSelected, variantIdsSelected, variantPrices, variantCompareAtPrices){
    const offerValuePrice = Number(offerSelected.discount_value);
    const variantsString = offerSelected.offersPointer + "@" + variantIdsSelected.join("+");
    let totalPrice = variantPrices.reduce((sum, price) => sum + price, 0);
    let totalCompareAtPrice = variantCompareAtPrices.reduce((sum, comparePrice, index) => {
        // Use compare price only if it exists AND is higher than regular price
        if (comparePrice && comparePrice > variantPrices[index]) {
            return sum + comparePrice;
        }
        // Otherwise use regular price
        return sum + variantPrices[index];
    }, 0);
    let discountedPrice = 0;

    switch (offerSelected.discount_type) {
        case "amount":
        case "value":
            discountedPrice = Math.max(0, totalPrice - offerValuePrice * parseFloat(Shopify.currency.rate));
            break;
        case "percent":
            discountedPrice = Math.max(0, totalPrice - ((totalPrice / 100) * offerValuePrice));
            break;
        case "fixed":
            if (offerValuePrice === 0) {
                discountedPrice = totalPrice;
            } else {
                discountedPrice = offerValuePrice * parseFloat(Shopify.currency.rate);
            }
            break;
        case "gift":
            discountedPrice = totalPrice - variantPrices[variantPrices.length - 1];
            break;
    }

    discountedPrice = discountedPrice.toFixed(2);
    totalCompareAtPrice = totalCompareAtPrice.toFixed(2);
    totalPrice = totalPrice.toFixed(2);

    const roundPrices = wideBundle.settings.round_prices_automatic == 1 && parseFloat(window?.Shopify?.currency?.rate) !== 1.0 && offerSelected.discount_type !== "gift";
    if (roundPrices && !Number.isInteger(parseFloat(discountedPrice))) {
        if (Math.ceil(discountedPrice) <= parseFloat(totalPrice)) {
            discountedPrice = Math.ceil(discountedPrice).toFixed(2);
        }
    }

    let compareAtPriceToShow = "";
    if (totalCompareAtPrice > 0 && parseFloat(wideBundle.getAmountFromPrice(totalCompareAtPrice)) > parseFloat(wideBundle.getAmountFromPrice(totalPrice))) {
        if (parseFloat(wideBundle.getAmountFromPrice(discountedPrice)) >= parseFloat(wideBundle.getAmountFromPrice(totalCompareAtPrice))) {
            compareAtPriceToShow = "";
        }
        else{
            compareAtPriceToShow = totalCompareAtPrice;
        }
    } else {
        compareAtPriceToShow = parseFloat(wideBundle.getAmountFromPrice(discountedPrice)) >= parseFloat(wideBundle.getAmountFromPrice(totalPrice)) ? "" : totalPrice;
    }

    return `
        <p class="wb_hidden_prices_element" data-calculated>
            <span class="wb_hidden_price notranslate money conversion-bear-money  transcy-money" variant-id="${variantsString}" product-id="null">${wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(discountedPrice))))}</span>
            <span class="wb_hidden_compared_price notranslate money conversion-bear-money transcy-money" variant-id="${variantsString}" product-id="null">${wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(compareAtPriceToShow))))}</span>
        </p>
    `;
}


//Create the heading above the widget
wideBundle.createHeading = function(widgetContainer){
    var heading = document.createElement('p');
    heading.classList.add('p-title-WB');
    //find the translated text and use it in the HTML
    let translatedHeading = wideBundle.getTranslatedText(wideBundle.heading);
    if(widgetContainer.hasAttribute('id')) {
        heading.innerHTML = "<span id='title-offer-WB' class='p-title-WB__content'>"+translatedHeading+"</span>";
    } else {
        heading.innerHTML = "<span class='p-title-WB__content'>"+translatedHeading+"</span>";
    }

    if(wideBundle.settings.design_code == 4){
        heading.innerHTML += "<span class='p-title-WB__arrow'></span>";
    }
    
    widgetContainer.appendChild(heading);
}

//Create the offer container
wideBundle.createOfferContainer = function (widgetContainer, offer, offersPointer) {
    var offerContainer = document.createElement('div');
    if(widgetContainer.hasAttribute('id')){
        offerContainer.id = "id" + offer.variants[0].id + '-' + offersPointer
    }
    offerContainer.classList.add('selectable'); //Add the class for unselected offers
    offerContainer.classList.add('new-form-option');
    if(offer.automatic_discount){
        offerContainer.classList.add(`offer-discount-system`);
    }
    offerContainer.setAttribute('data-id', offer.variants[0].id + '-' + offersPointer);
    offerContainer.setAttribute('data-variant-id', offer.variants[0].id);
    offerContainer.setAttribute('data-offers-pointer', offersPointer);
    offerContainer.setAttribute('data-offer-auto', offer.automatic_discount);
    offerContainer.addEventListener("click", wideBundle.changeSelectedOffer); //Add the click event to detect when we select the offer

    wideBundle.createOfferTimer(offerContainer, offer);
    
    return offerContainer;
}

// Create countdown timer on offer (top area)
wideBundle.createOfferTimer = function (offerContainer, offer) {
    if(
        !offer ||
        !offer.timer_type ||
        !offer.timer_text_color ||
        !offer.timer_text_size ||
        !offer.timer_text_style ||
        !offer.timer_background_color
    ){
        console.log('[US-TIMER] createOfferTimer: missing required style fields, skipping');
        return;
    }

    const isMidnight = offer.timer_type === "daily_midnight";
    const isRecurring = offer.timer_type === "recurring";

    // For midnight mode, we don't need timer_end_date
    if (!isMidnight && !offer.timer_end_date) {
        console.log('[US-TIMER] createOfferTimer: no timer_end_date for non-midnight mode, skipping');
        return;
    }

    let endMs;
    if (isMidnight) {
        // Calculate milliseconds until next midnight in visitor's local timezone
        endMs = new Date().setHours(24, 0, 0, 0);
        //console.log('[US-TIMER] midnight mode: end set to next midnight', new Date(endMs).toString());
    } else {
        endMs = Number(offer.timer_end_date);
        if (!endMs || !Number.isFinite(endMs)) return;
    }

    const stepMs = isRecurring && Number(offer.timer_duration) > 0
        ? Number(offer.timer_duration) * 60 * 1000
        : 0;
    
    // Avoid duplicate intervals if regenerated
    if(offerContainer._wbTimerInterval){
        clearInterval(offerContainer._wbTimerInterval);
        offerContainer._wbTimerInterval = null;
    }
    offerContainer.style.position = "relative";
    // offerContainer.style.overflow = "hidden"
    const timerWrap = document.createElement("div");
    timerWrap.classList.add("wb-offer-timer");

    // Styles from offer fields
    timerWrap.style.backgroundColor = offer.timer_background_color;
    timerWrap.style.position = 'absolute';
    timerWrap.style.padding = '4px';
    timerWrap.style.display = 'flex';
    timerWrap.style.justifyContent = 'center';
    timerWrap.style.top = 0;
    timerWrap.style.left = 0;
    timerWrap.style.width = '100%';

    const timerText = document.createElement("div");
    timerText.classList.add("wb-offer-timer__text");

    // text styles
    timerText.style.color = offer.timer_text_color;
    timerText.style.fontSize = String(offer.timer_text_size);


    if (offer.timer_text_style === 'bold') {
        timerText.style.fontWeight = "600";
    } else if (offer.timer_text_style === 'italic') {
        timerText.style.fontStyle = "italic";
        timerText.style.fontWeight = "400";
    } else if (offer.timer_text_style === 'bold-italic') {
        timerText.style.fontStyle = "italic";
        timerText.style.fontWeight = "600";
    } else {
         timerText.style.fontWeight = "400";
    }

    timerWrap.appendChild(timerText);

    // Put timer at the very top of offer container
    offerContainer.insertBefore(timerWrap, offerContainer.firstChild);

    function pad2(n){
        return String(n).padStart(2, "0");
    }

    function formatLeft(msLeft){
        if(msLeft < 0) msLeft = 0;

        const totalSec = Math.floor(msLeft / 1000);

        const days = Math.floor(totalSec / 86400);
        const hours = Math.floor((totalSec % 86400) / 3600);
        const mins = Math.floor((totalSec % 3600) / 60);
        const secs = totalSec % 60;

        // < 1 hour => MM:SS (minutes can be > 59? no, because < 1h)
        if(totalSec < 3600){
            return pad2(mins) + ":" + pad2(secs);
        }

        // < 24 hours => HH:MM:SS
        if(totalSec < 86400){
            return pad2(hours) + ":" + pad2(mins) + ":" + pad2(secs);
        }

        // >= 24 hours => DD:HH:MM:SS (days can be 3, 12, 120...)
        return String(days) + ":" + pad2(hours) + ":" + pad2(mins) + ":" + pad2(secs);
    }

    function buildTimerText(template, timeStr){
        const t = (template == null ? "" : String(template)).trim();
        if(!t) return timeStr;

        // replace {{time}} with optional spaces: {{ time }}
        if(/{{\s*time\s*}}/i.test(t)){
            return t.replace(/{{\s*time\s*}}/gi, timeStr);
        }

        // if no placeholder, append time
        return t + " " + timeStr;
    }

    function tick(){
        const now = Date.now();

        if (isMidnight && now >= endMs) {
            // Recalculate next midnight
            endMs = new Date().setHours(24, 0, 0, 0);
            console.log('[US-TIMER] midnight reset: new end', new Date(endMs).toString());
        }

        if (isRecurring && stepMs > 0) {
            if (now >= endMs) {
                const diff = now - endMs;
                const steps = Math.floor(diff / stepMs) + 1;
                endMs = endMs + steps * stepMs;
            }
        }

        const left = endMs - now;

        const timeStr = formatLeft(left);
        const text = buildTimerText(offer.timer_text, timeStr);
        const offerCornerSentence = offerContainer.querySelector(".corner-offer");

        timerText.innerHTML = wideBundle.getTranslatedText ? wideBundle.getTranslatedText(text) : text;

        // --- fixed date type (not recurring, not midnight)
        if (!isRecurring && !isMidnight && left <= 0) {
            if (offerContainer._wbTimerInterval) {
                clearInterval(offerContainer._wbTimerInterval);
                offerContainer._wbTimerInterval = null;
            }
            timerWrap.style.display = "none";
             offerContainer.style.setProperty("padding-top",  "10px", "important")
            return;
        }

        requestAnimationFrame(function(){
            const h = timerWrap.offsetHeight;
            offerContainer.style.setProperty("padding-top", (h + 10) + "px", "important");
            if (wideBundle.settings.design_code != 1 && wideBundle.settings.design_code != 5) {
                offerCornerSentence && offerCornerSentence.style.setProperty("top", (-17 - h - 10) + "px", "important");
            }
        });
    }

    setTimeout(() => {
        tick();
    }, 1);

    offerContainer._wbTimerInterval = setInterval(tick, 1000);
};

//Create the content on the left of the offer
wideBundle.createOfferContentLeft = function(offerContainer, offer){
    var contentLeft = document.createElement('div');
    contentLeft.classList.add('value-left');

    var roundCheckbox = document.createElement('span'); //Create the circle checkbox
    roundCheckbox.classList.add('checkedWB');
    contentLeft.append(roundCheckbox);

    if(offer.image != '' && offer.image != null){ //Add thumbnail if it exists
        var thumbnail = document.createElement('img');
        thumbnail.classList.add('thumbnailWB');
        contentLeft.classList.add('offer-image');
        thumbnail.setAttribute('src', offer.image);
        thumbnail.setAttribute('alt', "");
        contentLeft.append(thumbnail);
    }

    offerContainer.appendChild(contentLeft);
}

//Create the contnet on the right of the offer
wideBundle.createOfferContentRight = function(offerContainer, offer, offersPointer){
    var contentRight = document.createElement('div');
    contentRight.classList.add('value-right');
    offerContainer.appendChild(contentRight);

    titleOffer = document.createElement('p'); //Create the title of the offer
    titleOffer.classList.add('title-variant');
    titleOffer.innerHTML = wideBundle.getTranslatedText(offer.offer_title);

    var priceElement = document.createElement('p'); //Create the price of the offer;
    priceElement.classList.add('price-new-form');

    let variantId;
    if (offer.automatic_discount) {
        const offerDb = wideBundle.offers[offersPointer];
        variantId = offersPointer + "@" + (offerDb.filter((offer) => !offer.product_is_upsell).reduce((ids, offer) => {
            const variantId = offer.variants[0].id;
            return [...ids, ...(new Array(offer.product_qty).fill(variantId))];
        }, []).join("+"));
    } else {
    variantId = offer.variants[0].id; //We create the prices of the offer
    }
    var price = document.querySelector(`.wb_hidden_prices ${offer.automatic_discount ? '.wb_hidden_prices_element[data-calculated] ' : ' '}.wb_hidden_price[variant-id="${variantId}"]`)?.innerHTML ?? "";
    var compareAtPrice = document.querySelector(`.wb_hidden_prices ${offer.automatic_discount ? '.wb_hidden_prices_element[data-calculated] ' : ' '}.wb_hidden_compared_price[variant-id="${variantId}"]`)?.innerHTML ?? "";
    var priceHtml = `
        <span class='first-price-WB notranslate money conversion-bear-money transcy-money'>${price}</span>
        <span class='second-price-WB notranslate ${compareAtPrice != "" ? "money transcy-money" : ""} conversion-bear-money'><s class="crossed-price-WB">${compareAtPrice}</s></span>
    `;
    priceElement.innerHTML = priceHtml;


    

    if(offer.unit == 1 && wideBundle.settings.plan !== "monthly") {
        var crMarkets = offer.variants[0].conversion_rate
        var crOffer = offer.unit_price / offer.price_in_offer ;
        var unit_price_markets = offer.unit_price / crMarkets;
        
        var unitElement = document.createElement('p'); //Create the price of the offer;
        unitElement.classList.add('first-unit-WB');

        var unitHtml = `
        <span class='wb_unit_price'>${ wideBundle.removeDecimal(wideBundle.updatePriceSeparator(wideBundle.formatPriceForUnit(unit_price_markets)))}</span>
        <span class='wb_unit_text'>${offer.unit_text}</span>
        `;

        priceElement.setAttribute("data_offer_cr", crOffer);

        unitElement.innerHTML = wideBundle.getTranslatedText(unitHtml);
        priceElement.classList.add('hidden-unit');
    }

    wideBundle.createQuantityWidget(offerContainer); //We create the quantity widget if they enabled it in the settings

    if(isJsonString(offer.message) && offer.message !== null){
        messageText = JSON.parse(offer.message);
    }
    else{
        messageText = offer.message ? [offer.message] : [""];
    }

    messageEffect = offer.message_effect ? offer.message_effect.split(",") : [""]; //Get message effect
    messagePosition = offer.message_position ? offer.message_position.split(",") : [""]; //Get message position
    
    messagesToDisplay = wideBundle.settings.plan == 'monthly' ? 1 : messageText.length;

    for(var i = 0; i<messagesToDisplay; i++){//For each custom message
        if((messagePosition[i] == 0 && messageEffect[i] < 2) || (messagePosition[i] > 1 && messagePosition[i] < 4 && wideBundle.settings.plan == 'monthly')){ //Add the message before title if it exists
            wideBundle.createCustomSentence(messageText[i], messageEffect[i], contentRight);
        }
    }

    contentRight.appendChild(titleOffer); //Add the title of the offer
    contentRight.appendChild(priceElement); //Add the price of the offer
    if(offer.unit == 1 && wideBundle.settings.plan !== "monthly") {
        contentRight.appendChild(unitElement); //Add the price of the offer
    }

    for(var i = 0; i<messagesToDisplay; i++){//For each custom message
        if(messagePosition[i] == 1){ //Add the message after title if it exists
            wideBundle.createCustomSentence(messageText[i], messageEffect[i], contentRight);
        }
        
        if(wideBundle.settings.plan !== 'monthly'){
            if(messageText[i]){
                if(messagePosition[i] == 2){ 
                    var ribbon = document.createElement('div');
                    ribbon.classList.add('corner-offer');
                    ribbon.innerHTML = wideBundle.getTranslatedText(messageText[i]);

                    offerContainer.appendChild(ribbon);
                    offerContainer.classList.add('corner-offer-container')
                }
                else if(messagePosition[i] == 3){ 
                    offerContainer.classList.add('diagonal-offer');
                    offerContainer.style.setProperty('--message', `'${messageText[i]}'`);
                }
            }
        }


        if(messagePosition[i] == 4){
            titleOffer.classList.add('title-variant--with-custom');
            wideBundle.createCustomSentence(messageText[i], messageEffect[i], contentRight, titleOffer, messagePosition[i]);
        }
    }

    wideBundle.createSavingText(offer, contentRight, offerContainer); //Display the saving text if it's enabled
    wideBundle.createOptionSelectors(offer, contentRight, offersPointer, offerContainer); //Create the option selectors if they have some
}

wideBundle.createOfferContentUserText = function(offerContainer, offer) {
    const contentUserText = document.createElement('div');
    contentUserText.classList.add('wb-user-text-wrapper');

    const labelUserText = document.createElement('label');
    labelUserText.classList.add('label-user-text');
    labelUserText.setAttribute('for', `wb-user-text-${offer.variants[0].id}-${offerContainer.getAttribute('data-offers-pointer')}`);
    labelUserText.innerHTML = wideBundle.getTranslatedText(offer.user_text_label);
    labelUserText.style.color = offer.user_text_color || '#000000';
    labelUserText.style.fontSize = offer.user_text_size || '1em';
    if (offer.user_text_style === 'bold') {
        labelUserText.style.fontWeight = 'bold';
        labelUserText.style.fontStyle = 'normal';
    } else if (offer.user_text_style === 'italic') {
        labelUserText.style.fontWeight = 'normal';
        labelUserText.style.fontStyle = 'italic';
    } else if (offer.user_text_style === 'bold-italic') {
        labelUserText.style.fontWeight = 'bold';
        labelUserText.style.fontStyle = 'italic';
    } else {
        labelUserText.style.fontWeight = 'normal';
        labelUserText.style.fontStyle = 'normal';
    }
    contentUserText.appendChild(labelUserText);

    const inputUserText = document.createElement('input');
    const inputUserTextName = `wb-user-text-${offer.variants[0].id}-${offerContainer.getAttribute('data-offers-pointer')}`;
    inputUserText.classList.add('input-user-text');
    inputUserText.setAttribute('type', 'text');
    inputUserText.setAttribute('id', inputUserTextName);
    inputUserText.setAttribute('name', inputUserTextName);
    inputUserText.required = offer.user_text_required;
    if (wideBundle?.userTexts?.[inputUserTextName]?.trim()?.length > 0) {
        inputUserText.value = wideBundle.userTexts[inputUserTextName];
    }
    inputUserText.addEventListener("input", (event) => {
        wideBundle.userTexts[event.target.name] = event.target.value;
        wideBundle.updateFormHiddenIds();
    });
    contentUserText.appendChild(inputUserText);

    const errorUserText = document.createElement('span');
    errorUserText.classList.add('error-user-text');
    errorUserText.textContent = wideBundle.getTranslatedText('This field is required');
    contentUserText.appendChild(errorUserText);

    offerContainer.classList.add(`offer-free-gift`);
    const valueRight = offerContainer.querySelector('.value-right');
    if (valueRight) {
        valueRight.appendChild(contentUserText);
    } else {
        offerContainer.appendChild(contentUserText);
    }
}

wideBundle.fromGraphqlId = function (gid) {
    const shopifyGidRegexp = new RegExp(/gid:\/\/shopify\/\w+\/(\d+)/);
    return Number(shopifyGidRegexp.exec(gid)?.[1] ?? "0");
}

wideBundle.toGraphqlId = function (resource = "Product", id) {
    return `gid://shopify/${resource}/${id}`;
}

wideBundle.makeStorefrontApiRequest = async function (query, queryVariables = {}) {
    try {
        const countryCode = window?.Shopify?.country ?? null;
        const variables = { country: countryCode, ...queryVariables };
        const response = await fetch((window?.Shopify?.routes?.root ?? "/") + "api/2026-01/graphql.json", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-Shopify-Storefront-Access-Token": wideBundle?.settings?.storefront_token ?? "",
            },
            body: JSON.stringify({ query, variables }),
        });
        const data = await response.json();
        if (data?.errors?.length > 0) {
            console.error("[Widebundle] Failed storefront api request", { errors: data.errors, query, variables });
            return null;
        }

        return data.data;
    } catch (error) {
        console.error("[Widebundle] Failed storefront api request", { errors: [error], query, variables });
        return null;
    }
}

function formatQuotes(text) {
    return text.split('"').join('&quot;').split("'").join('&#39;');
}

//Create options selectors if the product has 1 or 2 options (color and size for example)
wideBundle.createOptionSelectors = function(offer, contentRight, offersPointer, offerContainer){
    optionsLabels = offer.options_labels ? offer.options_labels.split(",") : [""]; //Get option labels
    swatchId = Math.floor(Math.random()*898)+101;
    if (offer.automatic_discount && wideBundle.offers[offersPointer].length > 1){ //Add the title of the product and the options name for automatic discount only
        productTitle = offer.product_title;
        optionsName = [2, 3, 4].map(i => offer[`option${i}_values`]?.length > 1 ? offer[`option${i}_title`] : null).filter(title => title && title.trim()).join(', '); //For 3 options, if there is only 1 value in the array, we don't show option title
        optionsName = optionsName ? `(${wideBundle.getTranslatedText(optionsName)})` : '';
        if(optionsName && !offer.product_is_gift){
            let labelDropdowns = document.createElement('p');
            labelDropdowns.classList.add("general_option_label_wb");
            if (offer.dynamicGroupSelected !== null) {
                labelDropdowns.innerHTML = /* html */ `
                    <img width="38" height="38" src="${offer.dynamicGroupSelectedImage ?? ""}">
                    ${wbHtmlentities(wideBundle.getTranslatedText(productTitle))} ${wbHtmlentities(optionsName)}
                `;
            } else {
                labelDropdowns.textContent = `${wideBundle.getTranslatedText(productTitle)} ${optionsName}`;
                
            }
            contentRight.appendChild(labelDropdowns);
        }
    }
    else if(offer.automatic_discount){
        optionsName = [2, 3, 4].map(i => offer[`option${i}_values`]?.length > 1 ? offer[`option${i}_title`] : null).filter(title => title && title.trim()).join(', '); //For 3 options, if there is only 1 value in the array, we don't show option title
        if(optionsName && !offer.product_is_gift){
            let labelDropdowns = document.createElement('p');
            labelDropdowns.classList.add("general_option_label_wb");
            if (offer.dynamicGroupSelected !== null) {
                labelDropdowns.innerHTML = /* html */ `
                    <img width="38" height="38" src="${offer.dynamicGroupSelectedImage ?? ""}">
                    ${wbHtmlentities(wideBundle.getTranslatedText(optionsName))}
                `;
            } else {
                labelDropdowns.textContent = `${wideBundle.getTranslatedText(optionsName)}`;
                
            }
            labelDropdowns.textContent = `${wideBundle.getTranslatedText(optionsName)}`;
            contentRight.appendChild(labelDropdowns);
        }
    }
    for(var i = 0; i<offer.dropdowns_amount; i++){ //For each selector row
        let j = i+1;
        defaultSelect(offer, contentRight, i, j, optionsLabels, offersPointer, 0, swatchId, offerContainer);
    }

    if (offer.automatic_discount && wideBundle.offers[offersPointer].length > 1) {
        let j = 2;
        wideBundle.offers[offersPointer].slice(1).forEach((additionalOffer, productPointer) => {
            const dynamicGroupButton = document.createElement("button");
            if (additionalOffer.dynamicGroupUuid !== null) {
                const dynamicGroup = additionalOffer.dynamicGroups.find(dg => dg.uuid === additionalOffer.dynamicGroupUuid);
                dynamicGroupButton.type = "button";
                dynamicGroupButton.style.cursor = "pointer";
                dynamicGroupButton.classList.add("js-wb-dynamic-group");
                dynamicGroupButton.dataset.uuid = dynamicGroup.uuid;
                dynamicGroupButton.innerHTML = /* html */ `
                    ${additionalOffer.dynamicGroupSelected === null
                        ? `<div class="js-wb-dynamic-group__thumb">?</div>
                            <div class="js-wb-dynamic-group__choose">${wbHtmlentities(wideBundle.settings.dg_choose_btn_text)}</div>`
                        : `<div class="js-wb-dynamic-group__close">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M18 6 6 18"/>
                                    <path d="m6 6 12 12"/>
                                </svg>
                            </div>`}
                `;

                if (!window?.Shopify?.previewMock) {
                    const selected = additionalOffer.dynamicGroupSelected !== null;
                    dynamicGroupButton.addEventListener("click", (event) => {
                        if (event.target.closest(".js-wb-dynamic-group__close") !== null) {
                            closeDynamicGroupPopup(dynamicGroup.uuid, null);
                        } else {
                            openDynamicGroupPopup(dynamicGroup, selected);
                        }
                    });
                } else {
                    dynamicGroupButton.disabled = true;
                }

                if (additionalOffer.dynamicGroupSelected === null) {
                    contentRight.appendChild(dynamicGroupButton);
                }
            }
            productTitle = additionalOffer.product_title;
            if (additionalOffer.dynamicGroupSelected !== null) {
                optionsName = [2, 3, 4].map(i => additionalOffer[`option${i}_values`]?.length > 1 ? additionalOffer[`option${i}_title`] : null).filter(title => title && title.trim()).join(', ');
            } else {
                optionsName = [2, 3, 4].map(i => additionalOffer[`option${i}_values`]?.length > 1 ? additionalOffer[`option${i}_title`] : null).filter(title => title && title.trim()).join(', '); //For 3 options, if there is only 1 value in the array, we don't show option title
            }
            optionsName = optionsName ? `(${wideBundle.getTranslatedText(optionsName)})` : '';
            if((optionsName || additionalOffer.dynamicGroupSelected !== null) && !additionalOffer.product_is_gift && !additionalOffer.product_is_upsell){
                let labelDropdowns = document.createElement('p');
                labelDropdowns.classList.add("general_option_label_wb");
                if (additionalOffer.dynamicGroupSelected !== null) {
                    labelDropdowns.innerHTML = /* html */ `
                        <img width="38" height="38" src="${additionalOffer.dynamicGroupSelectedImage ?? ""}">
                        ${wbHtmlentities(wideBundle.getTranslatedText(productTitle))} ${wbHtmlentities(optionsName)}
                    `;
                } else {
                    labelDropdowns.textContent = `${wbHtmlentities(wideBundle.getTranslatedText(productTitle))} ${wbHtmlentities(optionsName)}`;
                    
                }

                if (additionalOffer.dynamicGroupSelected === null) {
                    contentRight.appendChild(labelDropdowns);
                } else if (additionalOffer.dynamicGroupUuid !== null) {
                    const labelsWrapper = document.createElement("div");
                    labelsWrapper.classList.add("general_option_label_wb_wrapper");
                    dynamicGroupButton.classList.add("js-wb-dynamic-group--slim");
                    labelsWrapper.appendChild(dynamicGroupButton);
                    labelsWrapper.appendChild(labelDropdowns);
                    contentRight.appendChild(labelsWrapper);
                }
            }
            optionsLabels = additionalOffer.options_labels ? additionalOffer.options_labels.split(",") : [""]; //Get option labels
            for(var i = 0; i<additionalOffer.dropdowns_amount; i++){ //For each selector row
                defaultSelect(additionalOffer, contentRight, i, j, optionsLabels, offersPointer, productPointer + 1, swatchId, offerContainer);
                j++;
            }
        });
    }
}

wideBundle.updateDynamicGroupProduct = function(uuid, productData) {
    const offersPointer = wideBundle.getSelectedOffer().offersPointer;
    const dynamicProductIndex = wideBundle.offers[offersPointer].findIndex((offer) => offer.dynamicGroupUuid === uuid);
    const dynamicProductOffer = wideBundle.offers[offersPointer][dynamicProductIndex];
    let newOffer;
    if (productData !== null) {
        newOffer = {
            ...dynamicProductOffer,
            all_products: false,
            dynamicGroupSelected: productData.id,
            dynamicGroupSelectedImage: productData.featuredImage?.url ?? "",
            product_id: productData.id.toString(),
            product_handle: productData.handle,
            product_title: productData.title,
            product_qty: 1,
            dropdowns_amount: 1,
            gift_product: null,
            gift_image: "",
            gift_text: "null",
            upsell_image: "",
            upsell_text: "",
            product_is_gift: false,
            product_is_upsell: false,
            has_gift_products: false,
            has_upsell_products: false,
            price_in_offer: Number(productData.variants[0].price.amount).toFixed(2),
            options_number: productData.options?.[1] ? 3 : 2,
            option2_is_color: "0",
            option2_title: "",
            option2_values: (productData.options?.[0]?.optionValues ?? []).map(val => val.name).toSorted(),
            option3_is_color: "0",
            option3_title: "",
            option3_values: (productData.options?.[1]?.optionValues ?? []).map(val => val.name).toSorted(),
            option4_is_color: "0",
            option4_title: "",
            option4_values: (productData.options?.[2]?.optionValues ?? []).map(val => val.name).toSorted(),
            options_color_values: dynamicProductOffer.options_color_values ? dynamicProductOffer.options_color_values : {},
            options_labels: "",
            variants: productData.variants.map((variant) => {
                return {
                    id: variant.id,
                    price: variant.price?.amount ? wideBundle.formatPrice(Number(variant.price.amount).toFixed(2)) : "",
                    compare_at_price: variant.compareAtPrice?.amount ? wideBundle.formatPrice(Number(variant.compareAtPrice.amount).toFixed(2)) : "",
                    option1: dynamicProductOffer.variants[0].option1,
                    option2: variant.selectedOptions?.[0]?.value ?? null,
                    option3: variant.selectedOptions?.[1]?.value ?? null,
                    option4: variant.selectedOptions?.[2]?.value ?? null,
                    conversion_rate: 1,
                };
            }),
        };
        if (productData.options?.[0]) {
            newOffer.option2_title = productData.options[0].name;
            newOffer.option2_is_color = (newOffer?.swatch_options ?? []).includes(productData.options[0].name) ? "1" : "0";
            const option2Count = wideBundle.offers[offersPointer]
                .slice(0, dynamicProductIndex)
                .filter(offer => 
                    offer.option2_title === newOffer.option2_title ||
                    offer.option3_title === newOffer.option2_title ||
                    offer.option4_title === newOffer.option2_title
                )
                .length + 1;
            newOffer.options_labels = newOffer.option2_title + " " + option2Count;
            newOffer.option2_values.forEach((val) => {
                const simplified = "_" + wideBundle.simplifyColor(val);
                newOffer.options_color_values[val] = wideBundle.listColors[simplified] ?? "#ffffff";
            });
        }
        if (productData.options?.[1]) {
            newOffer.option3_title = productData.options[1].name;
            newOffer.option3_is_color = (newOffer?.swatch_options ?? []).includes(productData.options[1].name) ? "1" : "0";
            const option3Count = wideBundle.offers[offersPointer]
                .slice(0, dynamicProductIndex)
                .filter(offer => 
                    offer.option2_title === newOffer.option3_title ||
                    offer.option3_title === newOffer.option3_title ||
                    offer.option4_title === newOffer.option3_title
                )
                .length + 1;
            newOffer.options_labels += " & " + newOffer.option3_title + " " + option3Count;
            newOffer.option3_values.forEach((val) => {
                const simplified = "_" + wideBundle.simplifyColor(val);
                newOffer.options_color_values[val] = wideBundle.listColors[simplified] ?? "#ffffff";
            });
        }
        if (productData.options?.[2]) {
            newOffer.option4_title = productData.options[2].name;
            newOffer.option4_is_color = (newOffer?.swatch_options ?? []).includes(productData.options[2].name) ? "1" : "0";
            const option4Count = wideBundle.offers[offersPointer]
                .slice(0, dynamicProductIndex)
                .filter(offer => 
                    offer.option2_title === newOffer.option4_title ||
                    offer.option3_title === newOffer.option4_title ||
                    offer.option4_title === newOffer.option4_title
                )
                .length + 1;
            newOffer.options_labels += " & " + newOffer.option4_title + " " + option4Count;
            newOffer.option4_values.forEach((val) => {
                const simplified = "_" + wideBundle.simplifyColor(val);
                newOffer.options_color_values[val] = wideBundle.listColors[simplified] ?? "#ffffff";
            });
        }
    } else {
        newOffer = {
            ...dynamicProductOffer,
            all_products: false,
            dynamicGroupSelected: null,
            dynamicGroupSelectedImage: "",
            product_id: wb_php_crc32(uuid),
            product_handle: uuid,
            product_title: "",
            product_qty: 1,
            dropdowns_amount: 1,
            gift_product: null,
            gift_image: "",
            gift_text: "null",
            product_is_gift: false,
            product_is_upsell: false,
            has_gift_products: false,
            has_upsell_products: false,
            price_in_offer: "0.0",
            options_number: 1,
            option2_is_color: "0",
            option2_title: "",
            option2_values: [],
            option3_is_color: "0",
            option3_title: "",
            option3_values: [],
            option4_is_color: "0",
            option4_title: "",
            option4_values: [],
            options_color_values: {},
            options_labels: "",
            variants: [
                {
                    id: Number(wb_php_crc32(uuid).toString() + "0"),
                    price: "0.0",
                    compare_at_price: "",
                    option1: dynamicProductOffer?.variants?.[0]?.option1 ?? "",
                    option2: null,
                    option3: null,
                    option4: null,
                    conversion_rate: 1,
                },
            ],
        };
    }
    wideBundle.offers[offersPointer][dynamicProductIndex] = newOffer;
    wideBundle.addHiddenPrices();

    for(var i = 0; i < wideBundle.widgetContainers.length; i++){ //For each widget container
        const widgetContainer = wideBundle.widgetContainers[i];
        let prevOfferContainer = widgetContainer.querySelector(".selectedWB");
        var offer = wideBundle.offers[offersPointer][0];
        let offerContainer = wideBundle.createOfferContainer(widgetContainer, offer, offersPointer); //Create the container
        wideBundle.createOfferContentLeft(offerContainer, offer); //Create the content left
        wideBundle.createOfferContentRight(offerContainer, offer, offersPointer); //Create the content right
        if (offer.user_text_enabled) {
            wideBundle.createOfferContentUserText(offerContainer, offer); //Create the content user text
        }

        //We need an additional div for all the elements if we have a gift offer for the flex wrap
        if (offerContainer.classList.contains('offer-free-gift') || offerContainer.classList.contains('offer-upsell-product')) {
            const flexContainer = document.createElement('div');
            flexContainer.classList.add('offer-with-gift-flex-wrapper');
            
            Array.from(offerContainer.children)
                .filter(child => !child.classList.contains('wb-gift-product-wrapper') && !child.classList.contains('wb-upsell-product-wrapper') && !child.classList.contains('wb-user-text-wrapper') && !child.classList.contains('wb-offer-timer'))
                .forEach(child => flexContainer.appendChild(child));
            
            offerContainer.prepend(flexContainer);
        }

        widgetContainer.insertBefore(offerContainer, prevOfferContainer);
        prevOfferContainer.remove();
        wideBundle.addStructureStyle();
        // wideBundle.updatePriceOnAllOffers();
        offerContainer.click();
    }
}

async function fetchDynamicGroupData(dynamicGroup) {
    if (!dynamicGroup.isCollection) {
        return dynamicGroup;
    }

    if (wideBundle?.dynamicGroupsCache?.collections?.[dynamicGroup?.collection?.id]) {
        return {
            ...dynamicGroup,
            options: wideBundle?.dynamicGroupsCache?.collections[dynamicGroup?.collection?.id] ?? [],
        };
    }

    let cursor = null;
    let hasNextPage = true;
    let products = [];
    while (hasNextPage) {
        const apiData = await wideBundle.makeStorefrontApiRequest(`#graphql
            query collectionProducts($id: ID!, $cursor: String, $country: CountryCode) @inContext(country: $country) {
                collection(id: $id) {
                    products(first: 250, after: $cursor) {
                        nodes {
                            id
                            title
                            featuredImage {
                                url(transform: { maxHeight: 80 })
                            }
                        }
                        pageInfo {
                            hasNextPage
                            endCursor
                        }
                    }
                }
            }
        `, {
            id: wideBundle.toGraphqlId("Collection", dynamicGroup.collection.id),
            cursor: cursor,
        });
        apiData.collection.products.nodes.forEach((product) => {
            products.push({
                id: wideBundle.fromGraphqlId(product.id),
                title: product.title,
                thumbnail: product.featuredImage !== null ? { alt: "Product", url: product.featuredImage.url } : null,
            });
        });
        hasNextPage = apiData.collection.products.pageInfo.hasNextPage;
        cursor = apiData.collection.products.pageInfo.endCursor;
    }

    wideBundle.dynamicGroupsCache.collections[dynamicGroup.collection.id] = products;
    wideBundle.offers.forEach((offerGroup, groupIndex) => {
        offerGroup.forEach((offer, offerIndex) => {
            offer.dynamicGroups.forEach((dg, dynamicGroupIndex) => {
                if (dg.options[0].id === dynamicGroup.collection.id) {
                    wideBundle.offers[groupIndex][offerIndex].dynamicGroups[dynamicGroupIndex] = {
                        ...dg,
                        options: products,
                    };
                }
            });
        });
    });

    return { ...dynamicGroup, options: products };
}

async function fetchDynamicProductData(data) {
    if (wideBundle?.dynamicGroupsCache?.products?.[data.id]) {
        return wideBundle.dynamicGroupsCache.products[data.id];
    }

    const productData = await wideBundle.makeStorefrontApiRequest(`#graphql
        query productDetails($id: ID!, $country: CountryCode) @inContext(country: $country) {
            product(id: $id) {
                id
                title
                handle
                featuredImage {
                    url(transform: { maxHeight: 80 })
                }
                options {
                    name
                    optionValues {
                        name
                    }
                }
            }
        }
    `, {
        id: wideBundle.toGraphqlId("Product", data.id),
    });

    let cursor = null;
    let hasNextPage = true;
    let variants = [];
    while (hasNextPage) {
        const variantsData = await wideBundle.makeStorefrontApiRequest(`#graphql
            query productVariants($id: ID!, $cursor: String, $country: CountryCode) @inContext(country: $country) {
                product(id: $id) {
                    variants(first: 250, after: $cursor) {
                        nodes {
                            id
                            availableForSale
                            currentlyNotInStock
                            quantityAvailable
                            compareAtPrice {
                                amount
                            }
                            price {
                                amount
                            }
                            selectedOptions {
                                name
                                value
                            }
                        }
                        pageInfo {
                            hasNextPage
                            endCursor
                        }
                    }
                }
            }
        `, {
            id: wideBundle.toGraphqlId("Product", data.id),
            cursor: cursor,
        });
        variantsData.product.variants.nodes.forEach((variant) => {
            variants.push({
                ...variant,
                id: wideBundle.fromGraphqlId(variant.id),
            });
        });
        hasNextPage = variantsData.product.variants.pageInfo.hasNextPage;
        cursor = variantsData.product.variants.pageInfo.endCursor;
    }

    let featuredImageUrl = null;
    if (productData.product?.featuredImage !== null) {
        const url = new URL(productData.product.featuredImage.url);
        // 1. Link has _123x suffix, which we need to remove
        // 2. Link has _x123 suffix, which we need to remove
        // 3. Find file extension at the end of url and append _200x200 to get resized image from CDN
        url.pathname = url.pathname.replace(/_(\d+)x(\d+)(\.\w+)$/, "$3");
        url.pathname = url.pathname.replace(/_x(\d+)(\.\w+)$/, "$2");
        url.pathname = url.pathname.replace(/\.(jpg|jpeg|png|webp|avif|gif|heic)$/, "_200x200.$1");
        featuredImageUrl = url.toString();
    }
    wideBundle.dynamicGroupsCache.products[data.id] = {
        ...productData.product,
        featuredImage: productData.product?.featuredImage !== null
            ? { alt: "Product", url: featuredImageUrl }
            : null,
        id: wideBundle.fromGraphqlId(productData.product.id),
        variants: variants,
    };
    variants.forEach((variant) => {
        const addToCartBtnEnable = variant.availableForSale ? "1" : "0";
        let inventoryQuantity = variant.quantityAvailable;
        if (variant.availableForSale && variant.currentlyNotInStock) {
            inventoryQuantity = 999999;
        } else if (variant.availableForSale && !variant.currentlyNotInStock && variant.quantityAvailable <= 0) {
            inventoryQuantity = 999999;
        }

        wideBundle.variantsInventory[variant.id] = {
            inventory_quantity: inventoryQuantity,
            add_to_cart_btn_enable: addToCartBtnEnable
        };
    });

    return wideBundle.dynamicGroupsCache.products[data.id];
}

function ensureDynamicGroupPopup() {
    if (document.querySelector("#wb-dynamic-group-popup")) return;
    const s = wideBundle.settings;

    const msgBgColor = s.unselected_background_color || "#ffffff";
    const msgBgColorTransparency = s.unselected_background_transparency || "";
    const msgBorderColor = s.unselected_border_color || "#000000";
    const msgBorderRadius = s.unselected_message_border_radius || "0px";
    const msgBorderSize = s.unselected_message_border_size || "0px";

    const titleColor = s.preview_heading_color || "#000000";
    const titleFont = s.unselected_title_text_font || "auto";
    const titleFontSize = s.unselected_title_fontsize || "1em";

    const optionFontSize = s.option_fontsize || "0.9em";
    const optionColor = s.option_select_color || s.option_color || "#000000";
    const optionBg = s.option_select_background || "#ffffff";
    const optionBorderColor = s.unselected_border_color || "#c6c6c6";
    const optionBorderRadius = s.unselected_border_radius || "5px";
    const optionBorderSize = s.unselected_border_size || "2px";

    const atcBg = s.atc_background || "#000000";
    const atcColor = s.atc_color || "#ffffff";
    const atcRadius = s.atc_radius || "0px";
    const atcFontSize = s.atc_font_size || "1em";
    const atcFont = s.atc_font || "auto";

    const popup = document.createElement("div");
    popup.innerHTML = /* html */ `
        <div
            id="wb-dynamic-group-popup"
            class="wb-dg-popup"
            style="
                display: none;
                --wb-msg-bg-color: ${msgBgColor + msgBgColorTransparency};
                --wb-msg-border-size: ${msgBorderSize === "0px" ? "1px" : msgBorderSize};
                --wb-msg-border-color: ${msgBorderColor};
                --wb-msg-border-radius: ${msgBorderRadius};
                --wb-title-color: ${titleColor};
                --wb-title-font: ${titleFont === "auto" ? "inherit" : titleFont};
                --wb-title-font-size: ${titleFontSize};
                --wb-option-font-size: ${optionFontSize};
                --wb-option-color: ${optionColor};
                --wb-option-bg: ${optionBg};
                --wb-option-border-color: ${optionBorderColor};
                --wb-option-border-radius: ${optionBorderRadius};
                --wb-option-border-size: ${optionBorderSize === "0px" ? "1px" : optionBorderSize};
                --wb-atc-bg: ${atcBg};
                --wb-atc-color: ${atcColor};
                --wb-atc-radius: ${atcRadius};
                --wb-atc-font: ${atcFont === "auto" ? "inherit" : '"' + atcFont + '"'};
                --wb-atc-font-size: ${atcFontSize};
            "
        >
            <div class="wb-dg-popup__content">
                <header class="wb-dg-popup__header">
                    <h2 class="wb-dg-popup__title js-dg-title">
                        ${wbHtmlentities(s.dg_popup_heading_text)}
                    </h2>
                    <button class="wb-dg-popup__close-btn js-dg-close-btn" type="button">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M18 6 6 18"/>
                            <path d="m6 6 12 12"/>
                        </svg>
                    </button>
                </header>
                <ul class="wb-dg-popup__products js-dg-products"></ul>
                <footer class="wb-dg-popup__footer">
                    <button class="wb-dg-popup__submit-btn js-dg-submit-btn" type="button" disabled>
                        ${wbHtmlentities(s.dg_choose_btn_text)}
                    </button>
                </footer>
            </div>
            <div class="wb-dg-popup__overlay js-dg-overlay">&nbsp;</div>
        </div>
    `;

    const overlay = popup.querySelector(".js-dg-overlay");
    const submit = popup.querySelector(".js-dg-submit-btn");
    const close = popup.querySelector(".js-dg-close-btn");
    document.body.appendChild(popup);

    popup.addEventListener("change", () => submit.disabled = false);
    overlay.addEventListener("click", () => closeDynamicGroupPopup(submit.dataset.uuid, null));
    close.addEventListener("click", () => closeDynamicGroupPopup(submit.dataset.uuid, null));
    submit.addEventListener("click", (event) => {
        const parent = event.target.closest("#wb-dynamic-group-popup");
        const parentRadio = parent.querySelector(".js-dg-products .wb-dg-popup-product__input:checked");
        const uuid = submit.dataset.uuid;
        const choice = parentRadio.value;
        submit.disabled = true;
        submit.textContent = "Loading...";
        closeDynamicGroupPopup(uuid, choice);
    });
}

async function openDynamicGroupPopup(inputDynamicGroup, selected = false) {
    const dynamicGroupButton = wideBundle.activeWidget.querySelector(`.js-wb-dynamic-group[data-uuid="${inputDynamicGroup.uuid}"]`);
    if (dynamicGroupButton) {
        dynamicGroupButton.disabled = false;
        dynamicGroupButton.innerHTML = /* html */ `
            ${!selected ? `
                <div class="js-wb-dynamic-group__thumb">
                    <img class="loading-wb" src='${GetLoadingGifBase64()}' width="20px" height="20px" />
                </div>` :
                `<div class="js-wb-dynamic-group__close">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M18 6 6 18"/>
                        <path d="m6 6 12 12"/>
                    </svg>
                </div>`}
            <div class="js-wb-dynamic-group__choose">${wbHtmlentities(wideBundle.settings.dg_choose_btn_text)}</div>
        `;
    }
    const dynamicGroup = await fetchDynamicGroupData(inputDynamicGroup);
    ensureDynamicGroupPopup();
    if (dynamicGroupButton) {
        dynamicGroupButton.disabled = false;
        dynamicGroupButton.innerHTML = /* html */ `
            ${!selected ? '<div class="js-wb-dynamic-group__thumb">?</div>' :
                `<div class="js-wb-dynamic-group__close">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M18 6 6 18"/>
                        <path d="m6 6 12 12"/>
                    </svg>
                </div>`}
            <div class="js-wb-dynamic-group__choose">${wbHtmlentities(wideBundle.settings.dg_choose_btn_text)}</div>
        `;
    }

    const popup = document.querySelector("#wb-dynamic-group-popup");
    const popupProducts = popup.querySelector(".js-dg-products");
    const submitBtn = popup.querySelector(".js-dg-submit-btn");

    popupProducts.innerHTML = "";
    dynamicGroup.options.forEach((option) => {
        let thumbnailUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
        if (option.thumbnail?.url?.length > 0) {
            thumbnailUrl = new URL(option.thumbnail?.url ?? "");
            // 1. Link has _123x suffix, which we need to remove
            // 2. Link has _x123 suffix, which we need to remove
            // 3. Find file extension at the end of url and append _200x200 to get resized image from CDN
            thumbnailUrl.pathname = thumbnailUrl.pathname.replace(/_(\d+)x(\d+)(\.\w+)$/, "$3");
            thumbnailUrl.pathname = thumbnailUrl.pathname.replace(/_x(\d+)(\.\w+)$/, "$2");
            thumbnailUrl.pathname = thumbnailUrl.pathname.replace(/\.(jpg|jpeg|png|webp|avif|gif|heic)$/, "_200x200.$1");
            thumbnailUrl = thumbnailUrl.toString();
        }
        
        popupProducts.insertAdjacentHTML("beforeend", /* html */ `
            <li class="wb-dg-popup__product wb-dg-popup-product js-dg-product">
                <input
                    id="wb-dg-${dynamicGroup.uuid}-${option.id}"
                    class="wb-dg-popup-product__input"
                    name="wb-dg-product"
                    type="radio"
                    value="${option.id}"
                >
                <label
                    class="wb-dg-popup-product__label"
                    for="wb-dg-${dynamicGroup.uuid}-${option.id}"
                >
                    <div class="wb-dg-popup-product__image">
                        <img
                            class="wb-dg-popup-product__thumb"
                            src="${thumbnailUrl}"
                            loading="lazy"
                            width="200"
                            height="200"
                        >
                    </div>
                    <span class="wb-dg-popup-product__title">
                        ${wbHtmlentities(option.title)}
                    </span>
                </label>
            </li>
        `);
    });

    submitBtn.dataset.uuid = dynamicGroup.uuid;

    popup.style.display = "flex";
    document.body.style.overflow = "hidden";
    document.body.style.overscrollBehavior = "none";
}

async function closeDynamicGroupPopup(uuid, choice = null) {
    const popup = document.querySelector("#wb-dynamic-group-popup");
    if (choice === null) {
        wideBundle.updateDynamicGroupProduct(uuid, null);
        const submit = popup.querySelector(".js-dg-submit-btn");
        submit.disabled = true;
        popup.style.display = "none";
        document.body.style.overflow = null;
        document.body.style.overscrollBehavior = null;
        return;
    }

    const selectedOffer = wideBundle.getSelectedOffer();
    const dynamicGroup = selectedOffer.dynamicGroups.find((group) => group.uuid === uuid);
    const selectedOption = dynamicGroup.options.find((option) => option.id === Number(choice));
    const productData = await fetchDynamicProductData(selectedOption);
    wideBundle.updateDynamicGroupProduct(uuid, productData);
    setTimeout(() => {
        const submit = popup.querySelector(".js-dg-submit-btn");
        submit.disabled = true;
        submit.textContent = wideBundle.settings.dg_choose_btn_text;
        popup.style.display = "none";
        document.body.style.overflow = null;
        document.body.style.overscrollBehavior = null;
    }, 0);
}

function defaultSelect(offer, contentRight, i, j, optionsLabels, offersPointer, productPointer, swatchId, offerContainer) {
        let giftWrapper = document.createElement('div');
        giftWrapper.classList.add('wb-gift-product-wrapper');
        var selectContainer = document.createElement('div');
        selectContainer.id = `div-second-select-${offer.variants[0].id}-${i}__${offersPointer}_${productPointer}`;
        selectContainer.classList.add(`div-second-select-${offer.variants[0].id}-${i}__${offersPointer}_${productPointer}`, `div-select2`);
        if(wideBundle.settings.plan !== "monthly" && (offer.option4_is_color === "1" || offer.option3_is_color === "1" || offer.option2_is_color === "1")) {
            selectContainer.classList.add('wb-swatch-container');
        }
        if(offer.automatic_discount){
            selectContainer.classList.add(`div-discount-system`);
        }
        selectContainer.setAttribute('data-id', offer.variants[0].id);
        selectContainer.setAttribute('data-product-id', offer.product_id);
        selectContainer.setAttribute('data-offers-pointer', offersPointer);
        selectContainer.setAttribute('data-product-pointer', productPointer);
        if (offer.dynamicGroupUuid !== null && offer.dynamicGroupSelected !== null && wideBundle.settings.design_code != 1) {
            selectContainer.style.marginLeft = "92px";
        }

        const maxDepth = offer.options_number - 1;
        let initialOptions = [offer.option2_values[0]];
        if (maxDepth > 0 && offer.option3_values?.[0]) initialOptions.push(offer.option3_values[0]);
        if (maxDepth > 1 && offer.option4_values?.[0]) initialOptions.push(offer.option4_values[0]);
        const optionAvailability = wideBundle.calcOptionsAvailability(
            initialOptions,
            [
                offer.option2_values,
                offer.option3_values,
                offer.option4_values,
            ],
            offer.variants,
        );
        if(offer.options_number == 3){ //If we have a 3rd option we add the <select> for this option with the options values
            selectContainer.classList.add('has-double-select');

            var selectForThirdOptionHtml = `<select
                class='${offer.option3_values.length <= 1 ? "hide-bloc-wb" : ""} ${offer.automatic_discount ? "discount_system_select_wb" : ""} select-bundle select-class-second select-option-third select-option-third-${j} add-option3-${offer.variants[0].id}-${j} ${offer.option3_is_color === "1" && wideBundle.settings.plan !== "monthly" ? 'swatch-3-select' : ''}'
                ${offer.option3_is_color === "1" && wideBundle.settings.plan !== "monthly" ? `id="swatch-3-select-` + swatchId + `-` + j + '--' + offer.product_id + `"` : ''}
                onchange='wideBundle.checkSelectsAvailability(event);'
                name='Variants2' size='1'
            >`;
            for(var k = 0; k<offer.option3_values.length; k++){
                var value = offer.option3_values[k];
                const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[1][k] : false;
                selectForThirdOptionHtml +=  `<option value="` + wbHtmlentities(value) +`" ${disabled?'disabled':''}>${wbHtmlentities(wideBundle.getTranslatedText(value))}</option>`;
            }
            selectForThirdOptionHtml += `</select>`;

            if(offer.option3_is_color === "1" && wideBundle.settings.plan !== "monthly") {
                selectForThirdOptionHtml += `<div class="wb-color-swatch-box">`;
                for(var k = 0; k<offer.option3_values.length; k++){
                    const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[1][k] : false;
                    var color_hex = offer.options_color_values[offer.option3_values[k]];
                    var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) ? `background-color: ${color_hex}` : `background-image: url(${color_hex})`;

                    selectForThirdOptionHtml +=  `<label class="wb-color-swatch">
                            <input type="radio" name="Variants3Swatch-${swatchId}-${j}--${offer.product_id}__${offersPointer}_${productPointer}"
                                class="swatch-3-radio swatch-3-radio-${j}"
                                data-productId="${offer.product_id}"
                                data-variantId="3"
                                data-swatchId="${swatchId}"
                                data-dropdownId="${j}"
                                data-k="${k}"
                                value="${wbHtmlentities(offer.option3_values[k])}"
                                ${(k === 0 ? `checked="checked"` : ``)}
                                ${disabled ? 'disabled' : ''}
                                onchange="wideBundle.mergeSwatch(this)"
                            />
                            <div class="wb-color-swatch-radio" title="${wbHtmlentities(wideBundle.getTranslatedText(offer.option3_values[k]))}" style="${style}"></div>
                        </label>`;
                }
                selectForThirdOptionHtml += `</div>`;
            }
        }
        else{
            var selectForThirdOptionHtml = '';
        }
        //Add the select for the 2nd option with the options values
        let selectForSecondOptionHtml = offer.automatic_discount
            ? (offer.options_number !== 3 && !offer.product_is_gift ? `<p class='title-option-wb label_num_auto_discount_wb'>#${i+1}</p>` : "")
            : `<p class='title-option-wb'>${wideBundle.getTranslatedText(optionsLabels[i])}</p>`;

        selectForSecondOptionHtml += `<div class="block_dropdowns_wb">`; //Add the selects into a div for the display flex

        selectForSecondOptionHtml += `<select
            class='${offer.option2_values.length <= 1 ? "hide-bloc-wb" : ""} ${offer.automatic_discount ? "discount_system_select_wb" : ""} select-bundle select-class-second select-option-second select-option-second-${j} add-option-${offer.variants[0].id}-${j} ${offer.option2_is_color === "1" && wideBundle.settings.plan !== "monthly" ? 'swatch-2-select' : ''}'
            ${offer.option2_is_color === "1" && wideBundle.settings.plan !== "monthly" ? `id="swatch-2-select-` + swatchId + `-` + j + '--' + offer.product_id + `"` : ''}
            onchange='wideBundle.checkSelectsAvailability(event);' name='Variants' size='1'
        >`;
        for (var k = 0; k < offer.option2_values.length; k++) {
            var value = offer.option2_values[k];
            const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[0][k] : false;
            selectForSecondOptionHtml += `<option value="` + wbHtmlentities(value) + `" ${disabled?'disabled':''}>${wbHtmlentities(wideBundle.getTranslatedText(value))}</option>`;
        }
        selectForSecondOptionHtml += `</select>`;
        if (offer.options_number == 2 && offer.automatic_discount) {
            selectForSecondOptionHtml += `<p class="clear"></p>`;
        }
        if(offer.option2_is_color === "1" && wideBundle.settings.plan !== "monthly") {
            selectForSecondOptionHtml += `<div class="wb-color-swatch-box">`;
            for (var k = 0; k < offer.option2_values.length; k++) {
                const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[0][k] : false;
                var color_hex = offer.options_color_values[offer.option2_values[k]];
                var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) ? `background-color: ${color_hex}` : `background-image: url(${color_hex})`;

                selectForSecondOptionHtml +=  `<label class="wb-color-swatch">
                            <input type="radio" name="Variants2Swatch-${swatchId}-${j}--${offer.product_id}__${offersPointer}_${productPointer}"
                                class="swatch-2-radio swatch-2-radio-${j}"
                                data-productId="${offer.product_id}"
                                data-variantId="2"
                                data-swatchId="${swatchId}"
                                data-dropdownId="${j}"
                                data-k="${k}"
                                value="${wbHtmlentities(offer.option2_values[k])}"
                                ${(k === 0 ? `checked="checked"` : ``)}
                                ${disabled ? 'disabled' : ''}
                                onchange="wideBundle.mergeSwatch(this)"
                            />
                            <div class="wb-color-swatch-radio" title="${wbHtmlentities(wideBundle.getTranslatedText(offer.option2_values[k]))}" style="${style}"></div>
                        </label>`;
            }
            selectForSecondOptionHtml += `</div>`;
        }
        selectForSecondOptionHtml += `${selectForThirdOptionHtml}${offer.automatic_discount ? '' : '<p class="clear"></p>'}`;

        //Hide the <selects> container if there is 1 option value or less for both options
        if(offer.option2_values.length <= 1 && offer.option3_values.length <= 1){
            selectContainer.classList.add('hide-bloc-wb');
        }

        if (offer.automatic_discount && offer.options_number == 3) {
            //Add the select for the 1st option with the options values
            selectForSecondOptionHtml = !offer.product_is_gift ? (`<p class='title-option-wb label_num_auto_discount_wb'>#${i+1}</p>` + selectForSecondOptionHtml) : selectForSecondOptionHtml;
            
            var selectForFirstOptionHtml = `<select
                            class='${offer.option4_values.length <= 1 ? "hide-bloc-wb" : ""} ${offer.automatic_discount ? "discount_system_select_wb" : ""} select-bundle select-class-first select-option-first select-option-first-${j} add-option-${offer.variants[0].id}-${j} ${offer.option4_is_color === "1" && wideBundle.settings.plan !== "monthly" ? 'swatch-1-select' : ''}'
                            ${offer.option4_is_color === "1" && wideBundle.settings.plan !== "monthly" ? `id="swatch-1-select-` + swatchId + `-` + j + '--' + offer.product_id + `"` : ''}
                            onchange='wideBundle.checkSelectsAvailability(event);' name='Variants3' size='1'
                        >`;
            for (var k = 0; k < offer.option4_values.length; k++) {
                var value = offer.option4_values[k];
                const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[2][k] : false;
                selectForFirstOptionHtml += `<option value="` + wbHtmlentities(value) + `" ${disabled?'disabled':''}>${wbHtmlentities(wideBundle.getTranslatedText(value))}</option>`;
            }
            selectForFirstOptionHtml += `</select>`;

            if(offer.option4_is_color === "1" && wideBundle.settings.plan !== "monthly") {
                selectForFirstOptionHtml += `<div class="wb-color-swatch-box">`;
                for (var k = 0; k < offer.option4_values.length; k++) {
                    const disabled = wideBundle.isAutomaticDiscount ? !optionAvailability[2][k] : false;
                    var color_hex = offer.options_color_values[offer.option4_values[k]];
                    var style = /^#(?:[0-9a-f]{3}){1,2}$/i.test(color_hex) ? `background-color: ${color_hex}` : `background-image: url(${color_hex})`;
    
                    selectForFirstOptionHtml +=  `<label class="wb-color-swatch">
                                <input type="radio" name="Variants4Swatch-${swatchId}-${j}--${offer.product_id}__${offersPointer}_${productPointer}"
                                    class="swatch-1-radio swatch-1-radio-${j}"
                                    data-productId="${offer.product_id}"
                                    data-variantId="1"
                                    data-swatchId="${swatchId}"
                                    data-dropdownId="${j}"
                                    data-k="${k}"
                                    value="${wbHtmlentities(offer.option4_values[k])}"
                                    ${(k === 0 ? `checked="checked"` : ``)}
                                    ${disabled ? 'disabled' : ''}
                                    onchange="wideBundle.mergeSwatch(this)"
                                />
                                <div class="wb-color-swatch-radio" title="${wbHtmlentities(wideBundle.getTranslatedText(offer.option4_values[k]))}" style="${style}"></div>
                            </label>`;
                }
                selectForFirstOptionHtml += `</div>`;
            }

            selectForSecondOptionHtml += selectForFirstOptionHtml;
            selectForSecondOptionHtml += `<p class="clear"></p>`;

            selectContainer.innerHTML = selectForSecondOptionHtml;
        }

        selectContainer.innerHTML = selectForSecondOptionHtml;
        if (offer.product_is_gift) {
            giftLeftContainer = document.createElement("div");
            giftLeftContainer.classList.add("gift-left-container");

            giftLeftSubContainer = document.createElement("div");
            giftLeftSubContainer.classList.add("gift-left-sub-container");

            offerContainer.classList.add(`offer-free-gift`);
            if (offer.gift_image !== null && offer.gift_image.length > 0) {
                const giftImage = document.createElement("img");
                giftImage.width = 27;
                giftImage.height = 27;
                giftImage.src = offer.gift_image;
                giftLeftContainer.appendChild(giftImage);
            }
            if (offer.gift_text !== null && offer.gift_text.length > 0) {
                const giftText = document.createElement("p");
                giftText.textContent = wideBundle.getTranslatedText(offer.gift_text);
                giftText.classList.add("free-gift-text");
                giftLeftSubContainer.appendChild(giftText);
            }

            // Add option titles using the same system
            const optionsName = [2, 3, 4]
                .map(i => offer[`option${i}_values`]?.length > 1 ? wideBundle.getTranslatedText(offer[`option${i}_title`]) : null)
                .filter(title => title && title.trim())
                .join(', ');

            if (optionsName) {
                let labelDropdowns = document.createElement('p');
                labelDropdowns.classList.add("general_option_label_wb");
                if (offer.dynamicGroupSelected !== null) {
                    labelDropdowns.innerHTML = /* html */ `
                        <img width="38" height="38" src="${offer.dynamicGroupSelectedImage ?? ""}">
                        ${wbHtmlentities(optionsName)}
                    `;
                } else {
                    labelDropdowns.textContent = `${wbHtmlentities(optionsName)}`;
                    
                }
                giftLeftSubContainer.appendChild(labelDropdowns);
            }
        
            selectContainer.innerHTML = selectForSecondOptionHtml;

            giftLeftSubContainer.appendChild(selectContainer);
            giftLeftContainer.appendChild(giftLeftSubContainer);

            // Add price display for gift product
            const priceElement = document.createElement('p');
            priceElement.classList.add('gift-price-new-form');
            
            var variantId = offer.variants[0].id;
            var price = document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantId}"]`).innerHTML;
            var compareAtPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantId}"]`).innerHTML;

            var priceToShow = compareAtPrice && compareAtPrice !== "" ? compareAtPrice : price;
            
            var priceHtml = `
                <span class='gift-price-WB notranslate money conversion-bear-money transcy-money'>${wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator("0.00"))))}</span>
                <span class='gift-compare-at-price-WB notranslate money transcy-money conversion-bear-money'><s class="crossed-price-WB">${wideBundle.replaceCurrencyForMarket(priceToShow)}</s></span>
            `;
            priceElement.innerHTML = priceHtml;
            const plusCircle = document.createElement('div');
            plusCircle.className = 'plus-circle';
            const svgPlus = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M12 8L12 16" stroke="white" stroke-width="2.5" stroke-linecap="round"/>
                                <path d="M16 12L8 12" stroke="white" stroke-width="2.5" stroke-linecap="round"/>
                            </svg>`;
            plusCircle.innerHTML = svgPlus;
            giftWrapper.appendChild(plusCircle);
            giftWrapper.appendChild(giftLeftContainer);
            giftWrapper.appendChild(priceElement);
            giftWrapper.dataset.gOffersPointer = offersPointer;
            giftWrapper.dataset.gProductPointer = productPointer;
            giftWrapper.dataset.gProductId = offer.product_id;
            offerContainer.appendChild(giftWrapper);

        } else if (offer.product_is_upsell) {
            let upsellWrapper = document.createElement('div');
            upsellWrapper.classList.add('wb-gift-product-wrapper');
            upsellWrapper.classList.add('wb-gift-product-wrapper--upsell');
            
            let upsellLeftContainer = document.createElement("div");
            upsellLeftContainer.classList.add("gift-left-container");

            let upsellLeftSubContainer = document.createElement("div");
            upsellLeftSubContainer.classList.add("gift-left-sub-container");

            offerContainer.classList.add(`offer-free-gift`);
            
            // Add product image if available (similar to gift)
            if (offer.upsell_image !== null && offer.upsell_image.length > 0) {
                const upsellImage = document.createElement("img");
                upsellImage.width = 27;
                upsellImage.height = 27;
                upsellImage.src = offer.upsell_image;
                upsellLeftContainer.appendChild(upsellImage);
            }
            
            // Add product title or upsell text
            const upsellText = document.createElement("p");
            upsellText.textContent = wideBundle.getTranslatedText(offer.upsell_text || "Upsell Product");
            upsellText.classList.add("free-gift-text"); // Reuse gift text class
            upsellLeftSubContainer.appendChild(upsellText);

            // Add option titles using the same system
            const optionsName = [2, 3, 4]
            .map(i => offer[`option${i}_values`]?.length > 1 ? wideBundle.getTranslatedText(offer[`option${i}_title`]) : null)
            .filter(title => title && title.trim())
            .join(', ');

            if (optionsName) {
                let labelDropdowns = document.createElement('p');
                labelDropdowns.classList.add("general_option_label_wb");
                labelDropdowns.textContent = `${wbHtmlentities(optionsName)}`;
                upsellLeftSubContainer.appendChild(labelDropdowns);
            }
        
            selectContainer.innerHTML = selectForSecondOptionHtml;

            upsellLeftSubContainer.appendChild(selectContainer);
            upsellLeftContainer.appendChild(upsellLeftSubContainer);

            // Add price display for upsell product
            const priceElement = document.createElement('p');
            priceElement.classList.add('gift-price-new-form'); // Reuse gift price class
            priceElement.classList.add('upsell-price-new-form');

            const variantId = offer.variants[0].id;
            const totalPrice = wideBundle.getAmountFromPrice(document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantId}"]`)?.innerHTML ?? "").replace(",", ".");
            const price = Math.max(0, totalPrice - ((totalPrice / 100) * offer.upsell_discount)).toFixed(2);
            const compareAtPrice = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantId}"]`)?.innerHTML ?? "";
            const formattedPrice = wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(price))));
            const formattedCompareAtPrice = compareAtPrice?.length > 0 ? wideBundle.replaceCurrencyForMarket(compareAtPrice) : wideBundle.replaceCurrencyForMarket(wideBundle.formatPrice(wideBundle.removeDecimal(wideBundle.updatePriceSeparator(totalPrice))));
            let priceHtml = `
                <span class='gift-price-WB notranslate money conversion-bear-money transcy-money'>${formattedPrice}</span>
            `;
            let compareAtPriceHtml = `
                <span class='gift-compare-at-price-WB notranslate money transcy-money conversion-bear-money'><s class="crossed-price-WB">${formattedCompareAtPrice}</s></span>
            `;
            if (
                Number(wideBundle.getAmountFromPrice(formattedPrice) ?? 0).toFixed(2) ===
                Number(wideBundle.getAmountFromPrice(formattedCompareAtPrice) ?? 0).toFixed(2)
            ) {
                compareAtPriceHtml = '';
            }
            priceElement.innerHTML = priceHtml + compareAtPriceHtml;
            
            // Create checkbox for upsell
            const upsellCheckbox = document.createElement('input');
            upsellCheckbox.type = 'checkbox';
            upsellCheckbox.classList.add('wb-upsell-checkbox');
            upsellCheckbox.checked = false; // Unchecked by default
            upsellCheckbox.setAttribute('data-offers-pointer', offersPointer);
            upsellCheckbox.setAttribute('data-product-pointer', productPointer);
            upsellCheckbox.setAttribute('data-product-id', offer.product_id);
            upsellCheckbox.setAttribute('data-upsell-id', offer.offer_uuid);
            
            upsellWrapper.appendChild(upsellCheckbox);
            upsellWrapper.appendChild(upsellLeftContainer);
            upsellWrapper.appendChild(priceElement);
            upsellWrapper.dataset.gOffersPointer = offersPointer;
            upsellWrapper.dataset.gProductPointer = productPointer;
            upsellWrapper.dataset.gProductId = offer.product_id;
            offerContainer.appendChild(upsellWrapper);

        } else {
            contentRight.appendChild(selectContainer);
        }
}

//Display the saving text if it's enabled
wideBundle.createSavingText = function(offer, contentRight, offerContainer){
    let variantsString = offer.variants[0].id;
    if (wideBundle.isAutomaticDiscount) {
        const variantIdsSelected = wideBundle.offers[offer.offersPointer].filter((offer) => !offer.product_is_upsell).reduce((ids, offer) => {
            const variantId = offer.variants[0].id;
            return [...ids, ...(new Array(offer.product_qty).fill(variantId))];
        }, []);
        variantsString = offer.offersPointer + "@" + variantIdsSelected.join("+");
    }

    if(wideBundle.settings.economic_display == 1){
        var priceEl = document.querySelector(`.wb_hidden_prices .wb_hidden_price[variant-id="${variantsString}"]`);
        var compareAtPriceEl = document.querySelector(`.wb_hidden_prices .wb_hidden_compared_price[variant-id="${variantsString}"]`);
        const price = priceEl ? priceEl.innerHTML : "";
        const compareAtPrice = compareAtPriceEl ? compareAtPriceEl.innerHTML : "";
        if (price.trim() === compareAtPrice.trim()) return;
        if (price.trim() === "") return;
        if (compareAtPrice.trim() === "") return;

        difference = getAmountDifference(price, compareAtPrice);

        if(wideBundle.settings.no_decimal == 1){ //If they enabled the feature to remove decimal
            difference.amount = wideBundle.removeDecimal(difference.amount);
        }

        var currencyAlone = price.replace(/\d+.\d+/g,'{{amount}}').replace(/\d+/g,'{{amount}}')
        var priceDifference = wideBundle.updatePriceSeparator(currencyAlone.replace('{{amount}}', difference.amount));

        var savingTextContent = wideBundle.getTranslatedText(wideBundle.settings.economic_text);
        savingTextContent = savingTextContent.replace("{{percent}}", `<span class='percent-wb'>${difference.percent}</span>`);
        savingTextContent = savingTextContent.replace("{{amount}}", `<span class='money conversion-bear-money span-economic-wb transcy-money'>${wideBundle.updatePriceSeparator(priceDifference)}</span>`);

        var today = new Date();
        var dd = String(today.getDate()).padStart(2, '0');
        var mm = String(today.getMonth() + 1).padStart(2, '0');
        var yyyy = today.getFullYear();
        today = dd + '/' + mm + '/' + yyyy;
        savingTextContent = savingTextContent.replace('{{today}}', today);

        var savingText = document.createElement('p');
        savingText.innerHTML = savingTextContent;
        savingText.classList.add('economic-wb');
        contentRight.appendChild(savingText);
        offerContainer.classList.add('with-economic-text');
    }
}

//Create a custom sentence if the user added one
wideBundle.createCustomSentence = function(message, effect, contentParent, titleElement = null, position = null){
    if(message){
        customSentence = document.createElement('span');
        customSentence.classList.add('best-title', 'best-title-new');

        customSentence.innerHTML = wideBundle.getTranslatedText(message);
        if(effect == 1){ //If blinking enabled
            customSentence.classList.add('best-title-blink');
        }
        contentParent.classList.add('with-message');
        if (titleElement && position == 4) {
            titleElement.innerHTML = `${wideBundle.getTranslatedText(titleElement.innerHTML)} <span class="title-custom-text">${wideBundle.getTranslatedText(message)}</span>`;
        } else {
            contentParent.appendChild(customSentence);
        }
    }
}

//Add the quantity widget if it's enabled
wideBundle.createQuantityWidget = function(offerContainer){
    if(wideBundle.settings.display_quantity == 1){
        var quantityContainer = document.createElement('div');
        quantityContainer.classList.add('spinWB');
        quantityHTML = `
            <span class='quantity-wb-less'>&ndash;</span>
            <input class='quantity-wb-input' id='quantity-wb' value='1' />
            <span class='quantity-wb-more'>+</span>
        `;
        quantityContainer.innerHTML = quantityHTML;
        offerContainer.append(quantityContainer);

        //Add the event listeners
        quantityContainer.querySelector('.quantity-wb-less').addEventListener('click', function(){
            var value = Math.max(1, document.querySelector('.selectedWB .quantity-wb-input').value -1);
            wideBundle.updateQuantityInputs(value);
            wideBundle.updateQuantityDisabled(value);
        });
        quantityContainer.querySelector('.quantity-wb-more').addEventListener('click', function(){
            var value = Math.max(1, parseInt(document.querySelector('.selectedWB .quantity-wb-input').value)+1);
            wideBundle.updateQuantityInputs(value);
            wideBundle.updateQuantityDisabled(value);
        });
        offerContainer.querySelector('.quantity-wb-input').addEventListener('change', function(){
            if(isNaN(this.value.replace(',', '.'))){
                wideBundle.updateQuantityInputs(1);
                wideBundle.updateQuantityDisabled(1);
            }
            else{
                wideBundle.updateQuantityInputs(Math.round(this.value.replace(',', '.')));
                wideBundle.updateQuantityDisabled(Math.round(this.value.replace(',', '.')));
            }
        });
    }
}

//Update the quantity inputs values in the page
wideBundle.updateQuantityInputs = function(value){
    //For quantity inputs in the offers
    var quantityInputs = document.querySelectorAll('.quantity-wb-input');
    for(var i = 0; i<quantityInputs.length; i++){
        quantityInputs[i].value = value;
    }

    let inputUpdated = 0;

    //For quantity inputs in the product page
    var quantityInputsArray = ['[name="quantity"]', 'select[data-quantity-select]',
    'div[data-pf-type="Layout"] div[data-pf-type="ProductQuantity"] input', '.gf_product-quantity input[name="quantity"]', "gp-product-quantity input[name='product-quantity']"];
    for(var i = 0; i<quantityInputsArray.length; i++){
        if(wideBundle.formInfo.element){
            var quantityInput = wideBundle.formInfo.element.querySelector(quantityInputsArray[i]);
            if(quantityInput){
                quantityInput.value = value;
                inputUpdated = 1;
            }
        }
    }
    if(!inputUpdated){
      for(var i = 0; i<quantityInputsArray.length; i++){
          var quantityInput = document.querySelector(quantityInputsArray[i]);
          if(quantityInput){
              quantityInput.value = value;
              inputUpdated = 1;
          }
      }
    }

    //For replo system
    var increaseButton = document.querySelector('div[data-replo-increase-product-quantity]');
    var decreaseButton = document.querySelector('div[data-replo-decrease-product-quantity]');
    if(increaseButton && decreaseButton){
        var commonParent = increaseButton.parentNode;
        var quantityDisplay = commonParent ? commonParent.querySelector('span[contenteditable="false"]') : null;
        
        if (!quantityDisplay) {
            console.error('Unable to find the quantity display span.');
            return;
        }
        var currentQuantity = parseInt(quantityDisplay.textContent, 10);
    
        var difference = value - currentQuantity;

        function adjustQuantity() {
            if (difference > 0) {
                increaseButton.click();
                difference--;
                if (difference > 0) {
                    setTimeout(adjustQuantity, 100); // Adjust the timeout as necessary
                }
            } else if (difference < 0) {
                decreaseButton.click();
                difference++;
                if (difference < 0) {
                    setTimeout(adjustQuantity, 100); // Adjust the timeout as necessary
                }
            }
        }
    
        adjustQuantity();
    }
}

//Update the selects in all the WideBundle widgets to change the selected values
wideBundle.updateSelectsInOffers = function(elementUpdated){
  var valueOfElement = elementUpdated.value;
  var classSelectors = Array.from(elementUpdated.classList);
  var classOfElement = '.' + classSelectors.join('.');

  for(var i=0; i<document.querySelectorAll("selectedWB" + classOfElement).length; i++){ //Update all the selects with this class
    document.querySelectorAll("selectedWB" + classOfElement)[i].value = valueOfElement;
  }
}

//Add the button that redirects to the checkout so we can click on it
wideBundle.addLinkToCheckout = function(){
    var checkoutLink = document.createElement('a');
    checkoutLink.id = "checkout-xx-aa";
    checkoutLink.href = getShopifyBaseUrl() + 'checkout';

    //Handle redirection if Transcy enabled
    if (typeof _transcy !== 'undefined' &&
        typeof _transcy.variants.localeCurrent !== 'undefined' &&
        typeof _transcy.variants.localeDefault !== 'undefined' &&
        _transcy.variants.localeCurrent !== _transcy.variants.localeDefault &&
        _transcy.variants.localeDefault !== '') {
            checkoutLink.href = `/${_transcy.variants.localeCurrent}/checkout`;
    }

    //Handle redirection if Weglot enabled
    if (typeof Weglot !== 'undefined' &&
        typeof Weglot.getCurrentLang() !== 'undefined' &&
        Weglot.getCurrentLang() !== '') {
            checkoutLink.href = `/checkout?locale=${Weglot.getCurrentLang()}`;
    }

    checkoutLink.innerHTML = 'checkout';
    document.body.append(checkoutLink);
}

//Regenerate WideBundle Widget if the theme replaced WideBundle
wideBundle.regenerateWideBundle = function(){
    if(typeof Shopify != "undefined"){
        var currentWidgetCreated = document.querySelector('#new-form');
        var intervalCheckingWidgetCount = 0;
        var checkCurrentWidget = setInterval(function(){ //Check for 8 seconds if the widget has been replaced
            if(typeof currentWidgetCreated !== "undefined" && currentWidgetCreated){
                newWidgetChecked = document.querySelector('#new-form');
                if(!currentWidgetCreated.isSameNode(newWidgetChecked)){ //If the widget has been replaced
                    currentWidgetCreated.remove();
                    newWidgetChecked.remove();
                    wideBundle.init(wideBundle.data);
                    clearInterval(checkCurrentWidget);
                }
            }
            intervalCheckingWidgetCount++;
            if(intervalCheckingWidgetCount >= 40){
                clearInterval(checkCurrentWidget);
            }
        }, 200);
    }
}

//Add the product to the cart (function called immediately after the click on the button)
wideBundle.addToCart = function(){
    if (window.hasOwnProperty("wideBundlePreviewMode") && window?.wideBundlePreviewMode === true) {
        console.log("[WideBundle] Skip add to cart action in preview mode...");
        return;
    }

    //Add the loading gif
    wideBundle.displayLoadingOnATC();

    wideBundle.showErrorIfNonExistingVariant(); //Show error if the variant doesn't exist on Shopify

    console.log('clicked on the button');
    //Get currency name
    currencyName = typeof window.ShopifyAnalytics !== "undefined"
        ? window.ShopifyAnalytics.meta.currency
        : typeof window.Shopify.currency !== "undefined"
            ? Shopify.currency.active
            : wideBundle.setting.currency_code;

    //Get infos about the variant to add
    var selectedOffer = wideBundle.getSelectedOffer();
    var selectedVariantId = wideBundle.getSelectedVariantId(true)[0];
    var quantityVariant = document.querySelector('.selectedWB .quantity-wb-input');
    var quantityVariantValue = quantityVariant ? Number(quantityVariant.value) : 1;
    var itemsToAddToCart = {items: [{quantity: quantityVariantValue, id: selectedVariantId}]};

    //test variable (apply sideCart without theme)
    let firstCartItem;

    if (selectedOffer.automatic_discount) {
        const offerGroup = wideBundle.offers[selectedOffer.offersPointer];
        const variantIds = wideBundle.getSelectedVariantId(true).slice();
        const giftVariantIds = wideBundle.getGiftVariantIds().slice();
        const abTestVariant = wideBundle.abTestEnabled ? wideBundle.retrieveAbTestVariant() : 'A';
        wideBundle.reportAbTestAddToCart(selectedOffer, abTestVariant);
        itemsToAddToCart.items = [];

        const userTextWrapper = wideBundle.activeWidget.querySelector(".selectedWB .wb-user-text-wrapper");
        const userTextInput = wideBundle.activeWidget.querySelector(".selectedWB .input-user-text");
        let userTextProperty = null;
        let userTextValue = null;
        if (offerGroup[0].user_text_enabled && userTextInput) {
            userTextProperty = offerGroup[0].user_text_property;

            if (offerGroup[0].user_text_required && !userTextInput.reportValidity()) {
                userTextValue = null;
                userTextWrapper?.classList?.add("wb-user-text-wrapper--has-error");
                wideBundle.removeLoadingOnATC();
                return;
            } else {
                userTextValue = userTextInput.value.trim();
                userTextInput.value = "";
                userTextWrapper?.classList?.remove("wb-user-text-wrapper--has-error");
            }
        }

        offerGroup.forEach((currentOffer, currentOfferIndex) => {
            for (let i = 0; i < currentOffer.product_qty; i++) {
                // Upsell checkbox logic
                const upsellCheckbox = wideBundle.activeWidget.querySelector(`input[type="checkbox"][data-upsell-id="${currentOffer.offer_uuid}"]`);
                if (currentOffer.product_is_upsell && upsellCheckbox && !upsellCheckbox.checked) {
                    wideBundle.removeLoadingOnATC();
                    return; // Skip this item if upsell checkbox is unchecked
                }

                const id = Number(variantIds.shift());
                const quantity = quantityVariantValue;
                const properties = {};
                
                if (wideBundle.abTestExcludeOffers.length > 0) {
                    properties["__wide-bundle-excl-offers"] = wideBundle.abTestExcludeOffers.join(",");
                }
                properties["__wide-bundle-variant"] = `${abTestVariant}:${currentOffer.offer_db_id}:${currentOffer.index}`;
               
                if (currentOfferIndex > 0 && (
                    (giftVariantIds.includes(id) && currentOffer.product_is_gift) || currentOffer.product_is_upsell
                )) {
                    properties["__wide-bundle-gift-variant"] = id;
                }
                if (currentOffer.dynamicGroupSelected !== null) {
                    properties["__wide-bundle-dyn-group"] = "dyn/" + currentOffer.dynamicGroupUuid;
                }
                if (userTextProperty !== null && userTextValue !== null) {
                    properties[userTextProperty] = userTextValue;
                }

                itemsToAddToCart.items.push({
                    id,
                    quantity,
                    properties,
                });
            }
        });

        //validation, if we send all prods using fetch and one add manually to sideCart
        if (wideBundle.settings.link_choice == "form" && itemsToAddToCart.items.length > 1) {
            firstCartItem = itemsToAddToCart.items.shift();
        }
    }

    const atcButtons = Array.from(document.querySelectorAll('.new-form-atc'));
    //Disable click
    atcButtons.forEach(function (atcButton) {
        atcButton.style.pointerEvents = 'none';
    });

    wideBundle.updateQuantityDisabled(quantityVariantValue).then(function (continueAddToCart) {
        if (!continueAddToCart) {
            return;
        }

        if(wideBundle.settings.link_choice == "form"){ //If the user selected "side cart" redirection

            wideBundle.showErrorIfSideCart(); //Show error if the user didn't add add-to-cart button and variants selector

            if (selectedOffer.automatic_discount) {
                // Convert theme's native variant id input into array-like field
                wideBundle.convertHiddenIdInputToArray();
            }
            wideBundle.updateVariantIdSelector(selectedVariantId); //Update the <select> in the form with name = id
            wideBundle.manageEcomSolidSideCart(itemsToAddToCart); //Open Ecom Solid Side Cart
            wideBundle.handleUploadApps(); //Handle upload apps (like Uploadlift) so we can send the file to the cart
            var addToCartButton = wideBundle.getAddToCartButton();
            if(addToCartButton){
                if (selectedOffer.automatic_discount && firstCartItem) {

                    //change id after fetch applying
                    wideBundle.updateVariantIdSelector(firstCartItem.id); //Update the <select> in the form with name = id

                    wideBundle.addToCartAjax(itemsToAddToCart)
                        .then(function(responseText) {
            
                            //Manage an upsell app to open the app after the product was added to the cart
                            if(typeof initiateRaidFunnelByVariant !== 'undefined'){
                                if(initiateRaidFunnelByVariant(selectedVariantId) == true){
                                    return Promise.resolve();
                                }
                            }
                            //Manage an upsell app to open the app after the product was added to the cart
                            else if(typeof app !== 'undefined' && typeof app.showModal !== 'undefined'){
                                app.showModal = true;
                                app.configs[0].value=app.getThemeQuantity();
                                app.isCart=false;
                                //Put back WideBundle button text
                                wideBundle.removeLoadingOnATC();
                            }

                            document.body.click();
                            if(addToCartButton.element.disabled){
                                addToCartButton.element.disabled = false;
                            }
                            addToCartButton.element.click();
                            wideBundle.handleSlideCartApp; //Open slide cart app
                            if (selectedOffer.automatic_discount) {
                                // Convert theme's native variant id input back to field
                                wideBundle.convertHiddenIdInputToField();
                            }

                            //Put back WideBundle button text
                            wideBundle.removeLoadingOnATC();


                            return Promise.resolve();
                        })
                        .catch(function(error) {
                            console.error(error);
                            if (error.cause && error.cause == 422) {
                                const atcButtons = Array.from(document.querySelectorAll('.new-form-atc'));
                                atcButtons.forEach(function (atcButton) {
                                    atcButton.classList.add('new-form-atc--out-of-stock');
                                    atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_content_text);
                                    atcButton.style.pointerEvents = 'none';
                                });
                                return Promise.resolve();
                            } else {
                                return Promise.reject(error);
                            }
                        });
                } else {
                    document.body.click();
                    if(addToCartButton.element.disabled){
                        addToCartButton.element.disabled = false;
                    }
                    addToCartButton.element.click();
                    wideBundle.handleSlideCartApp; //Open slide cart app
                    if (selectedOffer.automatic_discount) {
                        // Convert theme's native variant id input back to field
                        wideBundle.convertHiddenIdInputToField();
                    }

                    //Put back WideBundle button text
                    wideBundle.removeLoadingOnATC();
                }
            }
        }
        else{ //If the user selected "checkout" or "cart" redirection
            var redirectionUrl = getShopifyBaseUrl() + wideBundle.settings.link_choice;
            wideBundle.managePixels(currencyName); //Manage pixels (Facebook, Google, etc)
            wideBundle.addToCartAjax(itemsToAddToCart)
                .then(function(responseText) {
    
                    //Manage an upsell app to open the app after the product was added to the cart
                    if(typeof initiateRaidFunnelByVariant !== 'undefined'){
                        if(initiateRaidFunnelByVariant(selectedVariantId) == true){
                          return;
                        }
                    }
                    //Manage an upsell app to open the app after the product was added to the cart
                    else if(typeof app !== 'undefined' && typeof app.showModal !== 'undefined'){
                        app.showModal = true;
                        app.configs[0].value=app.getThemeQuantity();
                        app.isCart=false;
                        //Put back WideBundle button text
                        wideBundle.removeLoadingOnATC();
                    }
                    //If the user redirects to checkout
                    else if(wideBundle.settings.link_choice == "checkout"){
                        if(document.querySelector('#checkout-xx-aa')){
                            document.body.click(); //Manage the double click problem on some themes
                            document.querySelector('#checkout-xx-aa').click();
    
                            //Put back WideBundle button text
                            wideBundle.removeLoadingOnATC();
                        }
                    }
                    //If the user redirects to cart
                    else if(wideBundle.settings.link_choice == "cart"){
                        if (typeof _transcy !== 'undefined' &&
                            typeof _transcy.variants.localeCurrent !== 'undefined' &&
                            typeof _transcy.variants.localeDefault !== 'undefined' &&
                            _transcy.variants.localeCurrent !== _transcy.variants.localeDefault &&
                            _transcy.variants.localeDefault !== '') {
                                credirectionUrl = `/${_transcy.variants.localeCurrent}/cart`;
                        }
                        //Put back WideBundle button text
                        wideBundle.removeLoadingOnATC();
                        window.location = redirectionUrl;
                    }
    
                    return Promise.resolve();
                })
                .catch(function(error) {
                    console.error(error);
                    if (error.cause && error.cause == 422) {
                        const atcButtons = Array.from(document.querySelectorAll('.new-form-atc'));
                        atcButtons.forEach(function (atcButton) {
                            atcButton.classList.add('new-form-atc--out-of-stock');
                            atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_content_text);
                            atcButton.style.pointerEvents = 'none';
                        });
                        return Promise.resolve();
                    } else {
                        return Promise.reject(error);
                    }
                });
        }
    });
}

function wbCheckVariantsInventoryAvailability() {
    return new Promise((resolve, reject) => {
        const checkInterval = setInterval(() => {
            if (wideBundle.variantsInventory !== undefined && Object.keys(wideBundle.variantsInventory).length > 0) {
                clearInterval(checkInterval);
                resolve(wideBundle.variantsInventory);
            }
        }, 100);

        setTimeout(() => {
            clearInterval(checkInterval);
            reject(new Error(`Variants inventory was not found within the time limit.`));
        }, 10000);
    });
}

wideBundle.reportAbTestAddToCart = function(offer, variant) {
    const fetchUrl = new URL(wideBundle.domain + 'abTest.php');
    fetchUrl.searchParams.set('id', offer.offer_db_id);
    fetchUrl.searchParams.set('index', offer.index);
    fetchUrl.searchParams.set('abTestVariant', variant);
    window.originalFetch(fetchUrl.toString(), {
        mode: 'cors',
    }).then(response => {
        if (response.ok) {
            return response.text();
        } else {
            throw new Error(response.statusCode, { cause: response.status });
        }
    }).then(data => {
        console.log('A/B report response:', data);
    }).catch(error => {
        throw error;
    });
}

//Create the button out of stock if enabled and if the variant is out of stock
wideBundle.updateQuantityDisabled = async function(quantity = 1, showSpinner = true) {
    if (Number(wideBundle.settings.enable_atc_button) !== 1 && wideBundle.isAutomaticDiscount == false) {
        return true;
    }

    if(!wideBundle.isAutomaticDiscount){
        showSpinner = true;
    }

    try {
        showSpinner && wideBundle.displayLoadingOnATC();
        const selectedVariantIds = wideBundle.isAutomaticDiscount ? wideBundle.getSelectedVariantId(true) : [wideBundle.getSelectedVariantId(true)[0]];
        const bundleQuantities = selectedVariantIds.reduce((variants, variantId) => {
            if (variants[variantId]) {
                variants[variantId] += quantity;
                return variants;
            }

            return {
                ...variants,
                [variantId]: quantity,
            };
        }, {});
        const atcButtons = Array.from(document.querySelectorAll('.new-form-atc'));

        let data = {
            inventory_quantity: 0,
            add_to_cart_btn_enable: 0,
        };

        if (wideBundle.isAutomaticDiscount) {
            let variantsInventory = {};
            if (window.hasOwnProperty("wideBundlePreviewMode") && window?.wideBundlePreviewMode === true) {
                selectedVariantIds.forEach(variant_id => {
                    variantsInventory[variant_id] = {
                        inventory_quantity: 999999,
                        add_to_cart_btn_enable: '1'
                    };
                });
            } else {
                variantsInventory = await wbCheckVariantsInventoryAvailability();
            }

            for (let i = 0; i < selectedVariantIds.length; i++) {
                const variantId = selectedVariantIds[i];
                const inventoryQuantity = Number(variantsInventory?.[variantId]?.inventory_quantity ?? 0);
                const addToCartBtnEnable = Number(variantsInventory?.[variantId]?.add_to_cart_btn_enable ?? 0);

                if (bundleQuantities[variantId] > inventoryQuantity || addToCartBtnEnable === 0) {
                    data.inventory_quantity = 0;
                    data.add_to_cart_btn_enable = 0;
                    break;
                } else {
                    data.inventory_quantity += inventoryQuantity;
                    data.add_to_cart_btn_enable = 1;
                }
            }
        } else {
            const fetchUrl = new URL(wideBundle.domain + 'storefront/getvariantinventory');
            fetchUrl.searchParams.set('variant_ids', selectedVariantIds[0]);
            const response = await window.originalFetch(fetchUrl.toString(), { mode: 'cors' });
            const fetchData = await response.json();
            data = fetchData;
        }

        // Revert original buttons state
        atcButtons.forEach(function (atcButton) {
            atcButton.classList.remove('new-form-atc--out-of-stock');
            var atcText = wideBundle.getTranslatedText(wideBundle.settings.atc_text);
            if(atcText && (atcText.includes('{{price}}') || atcText.includes('{{compare-price}}'))){
                var priceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.first-price-WB') : null;
                var comparePriceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.second-price-WB') : null;
                var price = priceEl ? priceEl.outerHTML : '';
                var comparePrice = comparePriceEl ? comparePriceEl.outerHTML : '';
                atcText = atcText.replace(/{{price}}/g, price);
                atcText = atcText.replace(/{{compare-price}}/g, comparePrice);
            }
            atcButton.innerHTML = AddSVG()+atcText;
            atcButton.style.pointerEvents = 'auto';
        });

        if (data === false) {
            return false;
        }

        let enableButton = Number(data.add_to_cart_btn_enable) === 1;
        let continueSelling = true;
        if (Number(quantity) > 1 && Number(quantity) > Number(data.inventory_quantity)) {
            continueSelling = false;
        }
        let selectedOffer = wideBundle.getSelectedOffer();
        let hasAllGroups = wideBundle.offers[selectedOffer.offersPointer].reduce((a, p) => a + (p.dynamicGroupSelected !== null ? 1 : 0), 0) === selectedOffer.dynamicGroups.length;

        if (enableButton && continueSelling && hasAllGroups) {
            return true;
        } else {
            atcButtons.forEach(function (atcButton) {
                atcButton.classList.add('new-form-atc--out-of-stock');
                atcButton.style.pointerEvents = 'none';
                if (!hasAllGroups) {
                    atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_text);
                } else {
                    atcButton.innerHTML = wideBundle.getTranslatedText(wideBundle.settings.atc_content_text);
                }
            });

            return false;
        }
    } catch (error) {
        console.error(error);
        return false;
    }
}

//Open the side cart of the app Slide Cart
wideBundle.handleSlideCartApp = function(){
    try{
        if(typeof window.SLIDECART_UPDATE != "undefined"){
          setTimeout(() => {
            if(!window.SLIDECART_STATE().open){
              window.SLIDECART_UPDATE();
              window.SLIDECART_OPEN();
            }
          },
          600);
        }
      }catch(error){
        console.error(error);
      }
}

// Cache target product variant IDs
wideBundle.getTargetVariantIds = function() {
    if (!wideBundle._targetVariantIds) {
        wideBundle._targetVariantIds = new Set(
            wideBundle.data
                .filter(v => v.handle === wideBundle.currentHandle)
                .map(v => v.variant_id)
        );
    }
    return wideBundle._targetVariantIds;
}

/**
 * Get cart items with their properties for automatic discount bundles.
 * Returns an array of cart items including variant IDs and associated properties
 * (A/B test, gifts, dynamic groups, etc.)
 *
 * @returns {Array<{id: number, quantity: number, properties: Object}>} - Array of cart items with properties
 */
wideBundle.getAutomaticDiscountCartItems = function() {
    const selectedOffer = wideBundle.getSelectedOffer();

    // Only works for automatic discount bundles
    if (!selectedOffer || !selectedOffer.automatic_discount) {
        return [];
    }

    // Get quantity from DOM
    const quantityInput = document.querySelector('.selectedWB .quantity-wb-input');
    const quantity = quantityInput ? Number(quantityInput.value) : 1;

    const offerGroup = wideBundle.offers[selectedOffer.offersPointer];
    const variantIds = wideBundle.getSelectedVariantId(true).slice();
    const giftVariantIds = wideBundle.getGiftVariantIds().slice();
    const abTestVariant = wideBundle.abTestEnabled ? wideBundle.retrieveAbTestVariant() : 'A';
    
    const cartItems = [];
    
    offerGroup.forEach((currentOffer, currentOfferIndex) => {
        for (let i = 0; i < currentOffer.product_qty; i++) {
            const id = Number(variantIds.shift());
            const properties = {};
            
            if (wideBundle.abTestExcludeOffers.length > 0) {
                properties["__wide-bundle-excl-offers"] = wideBundle.abTestExcludeOffers.join(",");
            }
            properties["__wide-bundle-variant"] = `${abTestVariant}:${currentOffer.offer_db_id}:${currentOffer.index}`;
            
            // Gift variant properties
            if (currentOfferIndex > 0 && giftVariantIds.includes(id) && currentOffer.product_is_gift) {
                properties["__wide-bundle-gift-variant"] = id;
            }
            
            // Dynamic group properties
            if (currentOffer.dynamicGroupSelected !== null) {
                properties["__wide-bundle-dyn-group"] = "dyn/" + currentOffer.dynamicGroupUuid;
            }
            
            cartItems.push({
                id,
                quantity,
                properties,
            });
        }
    });
    
    return cartItems;
}

// Check for Recurpay subscription
wideBundle.getRecurpaySubscription = function() {
    const groupMain = document.querySelector('[name="recurpay__group_main"]');
    if (!groupMain || !groupMain.checked || groupMain.value !== "subscription") {
        return null;
    }

    const selectedOption = document.querySelector('[name="recurpay-input"]').selectedOptions[0];
    if (!selectedOption) return null;

    return {
        selling_plan: selectedOption.dataset.sellingPlan,
        planName: selectedOption.dataset.planName
    };
}

// Apply subscription to cart item if it's from target product
wideBundle.applySubscriptionToItem = function(item, subscription) {
    if (!subscription || !wideBundle.getTargetVariantIds().has(item.id)) {
        return item;
    }

    return {
        ...item,
        selling_plan: subscription.selling_plan,
        properties: {
            Plan: subscription.planName,
            _PlanId: subscription.selling_plan,
        }
    };
}

// Modified addToCartAjax to handle subscriptions
wideBundle.addToCartAjax = function(itemsToAddToCart) {
    const subscription = wideBundle.getRecurpaySubscription();
    const selectedOffer = wideBundle.getSelectedOffer();
    
    if (subscription && selectedOffer.automatic_discount) {
        itemsToAddToCart.items = itemsToAddToCart.items.map(item => 
            wideBundle.applySubscriptionToItem(item, subscription)
        );
    }

    return window.originalFetch("/cart/add.js", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(itemsToAddToCart)
    }).then(response => {
        if (response.ok) {
            return response.text();
        } else {
            throw new Error(response.statusCode, { cause: response.status });
        }
    }).catch(error => {
        throw error;
    });
}

//Handle Ecom Solid Side cart
wideBundle.manageEcomSolidSideCart = function(itemsToAddToCart){
    if(typeof window.SOLID != 'undefined'){
        isGemPages = wideBundle.formInfo.element.closest('[class^=\'gt_section-\'][data-name], [class^=\'gf_section-\'][data-name], [class^=\'gt_widget-\'][data-name], [class^=\'gt_element-\'][data-name]');
        if(isGemPages){
            wideBundle.managePixels();

            wideBundle.addToCartAjax(itemsToAddToCart)
                .then(async function(responseText) {
                    await window.SOLID.cart.GetCart();
                    window.SOLID.store.dispatch('addToCartSuccess');
                    window.SOLID.store.dispatch('openCartPopup', 'cart_drawer');
                    return Promise.resolve();
                })
                .catch(function(error) {
                    console.error(error);
                    return Promise.reject(error);
                });
        }
      }
}

//Send pixel events to Facebook, Google, etc
wideBundle.managePixels = function(currencyName){
    let priceAmount;
    const selectedOffer = wideBundle.getSelectedOffer();
    const selectedVariantIds = wideBundle.getSelectedVariantId(true);

    if (selectedOffer.automatic_discount) {
        // For automatic discount bundles, look for the calculated price
        const variantIdsString = selectedVariantIds.join('+');
        const calculatedPriceElement = document.querySelector(
            `.wb_hidden_prices .wb_hidden_prices_element[data-calculated] .wb_hidden_price[variant-id="${selectedOffer.offersPointer}@${variantIdsString}"]`
        );
        
        if (calculatedPriceElement) {
            priceAmount = parseFloat(
                wideBundle.getAmountFromPrice(calculatedPriceElement.innerHTML)
            ).toFixed(2);
        }
    } else {
        // Legacy single variant system
        const priceElement = document.querySelector(
            `.wb_hidden_prices .wb_hidden_price[variant-id="${selectedVariantIds[0]}"]`
        );
        if (priceElement) {
            priceAmount = parseFloat(
                wideBundle.getAmountFromPrice(priceElement.innerHTML)
            ).toFixed(2);
        }
    }


    if(wideBundle.settings.add_pixel){ //Facebook Pixel
        if(typeof window.fbq !== 'undefined'){
            if(typeof meta != "undefined" && typeof meta.product !== 'undefined'){
                for(var metaVariant in meta.product.variants){
                    if(meta.product.variants[metaVariant].id == wideBundle.getSelectedVariantId(true)[0]){
                        priceAmount = meta.product.variants[metaVariant].price / 100;
                        window.fbq('track', 'AddToCart', {
                            value: priceAmount.toFixed(2),
                            currency: currencyName
                        });
                    }
                    }
                }
                else{
                    price = document.querySelector('.wb_hidden_prices .wb_hidden_price[variant-id="'+wideBundle.getSelectedVariantId(true)[0]+'"]');
                    window.fbq('track', 'AddToCart', {
                        value: priceAmount,
                        currency: currencyName
                    });
            }
        }

        //Pinterest Pixel
        if(typeof window.pintrk !== 'undefined'){
            console.log('pinterest pixel found');
            pintrk('track', 'addtocart', {
                value: priceAmount,
                currency: currencyName
            });
        }
    }

    //Snap pixel
    if(typeof window.snaptr !== 'undefined'){
        snaptr('track', 'ADD_CART', {'currency': currencyName, 'price': priceAmount, 'item_category': '', 'item_ids': [] });
    }

    //Tiktok Pixel
    if(typeof window.ttq !== 'undefined'){
        ttq.track('AddToCart');
    }

    //Outbrain pixel
    if(typeof window.obApi !== 'undefined'){
        obApi('track', 'Add To Cart');
    }

    //Taboola Pixel
    if(typeof _tfa !== 'undefined'){
        _tfa.push({notify: 'event', name: 'add_to_cart'});
    }

    //Klaviyo
    if(typeof _learnq != "undefined"){
        fetch(`${window.location.origin}/cart.js`)
        .then(res => res.clone().json().then(data => {
            var cart = {
                total_price: data.total_price/100,
                $value: data.total_price/100,
                total_discount: data.total_discount,
                original_total_price: data.original_total_price/100,
                items: data.items
            }
            if (typeof item != 'undefined') {
                cart = Object.assign(cart, item)
            }
            console.log(cart);
            _learnq.push(['track', 'Added to Cart', cart]);
        }))
    }
}

//Show the loading gif on the add to cart button
wideBundle.displayLoadingOnATC = function(){
    loadingHTML = `<img class="loading-wb" src='${GetLoadingGifBase64()}' width="20px" height="20px" />`;
    if(document.querySelector('#new-form-atc')){
        document.querySelector('#new-form-atc').innerHTML = loadingHTML;
    }
    for(var i=0; i<document.querySelectorAll('.new-form-atc').length; i++){
        document.querySelectorAll('.new-form-atc')[i].innerHTML = loadingHTML;
    }
    if(document.querySelector('#checkout-xx-aa')){
        document.querySelector('#checkout-xx-aa').style.display = "block";
    }
}

//Put back the text to the add to cart button
wideBundle.removeLoadingOnATC = function(){
    setTimeout(function(){
        if(document.querySelector('#new-form-atc')){
            document.querySelector('#new-form-atc').style.pointerEvents = 'auto';
        }
        for(var i=0; i<document.querySelectorAll('.new-form-atc').length; i++){
            document.querySelectorAll('.new-form-atc')[i].style.pointerEvents = 'auto';
        }
        var atcText = wideBundle.getTranslatedText(wideBundle.settings.atc_text);
        if(atcText && (atcText.includes('{{price}}') || atcText.includes('{{compare-price}}'))){
            var priceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.first-price-WB') : null;
            var comparePriceEl = wideBundle.activeWidget ? wideBundle.activeWidget.querySelector('.selectedWB .price-new-form span.second-price-WB') : null;
            var price = priceEl ? priceEl.outerHTML : '';
            var comparePrice = comparePriceEl ? comparePriceEl.outerHTML : '';
            atcText = atcText.replace(/{{price}}/g, price);
            atcText = atcText.replace(/{{compare-price}}/g, comparePrice);
        }
        var atcHtml = AddSVG()+atcText;
        for(var j=0; j<document.querySelectorAll('.new-form-atc').length; j++){
            document.querySelectorAll('.new-form-atc')[j].innerHTML = atcHtml;
        }
        if(document.querySelector('#checkout-xx-aa')){
            document.querySelector('#checkout-xx-aa').style.display = "none";
        }
    }, 2000);
}

wideBundle.convertHiddenIdInputToArray = function() {

    //test return
    return;



    const formNode = wideBundle.getFormNode();
    if (!formNode.element) return;

    const hiddenId = formNode.element.querySelector(`[type="hidden"][name="id"]:not([data-wb-id]),[type="hidden"][name="_wb-id-disabled"]:not([data-wb-id])`);
    if (!hiddenId) return;

    if (wideBundle.getOfferWithTargetProduct()) {
        hiddenId.name = "id[]";
    } else {
        hiddenId.name = "_wb-id-disabled";
    }
}

wideBundle.convertHiddenIdInputToField = function() {

    //test return
    return;



    const formNode = wideBundle.getFormNode();
    if (!formNode.element) return;

    const hiddenId = formNode.element.querySelector(`[type="hidden"][name="id[]"]:not([data-wb-id]),[type="hidden"][name="_wb-id-disabled"]:not([data-wb-id])`);
    if (!hiddenId) return;

    hiddenId.name = "id";
}

//Handle upload apps (like Uploadlift) so we can send the file to the cart
wideBundle.handleUploadApps = function(){
    if(wideBundle.formInfo.element){
        if(document.querySelector('#new-form .upload-container')){ //Handle Upload Kit App
          UploadKitElementsInForm = wideBundle.formInfo.element.querySelectorAll('.wb-uploadlift');
          UploadKitElementsInForm.forEach(UploadKitElementInForm => {
            UploadKitElementInForm.remove();
          });
          elementsInUploadKit = document.querySelectorAll('#new-form .upload-container *');
          elementsInUploadKit.forEach(elementInUploadKit => {
            if(typeof elementInUploadKit != "undefined" && typeof elementInUploadKit.getAttribute != "undefined" && elementInUploadKit.getAttribute("name") != null && elementInUploadKit.getAttribute("name").indexOf('properties') == 0){
              newNode = elementInUploadKit.cloneNode();
              newNode.style.display = "none";
              newNode.classList.add('wb-uploadlift');
              wideBundle.formInfo.element.append(newNode);
            }
          });
        }
      }
}

//Update the <select> in the form (name = id) with another variant ID
wideBundle.updateVariantIdSelector = function(variantId){
    variantIdSelector = wideBundle.formInfo.element.querySelector('[name="id"]');
    let variantSelectorAddedByWB =  wideBundle.formInfo.element.querySelectorAll('.wb-variant-selector[name="id"]')
    variantIdSelectorArray = wideBundle.formInfo.element.querySelector('[name="id[]"]');
    if(variantIdSelector){
      var options = variantIdSelector.querySelectorAll('option');
      for(var i = 0; i < options.length; i++){
        if(options[i].value == variantId){
          options[i].selected = true;
        }
      }
      variantIdSelector.value = variantId;
      if(variantSelectorAddedByWB.length > 0){
        variantSelectorAddedByWB.forEach(variantIdSelector => {
          var options = variantIdSelector.querySelectorAll('option');
          for(var i = 0; i < options.length; i++){
            if(options[i].value == variantId){
              options[i].selected = true;
            }
          }
          variantIdSelector.value = variantId;
        })
      }
    }
    else if(!variantIdSelectorArray){ //Create ourselves the element
        let input = document.createElement('input');
        input.setAttribute("type", "hidden");
        input.setAttribute("name", "id");
        input.setAttribute("value", variantId);
        input.classList.add("wb-variant-selector");
        if(wideBundle.formInfo.element){
            old_input = wideBundle.formInfo.element.querySelectorAll('.wb-variant-selector'); //Remove old one
            for(var a=0; a<old_input.length; a++){
                old_input[a].remove();
            }
            wideBundle.formInfo.element.appendChild(input);
            var inputCopy = input.cloneNode(true);
            if(!window.openCart){ //Don't add the second one if the app MonsterUpsell is enabled on the store
              wideBundle.formInfo.element.insertBefore(inputCopy, wideBundle.formInfo.element.firstChild);
            }
            return true;
        }
    }
    return false;
}

//Display error if the user is on side cart redirection without add to cart and/or variants selector
wideBundle.showErrorIfSideCart = function(){
    //For GemPages variants selector and atc button
    var message = "";
    const offerIsAutomaticDiscount = wideBundle.getSelectedOffer().automatic_discount;
    if (offerIsAutomaticDiscount) return false;

    if((!wideBundle.getVariantsSelector() || !wideBundle.getAddToCartButton()) &&
    ((document.querySelector(".gf_row") && document.querySelector('body.gempage') && document.querySelector("div[data-label='Product']")) ||
        (document.querySelector('div[label="Block"]') && document.querySelector('gp-product')))
    ){
        if(!wideBundle.getVariantsSelector() && !wideBundle.getAddToCartButton()){
            message = "You need to add the variants selector and add-to-cart button from GemPages when side cart redirection is selected.";
        }
        else if(!wideBundle.getVariantsSelector()){
            message = "You need to add the variants selector from GemPages when side cart redirection is selected.";
        }
        else if(!wideBundle.getAddToCartButton()){
            message = "You need to add the add-to-cart button from GemPages when side cart redirection is selected.";
        }
        wideBundle.createError(message, "https://help.widebundle.com/en/article/how-to-use-the-side-cart-with-gempages-2q8d7q/#3-1-add-the-variant-selector-the-add-to-cart-button-and-the-quantity-selector")
        return true;
    }

    //For PageFly variants selector and atc button
    else if((!wideBundle.getVariantsSelector() || !wideBundle.getAddToCartButton()) && document.querySelector("div[data-pf-type='Body']")){
        wideBundle.createError("You have to use WideBundle's module from PageFly.", "https://help.widebundle.com/en/article/how-to-use-widebundle-with-pagefly-suqsj9/#2-add-the-widebundle-module")
        if(!wideBundle.getVariantsSelector() && !wideBundle.getAddToCartButton()){
            message = "You need to add the variants selector and add-to-cart button from PageFly when side cart redirection is selected.";
        }
        else if(!wideBundle.getVariantsSelector()){
            message = "You need to add the variants selector from PageFly when side cart redirection is selected.";
        }
        else if(!wideBundle.getAddToCartButton()){
            message = "You need to add the add-to-cart button from PageFly when side cart redirection is selected.";
        }
        wideBundle.createError(message, "https://help.widebundle.com/en/article/how-to-use-the-side-cart-with-pagefly-5q1ou9/#3-1-add-the-variant-selector-the-add-to-cart-button-and-the-quantity-selector")
        return true;
    }

    //For normal themes variants selector and atc button
    else if(!wideBundle.getAddToCartButton()){
        message = "You need to add the add-to-cart button in your theme when side cart redirection is selected.";
        wideBundle.createError(message, "https://help.widebundle.com/en/article/how-to-add-add-to-cart-button-in-your-theme-1lq4a2b/")
        return true;
    }
    else if(!wideBundle.getVariantsSelector()){
        message = "You need to add the variants selector in your theme when side cart redirection is selected.";
        wideBundle.createError(message, "https://help.widebundle.com/en/article/how-to-add-a-variant-selector-in-my-theme-1q74hv4/")
        return true;
    }
    
    return false;
}

//Show Error if the variant doesn't exist
wideBundle.showErrorIfNonExistingVariant = function(){
    if(typeof wideBundle.variantsOnShopify != "undefined"){
        var variantExisting = 0;
        for(var i = 0; i<wideBundle.variantsOnShopify.length; i++){
            var currentVariant = wideBundle.variantsOnShopify[i];
            if(typeof currentVariant["id"] != "undefined" && currentVariant["id"] == wideBundle.getSelectedVariantId(true)[0]){
                variantExisting = 1;
                break;
            }
        }
        if(!variantExisting){
            message = "This variant doesn't exist on Shopify.";
            wideBundle.createError(message, "https://help.widebundle.com/en/article/i-have-the-error-this-variant-doesnt-exist-on-shopify-5lci9m/")
            return true;
        }
    }
    return false;
}
//Init WideBundle Widget
wideBundle.init = function(data){
    console.log("WideBundle init started");
    console.time("loading all WB");
    wideBundle.userTexts = {};
    wideBundle.transformMainElement(); //If we only have secondary widgets we create one main with HD
    wideBundle.declareVariables(); //We declare the variables we need
    wideBundle.getOffersData(data); //We structure the offers data
    wideBundle.getVariantsInventory();
    wideBundle.priceInfo = wideBundle.getPriceNode(); //We get the price node and the price id if the user enabled the update price design
    if(wideBundle.priceInfo.element.length > 0){
        wideBundle.replacePriceIdInDB(); //We replace the price id in the database
        wideBundle.hideUnwantedPrices(); //We hide prices duplicated if the user enabled the update price design
    }
    wideBundle.replaceSelectedPrice(); //For some exceptions we will replace the price we have in priceInfo

    wideBundle.formInfo = wideBundle.getFormNode(); //Get the form node and the form id so we can replace it with WB widget
    wideBundle.replaceSelectedForm(); //For some exceptions we will replace the form we have in formInfo
    wideBundle.manualWidget = wideBundle.getManualWidget(); //Get the widget if added manually (usually for page builders) or null
    wideBundle.secondaryWidgets = wideBundle.getSecondaryWidgets(); //Get other widebundle in the page using class
    Object.defineProperty(wideBundle, "activeWidget", {
        get: function() {
            if (this.hasOwnProperty("_lastActiveWidget") && this._lastActiveWidget !== null) {
                return this._lastActiveWidget;
            } else if (this.hasOwnProperty("widgetContainers") && this.widgetContainers[0]) {
                return this.widgetContainers[0];
            } else {
                return null;
            }
        },
        configurable: true
    });

    //Hide elements only if there is form
    if(wideBundle.formInfo.element){
        wideBundle.replaceFormIdInDB(); //We replace the form id in the database
        wideBundle.hideElementsOutsideProductForm(); //We hide elements we don't want in the product form found
        wideBundle.hideReplo(); //Replo Page builder need special treatment
        if(!wideBundle.manualWidget){
          wideBundle.showElementsFromProductForm(); //We show elements that WideBundle hides in the product form using a JS function
        }
        wideBundle.showAndHideElementsWithInterval(); //Other elements that should be shown/hidden with specific system (like eventListeners)
    }
    else if(wideBundle.manualWidget){ //If there is no form but there is a manual widget we will use the form id of the manual widget
        wideBundle.formInfo.element = wideBundle.manualWidget;
        wideBundle.replaceFormIdInDB();
        wideBundle.hideReplo(); //Replo Page builder need special treatment
        //wideBundle.hideElementsOutsideProductForm(); //We hide elements we don't want in the product form found
    }
    if(wideBundle.formInfo.element || wideBundle.manualWidget){ //If we found a product form or a manual widget
        window.formWB = wideBundle.formInfo.element; //We set the formWB variable to the form we found
        window.form = wideBundle.formInfo.element; //We set the form variable to the form we found

        const hiddenIdInput = wideBundle.formInfo.element?.querySelector("[type='hidden'][name='id']");
        wideBundle.hiddenIdBackup = hiddenIdInput ? Number(hiddenIdInput.value) : null;
        if(!wideBundle.manualWidget){
            wideBundle.widgetContainers.push(wideBundle.createWidgetContainer()); //We create the container for the widget
        }
        else{
            wideBundle.widgetContainers.push(wideBundle.manualWidget); //We use the container for the widget that was manually added
        }

        Array.prototype.push.apply(wideBundle.widgetContainers, wideBundle.secondaryWidgets); //We add the secondary widgets to the widgetContainers array
        wideBundle.addHiddenPrices(); //Add prices of the offers to hidden div so we can use them later

        for(var i = 0; i < wideBundle.widgetContainers.length; i++){ //For each widget container
            var widgetContainer = wideBundle.widgetContainers[i];
            wideBundle.createWidgetContent(widgetContainer); //We create the content of the widget
        }
        wideBundle.loadGoogleFonts(); //Function to create tags <link> for all used Google fonts
        wideBundle.addMainStyle(); //We add the main css style of WideBundle
        wideBundle.addStructureStyle(); //We add the css style for quantity buttons and layout structure used
        wideBundle.preselectOffer(); //Select at least one offer
        wideBundle.addPricesFromAjax(); //If we couldn't get prices from json we will get them from ajax and replace them
        wideBundle.addLinkToCheckout(); //Add the link for the checkout to make it work
        if (!wideBundle.isAutomaticDiscount) {
            wideBundle.updatePricesInOffer(); //Update prices in the widget based on the offer selected
        }
        wideBundle.addBlinkingEffect(); //Add the blinking effect to the widget (for custom sentences)
        addStyleToPage(wideBundle.settings.custom_css, 'custom'); //Add custom css added in the admin dashboard
        wideBundle.regenerateWideBundle(); //Regenerate WideBundle if for some reason the widget isn't working
        wideBundle.updateVariantSelectedInFormWithConditions(); //Update the offer selected (based on url)
        wideBundle.runTranslationApps(); //Run translations
        wideBundle.takeAppsOut(); //Take out some apps from the product form. These apps usually load later and are more complex to take out than basic elements
        wideBundle.handleErrorsPageBuilders();
        wideBundle.updateQuantityDisabled();
        wideBundle.updateDiagonalOffer();
        wideBundle.getVariantsOnShopify(); //Get the variants of the product from Shopify
        setupReleaseItProducts();
        wideBundle.initDynamicGroups();
        const appLoadedEvent = new Event('widebundle:loaded'); //Send event that WB loaded
        document.dispatchEvent(appLoadedEvent);
        setTimeout(() => {
            if (!wideBundle.offers[0][0].automatic_discount) return;

            wideBundle.updateFormHiddenIds();

            wideBundle.variantsSelector = wideBundle.getVariantsSelector();
            if (!wideBundle.variantsSelector) return;
            
            wideBundle.fireAllChangeEvent();
        }, 0);
        try {
            eval(wideBundle.settings.js_code); //Run custom JS code we added through the admin dashboard
        } catch (error) {
            console.error("An error occurred while evaluating the code:", error);
        }
    }
    console.timeEnd("loading all WB");
};

//Hide WideBundle line item properties on the cart page
wideBundle.hideWideBundleLineItemProperties = function () {
    var run = function () {
        if (typeof meta === 'undefined' || meta?.page?.pageType !== 'cart') {
            return;
        }

        var selectors = [
            '.cart-item__property',
            '.cart__meta-text',
            '.product-option',
            '.product-details__property',
            '.product-details__item--property',
            '.line-item-property',
            '[data-cart-item-property]'
        ];

        var wbProperties = [
            '__wide-bundle-excl-offers',
            '__wide-bundle-variant',
            '__wide-bundle-gift-variant',
            '__wide-bundle-dyn-group',
        ];

        selectors.forEach(function (selector) {
            document.querySelectorAll(selector).forEach(function (node) {
                var text = node.textContent || '';
                for (var i = 0; i < wbProperties.length; i++) {
                    if (text.indexOf(wbProperties[i]) > -1) {
                        var container = node.closest('li') || node;
                        container.style.display = 'none';
                        break;
                    }
                }
            });
        });
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', run);
    } else {
        run();
    }
};

//Get the product loaded on the page that needs WideBundle, this function is only one time use while retrieving data from the servder, never ever use it across the code, if you need to use the current handle use wideBundle.currentHandle instead, it will have the correct value
wideBundle.getProductHandleOnPage = function() {
    var path = location.pathname.split("/");
    var pathHandle = path[path.length - 1] || path[path.length - 2];
    var urlHandles = ['products/', 'collections/', 'page/', 'pages/', 'blog/', 'blogs/'];
    var urlHandlesPos = posInUrl(location.href, urlHandles);


    //If handleWide exists
    if(typeof handleWide != 'undefined'){
        wideBundle.currentHandle = handleWide;
        return handleWide;
    }

    //If we are on product page
    if(urlHandlesPos['products/'] > -1){
        wideBundle.currentHandle = pathHandle;
        return pathHandle;
    }
    //If we are on homepage
    else if (typeof meta != 'undefined' &&
             typeof meta.page != 'undefined' &&
             meta.page.pageType == 'home' &&
             urlHandlesPos['collections/'] == -1) {
        wideBundle.currentHandle = "isOnHomePage";
        return 'isOnHomePage';
    }
    //If we are on a custom page and widebundleHandle exists
    else if (typeof meta != 'undefined' &&
             typeof meta.page != 'undefined' &&
             (meta.page.pageType == 'page' || meta.page.pageType == 'article' )&&
             (urlHandlesPos['page/'] == 1 || urlHandlesPos['pages/'] > 1 || urlHandlesPos['blog/'] == 1 || urlHandlesPos['blogs/'] > 1) &&
             typeof widebundleHandle != 'undefined') {
        wideBundle.currentHandle = widebundleHandle;
        return widebundleHandle;
    }
    //again check if we are on the home page, for some them we do not get the meta.page value populated with correct data, see the todays ticket ( with same date as this commit's date) for example
    else if(window.location.pathname === "/"){
        wideBundle.currentHandle = "isOnHomePage";
        return 'isOnHomePage';
    }
};

//First function run for WideBundle to get data from the server
(function(){
    wideBundle.hideWideBundleLineItemProperties();
    wideBundle.dataRequested = false;
    shopWB = ""; //We created this variable so that other WideBundle script will think it's currently loaded
    //document.addEventListener('DOMContentLoaded', function() {
        if(!wideBundle.dataRequested){
          wideBundle.dataRequested = true;
          // Get store information
          let shop = wideBundle.shop;
          var productHandle = wideBundle.getProductHandleOnPage();

          var url = wideBundle.domain + 'scripttagAjax.php';
          url += '?shop=' + encodeURIComponent(shop);
          url += '&productHandle=' + encodeURIComponent(productHandle);
          url += '&abTestVariant=' + wideBundle.retrieveAbTestVariant();

          function restoreFetch() { //Get original fetch to bypass theme delay problems
              if (!window._restoredFetch) {
                  const iframe = document.createElement('iframe');

                  iframe.style.display = 'none';
                  document.body.appendChild(iframe);

                  window._restoredFetch = iframe.contentWindow.fetch;
              }

              return window._restoredFetch;
          }
          if(typeof window.originalFetch == typeof undefined){
      			window.originalFetch = restoreFetch();
      		}

          // Make Ajax call after store information is available
          async function getProductData() {
              try{
                const response = await window.originalFetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-type': 'application/json;charset=UTF-8'
                    }
                });
                if(response.ok){
                    const data = await response.json();
                    // TODO: switch to new branch
                    if (data?.widget === "automatic_discounts" && data?.variants) {
                        wideBundle.abTestEnabled = data?.abTestEnabled == 1;
                        wideBundle.abTestExcludeOffers = data?.abTestExcludeOffers ?? [];
                        wideBundle.isAutomaticDiscount = true;
                        wideBundle.abTestIndex = data?.abTestIndex;
                    
                        const localStorageKey = "widebundle-ignore-visitors::" + data?.discount_offer_id;
                        const storedIndex = window.localStorage.getItem(localStorageKey);
                        if (!storedIndex || storedIndex !== wideBundle.abTestIndex) {
                            let url = wideBundle.domain + 'handleVisitors.php';
                            url += '?shop=' + encodeURIComponent(shop);
                            url += '&productHandle=' + encodeURIComponent(productHandle);
                            url += '&abTestVariant=' + (wideBundle.abTestEnabled ? wideBundle.retrieveAbTestVariant() : 'A');
                            const response = await window.originalFetch(url);
                            const status = await response.text();
                            console.log(`Handled visitors for offer "${data?.abTestIndex}" (${data?.discount_offer_id}), status: ${status}`);
                        } else {
                            console.log(`Ignored visitors for offer "${data?.abTestIndex}" (${data?.discount_offer_id})`);
                        }

                        window.localStorage.setItem(localStorageKey, wideBundle.abTestIndex);
                        
                        wideBundle.listColors = data?.listColors ?? false;
                        wideBundle.data = data.variants.map((variant) => {
                            return {
                                ...variant,
                                collection_target: Boolean(variant?.collection_target),
                                automatic_discount: true,
                            };
                        });

                        let prevUuid = wideBundle.data?.[0]?.offer_uuid;
                        wideBundle.data = wideBundle.data.flatMap((item) => {
                            if (!item?.all_products || !window.hasOwnProperty("wideBundle_targetProduct")) {
                                return [item];
                            }

                            const targetProduct = window?.wideBundle_targetProduct;
                            if (!targetProduct) {
                                return [item];
                            }

                            let optionTitlesCounter = {};
                            return targetProduct.variants.map((variant, variantIndex) => {
                                let title_option2 = "";
                                if (item.offer_uuid !== prevUuid) {
                                    optionTitlesCounter = {};
                                }

                                let variant_option2 = null;
                                let variant_option2_title = "";
                                let variant_option2_is_color = "0";
                                if (targetProduct.options?.[0]) {
                                    variant_option2 = Array(item.product_qty).fill(variant.option1).join('|');
                                    variant_option2_title = targetProduct.options[0].name;
                                    variant_option2_is_color = (item?.swatch_options ?? []).includes(targetProduct.options[0].name) ? "1" : "0";
                                    if (variantIndex === 0) {
                                        if (!optionTitlesCounter[variant_option2_title]) {
                                            optionTitlesCounter[variant_option2_title] = 0;
                                        }
                                        optionTitlesCounter[variant_option2_title] += 1;
                                    }
                                    title_option2 = variant_option2_title + " " + optionTitlesCounter[variant_option2_title];
                                }

                                let variant_option3 = null;
                                let variant_option3_title = "";
                                let variant_option3_is_color = "0";
                                if (targetProduct.options?.[1]) {
                                    variant_option3 = Array(item.product_qty).fill(variant.option2).join('|');
                                    variant_option3_title = targetProduct.options[1].name;
                                    variant_option3_is_color = (item?.swatch_options ?? []).includes(targetProduct.options[1].name) ? "1" : "0";
                                    if (variantIndex === 0) {
                                        if (!optionTitlesCounter[variant_option3_title]) {
                                            optionTitlesCounter[variant_option3_title] = 0;
                                        }
                                        optionTitlesCounter[variant_option3_title] += 1;
                                    }
                                    title_option2 += " & " . variant_option3_title + " " + optionTitlesCounter[variant_option3_title];
                                }

                                let variant_option4 = null;
                                let variant_option4_title = "";
                                let variant_option4_is_color = "0";
                                if (targetProduct.options?.[2]) {
                                    variant_option4 = Array(item.product_qty).fill(variant.option3).join('|');
                                    variant_option4_title = targetProduct.options[2].name;
                                    variant_option4_is_color = (item?.swatch_options ?? []).includes(targetProduct.options[2].name) ? "1" : "0";
                                    if (variantIndex === 0) {
                                        if (!optionTitlesCounter[variant_option4_title]) {
                                            optionTitlesCounter[variant_option4_title] = 0;
                                        }
                                        optionTitlesCounter[variant_option4_title] += 1;
                                    }
                                    title_option2 += " & " . variant_option4_title + " " + optionTitlesCounter[variant_option4_title];
                                }

                                if (variantIndex === 0) {
                                    for (let k = 1; k < item.product_qty; k++) {
                                        if (targetProduct.options?.[0]) {
                                            optionTitlesCounter[variant_option2_title] += 1;
                                            title_option2 += ',' + variant_option2_title + ' ' + optionTitlesCounter[variant_option2_title];
                                        }

                                        if (targetProduct.options?.[1]) {
                                            optionTitlesCounter[variant_option3_title] += 1;
                                            title_option2 += ',' + variant_option3_title + ' ' + optionTitlesCounter[variant_option3_title];
                                        }

                                        if (targetProduct.options?.[2]) {
                                            optionTitlesCounter[variant_option4_title] += 1;
                                            title_option2 += ',' + variant_option4_title + ' ' + optionTitlesCounter[variant_option4_title];
                                        }
                                    }
                                }

                                prevUuid = item.offer_uuid;
                                return {
                                    ...item,
                                    product_id: targetProduct.id.toString(),
                                    title: targetProduct.title,
                                    variant_compared: variant.compare_at_price !== null ? (variant.compare_at_price / 100).toFixed(2) : null,
                                    variant_id: variant.id,
                                    variant_option2,
                                    variant_option2_is_color,
                                    variant_option2_title,
                                    variant_option3,
                                    variant_option3_is_color,
                                    variant_option3_title,
                                    variant_option4,
                                    variant_option4_is_color,
                                    variant_option4_title,
                                    variant_price: (variant.price / 100).toFixed(2),
                                    variant_title: variant.title,
                                };
                            });
                        });
                    } else {
                        wideBundle.isAutomaticDiscount = false;
                        wideBundle.data = data;
                    }
                    
                    for (let i = 0; i < wideBundle.data.length; i++) {
                        for (let key in wideBundle.data[i]) {
                            if (!isNaN(parseInt(key))) {
                                delete wideBundle.data[i][key];
                            }
                        }
                    }
                    if (wideBundle.data.length > 0) {
                        if(wideBundle.currentHandle == "isOnHomePage"){
                          wideBundle.currentHandle = wideBundle.data[0].handle;
                        }

                        if (wideBundle.settings.plan !== "monthly") {
                            const productTemplate = wideBundle.templates.find(template => template.id == wideBundle.data[0].template_id);
                            if (productTemplate) {
                                // Remove translations from template to ensure we only use shop translations
                                const { translations, ...templateWithoutTranslations } = productTemplate;
                                
                                // Merge template settings with shop settings (without template translations)
                                wideBundle.settings = { 
                                    ...wideBundle.settings, 
                                    ...templateWithoutTranslations
                                };
                            }
                        }

                        wideBundle.init(wideBundle.data);
                    }
                }
                else{
                    console.error('Error:', response.statusText);
                }
              }catch(error){
                  console.error('Error:', error);
              }
          }

          // Call the function to make the Ajax call
          getProductData();
        }
    //});
})()

}