// Dingus Preview JavaScript
// GitHub Emoji Processing

function getEmoji(key) {
  var _key = key.replace(/:(\S+):/, "$1").replace(/–/, "-");
  if (Marked.githubEmoji.hasOwnProperty(_key)) {
    return (
      '<span class="g-emoji" alias="' +
      _key +
      '"><img src="' +
      Marked.githubEmoji[_key] +
      '"></span>'
    );
  }
  return key;
}

function emojify() {
  console.log("Starting emojify...");
  var firstDiff =
    document.querySelector("ins.diff-marker") ||
    document.querySelector("#firstdiff");
  if (firstDiff) {
    var parent = firstDiff.parentElement;
    parent.innerHTML = parent.innerHTML.replace(
      /:(\S*)(<ins.*?<\/ins>)(\S*):/,
      ":$1$3:$2"
    );
  }
  var wrapper = document.body;
  if (wrapper) {
    var elements = wrapper.querySelectorAll("*:not(code):not(pre)");
    console.log("Found", elements.length, "elements to process");
    var processedCount = 0;
    elements.forEach(function (el) {
      if (el.children.length === 0) {
        var originalHTML = el.innerHTML;
        el.innerHTML = el.innerHTML.replace(/:(\S+):/gi, getEmoji);
        if (originalHTML !== el.innerHTML) {
          processedCount++;
          console.log(
            "Processed element:",
            el.tagName,
            originalHTML,
            "->",
            el.innerHTML
          );
        }
      } else {
        // Process text nodes within elements that have children
        var walker = document.createTreeWalker(
          el,
          NodeFilter.SHOW_TEXT,
          null,
          false
        );
        var textNode;
        while ((textNode = walker.nextNode())) {
          if (
            textNode.parentNode.tagName !== "CODE" &&
            textNode.parentNode.tagName !== "PRE"
          ) {
            var originalText = textNode.textContent;
            var newText = textNode.textContent.replace(/:(\S+):/gi, getEmoji);
            if (newText !== textNode.textContent) {
              var tempDiv = document.createElement("div");
              tempDiv.innerHTML = newText;
              var parent = textNode.parentNode;
              while (tempDiv.firstChild) {
                parent.insertBefore(tempDiv.firstChild, textNode);
              }
              parent.removeChild(textNode);
              processedCount++;
              console.log("Processed text node:", originalText, "->", newText);
            }
          }
        }
      }
    });
    console.log("Emojify complete. Processed", processedCount, "elements");
  } else {
    console.log("No wrapper found");
  }
}

// Process emoji on page load
document.addEventListener("DOMContentLoaded", function () {
  emojify();
});
