// 简化的数学公式渲染调试脚本
(function() {
    'use strict';

    console.log('[Debug] Script loaded');

    // 等待页面加载完成
    function init() {
        console.log('[Debug] DOMContentLoaded fired');

        // 检查 KaTeX 是否存在
        if (typeof window.katex === 'undefined') {
            console.error('[Debug] KaTeX is not loaded!');
            return;
        }

        console.log('[Debug] KaTeX is loaded:', window.katex);

        // 查找所有 math-render 元素
        const elements = document.querySelectorAll('.math-render');
        console.log('[Debug] Found', elements.length, 'math-render elements');

        elements.forEach((el, index) => {
            console.log(`[Debug] Element ${index}:`, el);
            renderElement(el);
        });
    }

    function renderElement(element) {
        if (!element) return;

        // 避免重复渲染
        if (element.dataset.rendered === 'true') {
            console.log('[Debug] Already rendered:', element);
            return;
        }

        const content = element.dataset.mathContent || element.textContent;
        console.log('[Debug] Content to render:', content);

        if (!content) {
            console.warn('[Debug] No content found');
            return;
        }

        try {
            let html = content;

            // 渲染 $$...$$ 块级公式
            html = html.replace(/\$\$([\s\S]*?)\$\$/g, (match, formula) => {
                try {
                    return window.katex.renderToString(formula.trim(), {
                        throwOnError: false,
                        displayMode: true
                    });
                } catch (e) {
                    console.warn('KaTeX block render error:', e);
                    return match;
                }
            });

            // 渲染 $...$ 行内公式
            html = html.replace(/\$(.*?)\$/g, (match, formula) => {
                try {
                    console.log('[Debug] Rendering inline formula:', formula);
                    return window.katex.renderToString(formula, {
                        throwOnError: false,
                        displayMode: false
                    });
                } catch (e) {
                    console.warn('KaTeX inline render error:', e);
                    return match;
                }
            });

            console.log('[Debug] Rendered HTML:', html);
            element.innerHTML = html;
            element.dataset.rendered = 'true';
            console.log('[Debug] Rendered successfully');
        } catch (e) {
            console.error('[Debug] Render error:', e);
        }
    }

    // 监听 DOMContentLoaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();
