const INLINE_CONTAINER_TYPES = new Set([
    'link',
    'autolink'
]);
const SKIP_TYPES = new Set([
    'youtube',
    'vimeo',
    'horizontalrule',
    'tab'
]);
class LexicalTextConverter {
    addText(text) {
        if (null != text) this.current += text;
    }
    endParagraph() {
        const p = this.current.trim();
        if (p.length > 0) this.paragraphs.push(p);
        this.current = '';
    }
    getText() {
        this.endParagraph();
        return this.paragraphs.join('\n');
    }
    addBlockNodes(nodes) {
        this.endParagraph();
        for (const node of nodes ?? [])this.addNode(node);
        this.endParagraph();
    }
    addInlineNodes(nodes) {
        for (const node of nodes ?? [])this.addNode(node);
    }
    addNode(node) {
        const type = node.type;
        if ('text' === type || 'code-highlight' === type) return void this.addText(node.text);
        if ('linebreak' === type) return void this.endParagraph();
        if ('admonition' === type) {
            this.endParagraph();
            this.addText(node.title);
            this.endParagraph();
            this.addText(lexicalToText(node.content?.editorState).trim());
            this.endParagraph();
            return;
        }
        if ('inline-image' === type) {
            this.endParagraph();
            this.addText(node.altText);
            if (node.showCaption) {
                this.endParagraph();
                this.addText(lexicalToText(node.caption?.editorState).trim());
            }
            this.endParagraph();
            return;
        }
        if (null != type && SKIP_TYPES.has(type)) return;
        if (null != type && INLINE_CONTAINER_TYPES.has(type)) return void this.addInlineNodes(node.children);
        if (Array.isArray(node.children)) this.addBlockNodes(node.children);
    }
    constructor(){
        this.paragraphs = [];
        this.current = '';
    }
}
function resolveRoot(value) {
    let v = value;
    if ('string' == typeof v) try {
        v = JSON.parse(v);
    } catch  {
        return null;
    }
    if ('object' != typeof v || null === v) return null;
    const obj = v;
    const root = obj.root ?? obj;
    return 'root' === root.type ? root : null;
}
function lexicalToText(value) {
    const root = resolveRoot(value);
    if (null == root) return '';
    const converter = new LexicalTextConverter();
    converter.addBlockNodes(root.children);
    return converter.getText();
}
export { lexicalToText };
