import React, { memo, useMemo, useRef } from "react";
import { renderMarkdownBlock } from "../markdownReactShared";
import { StreamingAnimationContext } from "../StreamingAnimationContext";
import { shouldReparseLastBlock } from "./lastBlockThrottle";
/**
 * 块级渲染单元：sealed 块缓存不动，tail 块节流重解析。
 */ 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);
    var cacheRef = useRef(new Map());
    var processorRef = useRef(null);
    /**
   * 宿主常把 `components: { __codeBlock: X }` 内联在每次 render，引用恒变。
   * 若列入 useMemo 依赖，末块晋升为 sealed 时会误触发重 parse，子树卸载重挂。
   * 密封命中缓存时故意不随 components 引用抖动；需重算时由 variant / blockSource / processor 驱动。
   */ var componentsRef = useRef(components);
    componentsRef.current = components;
    var node = useMemo(function() {
        if (processorRef.current !== processor) {
            processorRef.current = processor;
            cacheRef.current.clear();
            lastParsedRef.current = null;
        }
        var comps = componentsRef.current;
        if (variant === 'sealed') {
            var cached = cacheRef.current.get(blockSource);
            if (cached) return cached;
            var el = renderMarkdownBlock(blockSource, processor, comps);
            cacheRef.current.set(blockSource, el);
            return el;
        }
        // tail 块：不写入 cacheRef，仅用 lastParsedRef
        if (!streaming) {
            var el1 = renderMarkdownBlock(blockSource, processor, comps);
            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, comps);
        lastParsedRef.current = {
            source: blockSource,
            node: el2
        };
        return el2;
    }, [
        variant,
        blockSource,
        processor,
        streaming
    ]);
    var animateBlock = variant === 'tail' && streaming;
    return /*#__PURE__*/ React.createElement(StreamingAnimationContext.Provider, {
        value: {
            animateBlock: animateBlock
        }
    }, node);
});
MarkdownBlockPiece.displayName = 'MarkdownBlockPiece';
