import { visit } from 'unist-util-visit';
/**
 * Remark plugin to transform mermaid code blocks into Mermaid components
 * 
 * Transforms:
 * ```mermaid
 * flowchart LR
 *     A --> B
 * ```
 * 
 * Into:
 * <Mermaid>
 * {`flowchart LR
 *     A --> B`}
 * </Mermaid>
 */ export function remarkMermaid() {
    return (tree)=>{
        visit(tree, 'code', (node, index, parent)=>{
            if (node.lang !== 'mermaid' || !parent || index === undefined) {
                return;
            }
            // Replace the code block with MDX JSX element
            const mermaidNode = {
                type: 'mdxJsxFlowElement',
                name: 'Mermaid',
                attributes: [],
                children: [
                    {
                        type: 'mdxFlowExpression',
                        value: '`' + node.value + '`',
                        data: {
                            estree: {
                                type: 'Program',
                                body: [
                                    {
                                        type: 'ExpressionStatement',
                                        expression: {
                                            type: 'TemplateLiteral',
                                            expressions: [],
                                            quasis: [
                                                {
                                                    type: 'TemplateElement',
                                                    value: {
                                                        raw: node.value,
                                                        cooked: node.value
                                                    },
                                                    tail: true
                                                }
                                            ]
                                        }
                                    }
                                ],
                                sourceType: 'module'
                            }
                        }
                    }
                ]
            };
            // Replace the code node with the Mermaid component
            parent.children.splice(index, 1, mermaidNode);
        });
    };
}
