import { browser } from '$app/environment';
import katex from 'katex';

export async function autoRenderMath(node: HTMLElement) {
	if (!browser) return;

	try {
		const renderMathInElement = (await import('katex/dist/contrib/auto-render')).default;
		await import('katex/dist/katex.min.css');

		// 1. First, handle the standard delimiters
		renderMathInElement(node, {
			delimiters: [
				{ left: '$$', right: '$$', display: true },
				{ left: '$', right: '$', display: false },
				{ left: '\\(', right: '\\)', display: false },
				{ left: '\\[', right: '\\]', display: true }
			],
			throwOnError: false
		});

		// 2. Then, handle <script type="math/tex"> tags generated by python-markdown-math
		const mathScripts = node.querySelectorAll('script[type^="math/tex"]');
		mathScripts.forEach((script) => {
			const displayMode = script.getAttribute('type') === 'math/tex; mode=display';
			const content = script.textContent || '';
			const span = document.createElement('span');
			
			try {
				katex.render(content, span, {
					displayMode: displayMode,
					throwOnError: false
				});
				script.parentNode?.replaceChild(span, script);
			} catch (err) {
				console.error('KaTeX rendering error:', err);
			}
		});
	} catch (e) {
		console.error('KaTeX failed to load:', e);
	}
}

/**
 * Svelte action to render LaTeX math in an element using KaTeX auto-render.
 */
export function renderMath(node: HTMLElement) {
	if (browser) {
		autoRenderMath(node);
	}

	return {
		update() {
			if (browser) {
				autoRenderMath(node);
			}
		}
	};
}
