"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/LatexRenderer/LatexRenderer.tsx
var LatexRenderer_exports = {};
__export(LatexRenderer_exports, {
  default: () => LatexRenderer_default
});
module.exports = __toCommonJS(LatexRenderer_exports);
var import_katex_min = require("katex/dist/katex.min.css");

// src/components/HtmlMathRenderer/KatexMath.tsx
var import_katex = __toESM(require("katex"));
var import_jsx_runtime = require("react/jsx-runtime");
var KatexMath = ({
  math,
  displayMode = false,
  renderError
}) => {
  let html;
  try {
    html = import_katex.default.renderToString(math, {
      displayMode,
      throwOnError: true
    });
  } catch (error_) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: renderError ? renderError(error_) : null });
  }
  const Tag = displayMode ? "div" : "span";
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    Tag,
    {
      "data-testid": "react-katex",
      dangerouslySetInnerHTML: { __html: html }
    }
  );
};

// src/components/LatexRenderer/LatexRenderer.tsx
var import_dompurify = __toESM(require("dompurify"));
var import_html_react_parser = __toESM(require("html-react-parser"));

// src/utils/utils.ts
var import_clsx = require("clsx");
var import_tailwind_merge = require("tailwind-merge");
function cn(...inputs) {
  return (0, import_tailwind_merge.twMerge)((0, import_clsx.clsx)(inputs));
}

// src/components/LatexRenderer/LatexRenderer.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var sanitizeHtml = (value) => {
  return import_dompurify.default.sanitize(value, {
    ADD_ATTR: ["data-latex", "data-display-mode", "data-math", "data-math-id"]
  });
};
var decodeHtmlEntities = (str) => {
  const textarea = document.createElement("textarea");
  textarea.innerHTML = str;
  return textarea.value;
};
var cleanLatex = (str) => {
  return str.replaceAll(/[\u200B-\u200D\uFEFF]/g, "").trim();
};
var createMathReplacer = (mathParts, errorRenderer) => {
  return (domNode) => {
    if (domNode instanceof import_html_react_parser.Element && domNode.name === "span" && domNode.attribs["data-math-id"]) {
      const mathId = Number.parseInt(domNode.attribs["data-math-id"], 10);
      const mathPart = mathParts[mathId];
      if (!mathPart) return domNode;
      if (mathPart.type === "inline") {
        return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
          KatexMath,
          {
            math: mathPart.latex,
            renderError: () => errorRenderer(mathPart.latex)
          },
          `math-${mathId}`
        );
      } else {
        return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "my-2.5 text-center", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
          KatexMath,
          {
            math: mathPart.latex,
            displayMode: true,
            renderError: () => errorRenderer(mathPart.latex)
          }
        ) }, `math-${mathId}`);
      }
    }
    return domNode;
  };
};
var LatexRenderer = ({
  content,
  className,
  style,
  onError
}) => {
  const renderContentWithMath = (htmlContent) => {
    if (!htmlContent) return null;
    let processedContent = htmlContent;
    const mathParts = [];
    const mathFormulaPattern = /<span[^>]*class="math-formula"[^>]*data-latex="([^"]*)"[^>]*>[\s\S]*?<\/span>/g;
    processedContent = processedContent.replaceAll(
      mathFormulaPattern,
      (match, latex) => {
        const isDisplayMode = match.includes('data-display-mode="true"');
        const id = mathParts.length;
        mathParts.push({
          id,
          type: isDisplayMode ? "block" : "inline",
          latex: cleanLatex(decodeHtmlEntities(latex))
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const wrappedMathPattern = /<span[^>]*class="math-expression"[^>]*data-math="([^"]*)"[^>]*>.*?<\/span>/g;
    processedContent = processedContent.replaceAll(
      wrappedMathPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "inline",
          latex: cleanLatex(decodeHtmlEntities(latex))
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const doubleDollarPattern = /(?<!\\)\$\$([\s\S]+?)\$\$/g;
    processedContent = processedContent.replaceAll(
      doubleDollarPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "block",
          latex: cleanLatex(latex)
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const singleDollarPattern = /(?<!\\)\$([\s\S]+?)\$/g;
    processedContent = processedContent.replaceAll(
      singleDollarPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "inline",
          latex: cleanLatex(latex)
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const latexTagPattern = /(?:<latex>|&lt;latex&gt;)([\s\S]*?)(?:<\/latex>|&lt;\/latex&gt;)/g;
    processedContent = processedContent.replaceAll(
      latexTagPattern,
      (match, latex) => {
        const id = mathParts.length;
        mathParts.push({
          id,
          type: "inline",
          latex: cleanLatex(latex)
        });
        return `<span data-math-id="${id}"></span>`;
      }
    );
    const latexEnvPattern = /\\begin\{([^}]+)\}([\s\S]*?)\\end\{\1\}/g;
    processedContent = processedContent.replaceAll(latexEnvPattern, (match) => {
      const id = mathParts.length;
      mathParts.push({
        id,
        type: "block",
        latex: cleanLatex(match)
      });
      return `<span data-math-id="${id}"></span>`;
    });
    const sanitizedContent = sanitizeHtml(processedContent);
    const defaultErrorRenderer = (latex) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "text-red-600", children: [
      "Math Error: ",
      latex
    ] });
    const errorRenderer = onError || defaultErrorRenderer;
    const options = {
      replace: createMathReplacer(mathParts, errorRenderer)
    };
    return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: (0, import_html_react_parser.default)(sanitizedContent, options) });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
    "div",
    {
      className: cn("whitespace-pre-wrap leading-relaxed", className),
      style,
      children: renderContentWithMath(content)
    }
  );
};
var LatexRenderer_default = LatexRenderer;
//# sourceMappingURL=index.js.map