import { memo, useEffect, useRef } from "react";

interface MathBlockProps { content: string; inline?: boolean }

const MathBlock = memo(function MathBlock({ content, inline = false }: MathBlockProps) {
  const ref = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    if (!ref.current) return;
    let cancelled = false;
    import("katex").then(katex => {
      if (cancelled || !ref.current) return;
      try {
        katex.default.render(content.trim(), ref.current, {
          displayMode: !inline,
          throwOnError: false,
          output: "html",
          trust: false,
        });
      } catch (e) {
        if (ref.current) ref.current.textContent = content;
      }
    }).catch(() => {
      if (ref.current) ref.current.textContent = content;
    });
    return () => { cancelled = true; };
  }, [content, inline]);

  if (inline) {
    return <span ref={ref} style={{ fontFamily: "KaTeX_Main, serif" }} />;
  }

  return (
    <div style={{
      background: "#0d0d18", border: "1px solid #1e1e2e", borderRadius: 10,
      padding: "0.75rem 1rem", marginBottom: "0.6em",
      display: "flex", justifyContent: "center", overflowX: "auto",
    }}>
      <span ref={ref} style={{ fontFamily: "KaTeX_Main, serif", fontSize: "1.05em" }} />
    </div>
  );
}
);
export default MathBlock;
