import { mathjax } from "mathjax-full/js/mathjax.js";
import { TeX } from "mathjax-full/js/input/tex.js";
import { SVG } from "mathjax-full/js/output/svg.js";
import { liteAdaptor } from "mathjax-full/js/adaptors/liteAdaptor.js";
import { RegisterHTMLHandler } from "mathjax-full/js/handlers/html.js";
import { AllPackages } from "mathjax-full/js/input/tex/AllPackages";

const adaptor = liteAdaptor();
RegisterHTMLHandler(adaptor);

const tex = new TeX({
  packages: AllPackages,
});
const svg = new SVG({ fontCache: "none" });
const html = mathjax.document("", { InputJax: tex, OutputJax: svg });

export const renderLatexToSVG = (latex) => {
  const node = html.convert(latex, {
    display: true, // 是否以块级渲染
  });

  // 返回 SVG 字符串
  return adaptor.outerHTML(node);
};

/**
 * 将 SVG 转换为图片（PNG 或 JPEG）
 * @param {string} svgString - SVG 的字符串内容
 * @param {number} width - 图片宽度
 * @param {number} height - 图片高度
 * @returns {Promise<string>} - 返回图片的 Base64 URL
 */
export const svgToImage = (svgString, width = 300, height = 300) => {
  return new Promise((resolve, reject) => {
    const svgBlob = new Blob([svgString], { type: "image/svg+xml" });
    const url = URL.createObjectURL(svgBlob);

    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);

      const dataUrl = canvas.toDataURL("image/png");
      resolve(dataUrl);
      URL.revokeObjectURL(url);
    };

    img.onerror = (err) => {
      reject(err);
    };

    img.src = url;
  });
};
