
(function ($) {
  function replacePlaceholders(node, replacements) {
    // Helper function to replace placeholders in a string
    function replaceText(text) {
      return text.replace(/\{([^{}]+)\}/g, (match, key) => {
        return replacements.hasOwnProperty(key) ? (replacements[key] || '') : match;
      });
    }

    // Process attributes if it's an element node
    if (node.nodeType === Node.ELEMENT_NODE) {
      // Process src and href attributes
      ['src', 'href'].forEach(attr => {
        if (node.hasAttribute(attr)) {
          const originalValue = node.getAttribute(attr);
          const newValue = replaceText(originalValue);
          if (originalValue !== newValue) {
            node.setAttribute(attr, newValue);
          }
        }
      });
    }

    // Process text nodes
    if (node.nodeType === Node.TEXT_NODE) {
      const newText = replaceText(node.nodeValue);
      if (node.nodeValue !== newText) {
        node.nodeValue = newText;
      }
    }

    // Recursively process child nodes
    for (const child of node.childNodes) {
      replacePlaceholders(child, replacements);
    }
  }

  // Initialize Elementor HTML widget handler
  $(window).on('elementor/frontend/init', function () {
    elementorFrontend.hooks.addAction('frontend/element_ready/html.default', function ($scope) {
      replacePlaceholders($scope[0], epa_receipt_object);
    });
    elementorFrontend.hooks.addAction('frontend/element_ready/text-editor.default', function ($scope) {
      replacePlaceholders($scope[0], epa_receipt_object);
    });
  });
  
  $(document).ready(function () {
    if (!$('.elementor-widget-html').length) {
      replacePlaceholders(document.querySelector('main'), epa_receipt_object);
    }
  });
})(jQuery);