function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
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 _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { ConfigProvider } from "antd";
import clsx from "clsx";
import React, { forwardRef, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { useStyle as useContentStyle } from "../MarkdownEditor/editor/style";
import { useStyle as useEditorStyle } from "../MarkdownEditor/style";
import { CharacterQueue } from "./CharacterQueue";
import { DefaultCodeRouter } from "./DefaultCodeRouter";
import { extractFootnoteDefinitionsFromMarkdown } from "./extractFootnoteDefinitions";
import { useRendererVarStyle } from "./style";
import { useMarkdownToReact } from "./useMarkdownToReact";
import { useStreaming } from "./useStreaming";
/**
 * 从插件列表中收集 rendererComponents
 */ var collectRendererComponents = function collectRendererComponents(plugins) {
    var components = {};
    if (!plugins) return components;
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var plugin = _step.value;
            var renderer = plugin.renderer;
            if (renderer === null || renderer === void 0 ? void 0 : renderer.rendererComponents) {
                Object.assign(components, renderer.rendererComponents);
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return components;
};
/** 轻量流式 Markdown 渲染器——无 Slate 实例，Markdown → hast → React */ var InternalMarkdownRenderer = /*#__PURE__*/ forwardRef(function(props, ref) {
    var content = props.content, _props_streaming = props.streaming, streaming = _props_streaming === void 0 ? false : _props_streaming, isFinished = props.isFinished, queueOptions = props.queueOptions, plugins = props.plugins, remarkPlugins = props.remarkPlugins, htmlConfig = props.htmlConfig, className = props.className, style = props.style, customPrefixCls = props.prefixCls, linkConfig = props.linkConfig, streamingParagraphAnimation = props.streamingParagraphAnimation, apaasify = props.apaasify, eleRender = props.eleRender, fileMapConfig = props.fileMapConfig, fncProps = props.fncProps, editorCodeProps = props.codeProps;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    // 复用 MarkdownEditor 的 CSS 前缀和样式，保持渲染一致性
    var prefixCls = getPrefixCls('agentic-md-editor', customPrefixCls);
    var _useEditorStyle = useEditorStyle(prefixCls), wrapSSR = _useEditorStyle.wrapSSR, hashId = _useEditorStyle.hashId;
    // 注册 content 层的样式（段落间距、链接、blockquote 等）
    var contentCls = "".concat(prefixCls, "-content");
    var _useContentStyle = useContentStyle(contentCls, {}), wrapContentSSR = _useContentStyle.wrapSSR;
    // 注册间距 CSS 变量回退值（:where 低优先级，不覆盖宿主定义）
    var _useRendererVarStyle = useRendererVarStyle(prefixCls), wrapVarSSR = _useRendererVarStyle.wrapSSR;
    var containerRef = useRef(null);
    var _useState = _sliced_to_array(useState(content || ''), 2), displayedContent = _useState[0], setDisplayedContent = _useState[1];
    var queueRef = useRef(null);
    /** 与 CharacterQueue 构造参数同步，避免 queueOptions 变更后仍用旧队列行为 */ var queueOptsSigRef = useRef('');
    useImperativeHandle(ref, function() {
        return {
            nativeElement: containerRef.current,
            getDisplayedContent: function getDisplayedContent() {
                return displayedContent;
            }
        };
    });
    // 收集插件的 rendererComponents
    var pluginComponents = useMemo(function() {
        return collectRendererComponents(plugins);
    }, [
        plugins
    ]);
    // 字符队列：默认关闭逐字动画，避免 RAF 每帧全量重解析 Markdown 导致整页闪动。
    // 需要打字机效果时显式传入 queueOptions={{ animate: true, animateTailChars?: number }}。
    var resolvedQueueOptions = useMemo(function() {
        return streaming ? _object_spread({
            animate: false,
            animateTailChars: undefined
        }, queueOptions) : queueOptions;
    }, [
        streaming,
        queueOptions
    ]);
    useEffect(function() {
        if (!streaming) {
            var _queueRef_current;
            (_queueRef_current = queueRef.current) === null || _queueRef_current === void 0 ? void 0 : _queueRef_current.dispose();
            queueRef.current = null;
            queueOptsSigRef.current = '';
            setDisplayedContent(content || '');
            return;
        }
        var sig = JSON.stringify(resolvedQueueOptions !== null && resolvedQueueOptions !== void 0 ? resolvedQueueOptions : {});
        if (!queueRef.current || sig !== queueOptsSigRef.current) {
            var _queueRef_current1;
            (_queueRef_current1 = queueRef.current) === null || _queueRef_current1 === void 0 ? void 0 : _queueRef_current1.dispose();
            queueRef.current = new CharacterQueue(function(displayed) {
                return setDisplayedContent(displayed);
            }, resolvedQueueOptions);
            queueOptsSigRef.current = sig;
        }
        queueRef.current.push(content || '');
        if (isFinished) {
            queueRef.current.complete();
        }
    }, [
        content,
        streaming,
        resolvedQueueOptions,
        isFinished
    ]);
    // 清理
    useEffect(function() {
        return function() {
            var _queueRef_current;
            (_queueRef_current = queueRef.current) === null || _queueRef_current === void 0 ? void 0 : _queueRef_current.dispose();
            queueRef.current = null;
        };
    }, []);
    useEffect(function() {
        var notify = fncProps === null || fncProps === void 0 ? void 0 : fncProps.onFootnoteDefinitionChange;
        if (!notify) return;
        notify(extractFootnoteDefinitionsFromMarkdown(displayedContent || ''));
    }, [
        displayedContent,
        fncProps === null || fncProps === void 0 ? void 0 : fncProps.onFootnoteDefinitionChange
    ]);
    // 构建组件映射
    // code 渲染器通过 pre override 在 useMarkdownToReact 中路由，
    // 不直接映射到 <code> 标签（否则会影响行内代码 `code`）
    var apaasifyRender = useMemo(function() {
        if ((apaasify === null || apaasify === void 0 ? void 0 : apaasify.enable) && apaasify.render) return apaasify.render;
        return undefined;
    }, [
        apaasify
    ]);
    var components = useMemo(function() {
        var codeRouter = function codeRouter(blockProps) {
            return /*#__PURE__*/ React.createElement(DefaultCodeRouter, _object_spread_props(_object_spread({}, blockProps), {
                pluginComponents: pluginComponents,
                apaasifyRender: apaasifyRender,
                fileMapConfig: fileMapConfig,
                editorCodeProps: editorCodeProps
            }));
        };
        codeRouter.displayName = 'CodeRouter';
        return _object_spread({
            __codeBlock: codeRouter
        }, pluginComponents);
    }, [
        pluginComponents,
        apaasifyRender,
        fileMapConfig,
        editorCodeProps
    ]);
    // 流式缓存：将不完整的 Markdown token 暂缓，避免 parser 错误解析
    var safeContent = useStreaming(displayedContent, streaming);
    var reactContent = useMarkdownToReact(safeContent, {
        remarkPlugins: remarkPlugins,
        htmlConfig: htmlConfig,
        components: components,
        prefixCls: prefixCls,
        linkConfig: linkConfig,
        fncProps: fncProps,
        streaming: streaming,
        streamingParagraphAnimation: streamingParagraphAnimation,
        contentRevisionSource: streaming ? displayedContent : undefined,
        eleRender: eleRender
    });
    return wrapVarSSR(wrapSSR(wrapContentSSR(/*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        className: clsx(prefixCls, "".concat(prefixCls, "-readonly"), hashId, className),
        "data-testid": "markdown-renderer",
        style: style
    }, /*#__PURE__*/ React.createElement("div", {
        className: clsx("".concat(prefixCls, "-container"), hashId),
        style: {
            display: 'block'
        }
    }, /*#__PURE__*/ React.createElement("div", {
        className: clsx(contentCls, "".concat(contentCls, "-markdown-readonly"), hashId),
        style: {
            whiteSpace: 'normal',
            wordWrap: 'normal'
        }
    }, reactContent))))));
});
InternalMarkdownRenderer.displayName = 'MarkdownRenderer';
export default InternalMarkdownRenderer;
