<script>
/* Kaching Bundles -> Ascendify live price sync */
(function () {
  if (window.__kachingPriceSync) return;
  window.__kachingPriceSync = true;

  var run = function () {
    var app = document.querySelector('kaching-bundle');
    if (!app) return false;

    var getSelectedBar = function () {
      return app.querySelector('.kaching-bundles__bar:has(input:checked)')
        || app.querySelector('.kaching-bundles__bar input:checked')
        && app.querySelector('.kaching-bundles__bar input:checked').closest('.kaching-bundles__bar');
    };

    var updateMainPrice = function (price, comparePrice) {
      var priceRoot = document.querySelector('.product-page-price .price');
      if (!priceRoot || !price) return;

      var regular = priceRoot.querySelector('.price__regular .price-item--regular');
      var sale = priceRoot.querySelector('.price__sale .price-item--sale');
      if (regular) regular.textContent = price;
      if (sale) sale.textContent = price;

      var compareEl = priceRoot.querySelector('.price__compare-price s');
      if (comparePrice) {
        priceRoot.classList.add('price--on-sale');
        if (compareEl) {
          compareEl.textContent = comparePrice;
        } else {
          var saleBlock = priceRoot.querySelector('.price__sale');
          if (saleBlock) {
            var wrap = document.createElement('span');
            wrap.className = 'price__compare-price';
            wrap.innerHTML = '<s class="price-item price-item--regular"></s>';
            wrap.querySelector('s').textContent = comparePrice;
            saleBlock.appendChild(wrap);
          }
        }
      }
    };

    var parseMoney = function (s) {
      var t = (s || '').replace(/[^\d.,]/g, '');
      if (t.indexOf('.') > -1 && t.indexOf(',') > -1) {
        t = t.lastIndexOf(',') > t.lastIndexOf('.')
          ? t.replace(/\./g, '').replace(',', '.')
          : t.replace(/,/g, '');
      } else if (t.indexOf(',') > -1) {
        t = t.split(',').pop().length === 2
          ? t.replace(/,/g, '.')
          : t.replace(/,/g, '');
      }
      return parseFloat(t) || 0;
    };

    var moneyFormatter = function (sample) {
      var prefix = (sample.match(/^[^\d]*/) || [''])[0];
      var suffix = (sample.match(/[^\d]*$/) || [''])[0];
      var digits = sample.replace(/[^\d.,]/g, '');
      var decSep = ',', thouSep = '.';
      if (digits.indexOf('.') > -1 && digits.indexOf(',') > -1) {
        decSep = digits.lastIndexOf(',') > digits.lastIndexOf('.') ? ',' : '.';
      } else if (digits.indexOf('.') > -1 && digits.split('.').pop().length === 2) {
        decSep = '.';
      }
      thouSep = decSep === ',' ? '.' : ',';
      return function (num) {
        var parts = num.toFixed(2).split('.');
        var intp = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thouSep);
        var out = parts[1] === '00' ? intp : intp + decSep + parts[1];
        return prefix + out + suffix;
      };
    };

    var updateBadge = function (price, comparePrice) {
      var container = document.querySelector('.product-page-price .price__badges-container');
      if (!container) return;
      var badge = container.querySelector('.price__badge-sale, .price__badge-custom');
      if (!badge) return;

      var p = parseMoney(price), c = parseMoney(comparePrice);
      if (!c || c <= p) { badge.style.display = 'none'; return; }
      badge.style.display = '';

      var saved = c - p;
      var pct = Math.floor((saved / c) * 100) + '%';
      var amount = moneyFormatter(comparePrice || price)(saved);

      var tplEl = badge.querySelector('[data-template]');
      if (tplEl && tplEl.getAttribute('data-template')) {
        tplEl.textContent = tplEl.getAttribute('data-template')
          .replace(/\[amount\]/g, amount)
          .replace(/\[percentage\]/g, pct);
      } else {
        if (!badge.dataset.kachingTpl) badge.dataset.kachingTpl = badge.textContent.trim();
        var moneyRe = new RegExp((comparePrice.match(/^[^\d]*/) || [''])[0].replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s?[\\d.,]+');
        var txt = badge.dataset.kachingTpl
          .replace(moneyRe, amount)
          .replace(/\d+\s*%/, pct);
        badge.textContent = txt;
      }
    };

    var sync = function () {
      var bar = getSelectedBar();
      if (!bar) return;
      var priceEl = bar.querySelector('.kaching-bundles__bar-price');
      var compareEl = bar.querySelector('.kaching-bundles__bar-full-price');
      var price = priceEl ? priceEl.textContent.trim() : '';
      var comparePrice = compareEl ? compareEl.textContent.trim() : '';
      updateMainPrice(price, comparePrice);
      updateBadge(price, comparePrice);
    };

    app.addEventListener('change', function () {
      sync();
      setTimeout(sync, 60);
      setTimeout(sync, 250);
    });

    var tries = 0;
    var settle = setInterval(function () {
      tries++;
      if (getSelectedBar()) { sync(); clearInterval(settle); }
      if (tries > 40) clearInterval(settle);
    }, 300);

    return true;
  };

  var tries = 0;
  var boot = setInterval(function () {
    tries++;
    if (run() || tries > 60) clearInterval(boot);
  }, 300);
  document.addEventListener('DOMContentLoaded', run);
})();
</script>