import { css } from "@emotion/css";
import katex from "katex";
import { useLayoutEffect, useRef } from "react";

export const Katex = (props: { tex: string }) => {
	const {tex} = props;
	const ref = useRef<HTMLDivElement>(null);

	useLayoutEffect(() => {
		const element = ref.current;
		if (!element) {
			return;
		}
		katex.render(tex, element);
	}, [tex])
	return (
		<span ref={ref} className={css`
			math {
				display: none;
			}
		`}></span>
	);
};

export const MathText = (props: { children: string }) => {
	const str = props.children;
	const segments = str.split("$").map((s, i) => (i % 2 === 0 ? {type: "text", value: s} : {type: "math", value: s}));
	const components = segments.map((segment, i) => {
		if (segment.type === "text") {
			return segment.value.split("\\\\").flatMap((s, j) => [<br key={j}/>, s]).slice(1);
		} else if (segment.type === "math") {
			return <Katex key={i} tex={segment.value}/>;
		}
	})

	return (
		<>{components}</>
	);
};
