// (C) 2022-2025 GoodData Corporation
import { REFERENCE_REGEX_SPLIT } from "./types.js";
export function remarkReferences() {
    return function () {
        return function (tree) {
            iterateTree(tree, {
                onText: (text) => {
                    const nodes = [];
                    const parts = text.value.split(REFERENCE_REGEX_SPLIT);
                    let start = text.position?.start ?? { line: 0, column: 0, offset: 0 };
                    parts.forEach((part) => {
                        const end = {
                            line: start.line,
                            column: start.column + part.length,
                            offset: (start.offset ?? 0) + part.length,
                        };
                        nodes.push({
                            ...text,
                            value: part,
                            position: {
                                start,
                                end,
                            },
                        });
                        start = end;
                    });
                    return nodes;
                },
            });
            return tree;
        };
    };
}
function iterateTree(node, callbacks) {
    //Text type
    if (node.type === "text") {
        return callbacks.onText(node);
    }
    // has children
    if (node.children) {
        node.children = node.children.reduce((acc, child) => {
            return [...acc, ...iterateTree(child, callbacks)];
        }, []);
        return [node];
    }
    // no children
    return [node];
}
