function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
import { handleInlineCode } from "./parseElements";
import { shouldTreatInlineMathAsText } from "./parseMath";
/**
 * 设置节点的 finished 属性
 */ export var setFinishedProp = function(leaf, finished) {
    if (finished !== false) {
        return leaf;
    }
    return _object_spread_props(_object_spread({}, leaf), {
        otherProps: _object_spread_props(_object_spread({}, leaf.otherProps), {
            finished: finished
        })
    });
};
/**
 * 检查 leaf 是否有格式属性需要保留
 */ var hasFormattingProps = function(leaf) {
    var _leaf_otherProps;
    return !!(leaf.bold || leaf.italic || leaf.strikethrough || leaf.url || leaf.code || ((_leaf_otherProps = leaf.otherProps) === null || _leaf_otherProps === void 0 ? void 0 : _leaf_otherProps.finished) === false);
};
/**
 * 解析文本节点和内联元素
 */ export var parseText = function(els) {
    var leaf = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
        data: {}
    };
    var leafs = [];
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = els[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var n = _step.value;
            if (n.type === 'strong') {
                var strongLeaf = setFinishedProp(_object_spread_props(_object_spread({}, leaf), {
                    bold: true
                }), n.finished);
                var strongResult = parseText(n.children, strongLeaf);
                leafs = leafs.concat(strongResult);
                // 如果处理完嵌套节点后没有生成任何节点，且 leaf 有格式属性，生成空文本节点以保留格式
                if (strongResult.length === 0 && hasFormattingProps(strongLeaf)) {
                    leafs.push(_object_spread_props(_object_spread({}, strongLeaf), {
                        text: ''
                    }));
                }
                continue;
            }
            if (n.type === 'emphasis') {
                var emphasisLeaf = setFinishedProp(_object_spread_props(_object_spread({}, leaf), {
                    italic: true
                }), n.finished);
                var emphasisResult = parseText(n.children, emphasisLeaf);
                leafs = leafs.concat(emphasisResult);
                // 如果处理完嵌套节点后没有生成任何节点，且 leaf 有格式属性，生成空文本节点以保留格式
                if (emphasisResult.length === 0 && hasFormattingProps(emphasisLeaf)) {
                    leafs.push(_object_spread_props(_object_spread({}, emphasisLeaf), {
                        text: ''
                    }));
                }
                continue;
            }
            if (n.type === 'delete') {
                var deleteLeaf = _object_spread_props(_object_spread({}, leaf), {
                    strikethrough: true
                });
                var deleteResult = parseText(n.children, deleteLeaf);
                leafs = leafs.concat(deleteResult);
                // 如果处理完嵌套节点后没有生成任何节点，且 leaf 有格式属性，生成空文本节点以保留格式
                if (deleteResult.length === 0 && hasFormattingProps(deleteLeaf)) {
                    leafs.push(_object_spread_props(_object_spread({}, deleteLeaf), {
                        text: ''
                    }));
                }
                continue;
            }
            if (n.type === 'link') {
                // 只有当 link 节点有 URL 时才处理为链接，否则按普通文本处理
                if (n === null || n === void 0 ? void 0 : n.url) {
                    var linkLeaf = _object_spread_props(_object_spread({}, leaf), {
                        url: n === null || n === void 0 ? void 0 : n.url
                    });
                    var linkResult = parseText(n.children, linkLeaf);
                    leafs = leafs.concat(linkResult);
                    // 如果处理完嵌套节点后没有生成任何节点，且 leaf 有格式属性，生成空文本节点以保留格式
                    if (linkResult.length === 0 && hasFormattingProps(linkLeaf)) {
                        leafs.push(_object_spread_props(_object_spread({}, linkLeaf), {
                            text: ''
                        }));
                    }
                } else {
                    // 没有 URL，按普通文本处理
                    var textResult = parseText(n.children, leaf);
                    leafs = leafs.concat(textResult);
                }
                continue;
            }
            if (n.type === 'inlineCode') {
                var inlineCodeResult = handleInlineCode(n);
                leafs.push(_object_spread({}, leaf, inlineCodeResult));
                continue;
            }
            if (n.type === 'inlineMath') {
                var inlineMathValue = typeof n.value === 'string' ? n.value : '';
                if (shouldTreatInlineMathAsText(inlineMathValue)) {
                    leafs.push(_object_spread_props(_object_spread({}, leaf), {
                        text: "$".concat(inlineMathValue, "$")
                    }));
                } else {
                    leafs.push(_object_spread_props(_object_spread({}, leaf), {
                        type: 'inline-katex',
                        children: [
                            {
                                text: inlineMathValue
                            }
                        ]
                    }));
                }
                continue;
            }
            // @ts-ignore
            leafs.push(_object_spread_props(_object_spread({}, leaf), {
                text: n.value || ''
            }));
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return leafs;
};
/**
 * 应用HTML标签样式到元素（纯函数版本）
 * @param el - 目标元素对象
 * @param htmlTag - HTML标签数组，包含样式信息
 * @returns 返回应用了样式的新元素对象
 */ export var applyHtmlTagsToElement = function(el, htmlTag) {
    if (!htmlTag.length) {
        return el;
    }
    var result = _object_spread({}, el);
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = htmlTag[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var t = _step.value;
            if (t.tag === 'font') {
                result.color = t.color;
            }
            if (t.tag === 'sup') result.identifier = el.text;
            if (t.tag === 'sub') result.identifier = el.text;
            if (t.tag === 'code') result.code = true;
            if (t.tag === 'i') result.italic = true;
            if (t.tag === 'b' || t.tag === 'strong') result.bold = true;
            if (t.tag === 'del') result.strikethrough = true;
            if ((t.tag === 'span' || t.tag === 'font') && t.color) {
                result.highColor = t.color;
            }
            if (t.tag === 'a' && (t === null || t === void 0 ? void 0 : t.url)) {
                result.url = t === null || t === void 0 ? void 0 : t.url;
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return result;
};
/**
 * 处理文本和内联元素节点（纯函数版本）
 * @param currentElement - 当前处理的元素
 * @param htmlTag - HTML标签数组
 * @param applyInlineFormattingFn - 应用内联格式的函数
 * @param parseNodesFn - 解析节点的函数
 * @returns 处理后的元素对象
 */ export var handleTextAndInlineElementsPure = function(currentElement, htmlTag, applyInlineFormattingFn, parseNodesFn) {
    var elementType = currentElement.type;
    // 处理文本节点
    if (elementType === 'text') {
        var el = {
            text: currentElement.value
        };
        return htmlTag.length > 0 && currentElement.value ? applyHtmlTagsToElement(el, htmlTag) : el;
    }
    // 处理换行
    if (elementType === 'break') {
        return {
            text: '\n'
        };
    }
    // 处理内联代码（特殊处理，因为它没有 children）
    if (elementType === 'inlineCode') {
        var finished = currentElement.finished;
        var leaf = _object_spread({}, finished === false && {
            otherProps: {
                finished: finished
            }
        });
        var formattedLeaf = applyInlineFormattingFn(leaf, currentElement);
        var leafWithHtmlTags = applyHtmlTagsToElement(formattedLeaf, htmlTag);
        var inlineCodeResult = handleInlineCode(currentElement);
        return _object_spread({}, leafWithHtmlTags, inlineCodeResult);
    }
    // 处理内联元素（strong, link, emphasis, delete）
    var inlineElementTypes = [
        'strong',
        'link',
        'emphasis',
        'delete'
    ];
    if (inlineElementTypes.includes(elementType)) {
        var _currentElement_children, _parseNodesFn, _currentElement_children1;
        var finished1 = currentElement.finished;
        var leaf1 = _object_spread({}, finished1 === false && {
            otherProps: {
                finished: finished1
            }
        });
        var formattedLeaf1 = applyInlineFormattingFn(leaf1, currentElement);
        var leafWithHtmlTags1 = applyHtmlTagsToElement(formattedLeaf1, htmlTag);
        var hasHtmlChildren = currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.some(function(n) {
            return n.type === 'html';
        });
        return hasHtmlChildren ? _object_spread_props(_object_spread({}, (_parseNodesFn = parseNodesFn(currentElement === null || currentElement === void 0 ? void 0 : currentElement.children, false, currentElement)) === null || _parseNodesFn === void 0 ? void 0 : _parseNodesFn.at(0)), {
            url: leafWithHtmlTags1.url
        }) : parseText(((_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : _currentElement_children1.length) ? currentElement.children : [
            {
                value: (leafWithHtmlTags1 === null || leafWithHtmlTags1 === void 0 ? void 0 : leafWithHtmlTags1.url) || ''
            }
        ], leafWithHtmlTags1);
    }
    // 默认返回空文本
    return {
        text: ''
    };
};
