// Initialize Mermaid for Hugo Book theme
// Loaded via Hugo's custom head/footer

(function () {
  var initialized = false;

  function renderNode(node) {
    var graphDefinition = node.textContent;
    node.innerHTML = "";
    node.removeAttribute("data-processed");

    if (typeof window.mermaid.render === "function") {
      try {
        var id = "mermaid-" + Math.random().toString(36).substr(2, 9);
        var result = window.mermaid.render(id, graphDefinition);

        if (result && typeof result.then === "function") {
          result
            .then(function (out) {
              node.innerHTML = out && out.svg ? out.svg : "";
            })
            .catch(function (err) {
              node.innerHTML =
                '<pre class="mermaid-error">Error: ' +
                (err && err.message ? err.message : String(err)) +
                "</pre>";
            });
          return;
        }

        if (result && result.svg) {
          node.innerHTML = result.svg;
          return;
        }

        if (typeof result === "string") {
          node.innerHTML = result;
          return;
        }
      } catch (err) {
        node.innerHTML =
          '<pre class="mermaid-error">Error: ' +
          (err && err.message ? err.message : String(err)) +
          "</pre>";
        return;
      }
    }

    // Fallback
    node.innerHTML = graphDefinition;
  }

  function renderMermaid() {
    if (typeof window.mermaid === "undefined") {
      setTimeout(renderMermaid, 100);
      return;
    }

    if (!initialized) {
      window.mermaid.initialize({
        startOnLoad: false,
        securityLevel: "loose",
        theme: "default",
      });
      initialized = true;
    }

    var nodes = document.querySelectorAll(".mermaid");
    if (!nodes || nodes.length === 0) {
      return;
    }

    for (var i = 0; i < nodes.length; i++) {
      renderNode(nodes[i]);
    }
  }

  // Initial load
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", renderMermaid);
  } else {
    setTimeout(renderMermaid, 100);
  }
})();
