import React, { memo, useMemo, useRef } from "react";
import { renderMarkdownBlock } from "../markdownReactShared";
import { StreamingAnimationContext } from "../StreamingAnimationContext";
import { shouldReparseLastBlock } from "./lastBlockThrottle";
/**
 * 统一的块级渲染：封版与末块使用同一组件类型；按 blockSource 缓存解析结果引用，使 tail→sealed 时与旧 Map 缓存一样复用同一棵 React 子树。
 */ export var MarkdownBlockPiece = /*#__PURE__*/ memo(function MarkdownBlockPiece(param) {
    var variant = param.variant, blockSource = param.blockSource, processor = param.processor, components = param.components, streaming = param.streaming;
    var lastParsedRef = useRef(null);
    /** 完整 parse 结果缓存：键为 block 源串，供 sealed 与 tail 晋升时复用同一引用 */ var parseBySourceRef = useRef(new Map());
    var node = useMemo(function() {
        var cached = parseBySourceRef.current.get(blockSource);
        if (cached && variant === 'sealed') {
            return cached;
        }
        if (variant === 'sealed') {
            var el = renderMarkdownBlock(blockSource, processor, components, {
                markStreamingTailParagraph: false
            });
            parseBySourceRef.current.set(blockSource, el);
            return el;
        }
        if (!streaming) {
            var el1 = renderMarkdownBlock(blockSource, processor, components, {
                markStreamingTailParagraph: false
            });
            parseBySourceRef.current.set(blockSource, el1);
            lastParsedRef.current = {
                source: blockSource,
                node: el1
            };
            return el1;
        }
        var prev = lastParsedRef.current;
        if (prev && !shouldReparseLastBlock(prev.source, blockSource, true)) {
            return prev.node;
        }
        var el2 = renderMarkdownBlock(blockSource, processor, components, {
            markStreamingTailParagraph: true
        });
        parseBySourceRef.current.set(blockSource, el2);
        lastParsedRef.current = {
            source: blockSource,
            node: el2
        };
        return el2;
    }, [
        variant,
        blockSource,
        processor,
        components,
        streaming
    ]);
    var animateBlock = variant === 'tail' && streaming;
    return /*#__PURE__*/ React.createElement(StreamingAnimationContext.Provider, {
        value: {
            animateBlock: animateBlock
        }
    }, node);
});
MarkdownBlockPiece.displayName = 'MarkdownBlockPiece';
