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 _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 _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);
}
/**
 * @fileoverview 思考块组件
 * 只读模式下渲染思考类型的代码块
 */ import { useMergedState } from "rc-util";
import React, { createContext, useContext, useEffect, useMemo, useRef } from "react";
import { MessagesContext } from "../../../Bubble/MessagesContent/BubbleContext";
import { I18nContext } from "../../../I18n";
import { EditorStoreContext, useEditorStore } from "../../../MarkdownEditor/editor/store";
import { EditorUtils } from "../../../MarkdownEditor/editor/utils/editorUtils";
import { ToolUseBarThink } from "../../../ToolUseBarThink";
/**
 * ThinkBlock Context
 */ export var ThinkBlockContext = /*#__PURE__*/ createContext(null);
/**
 * ThinkBlock Provider 组件
 *
 * 用于全局控制所有 ThinkBlock 实例的展开/收起状态
 *
 * @example
 * ```tsx
 * <ThinkBlockProvider expanded={isExpanded} onExpandedChange={setIsExpanded}>
 *   <MarkdownEditor ... />
 * </ThinkBlockProvider>
 * ```
 */ export var ThinkBlockProvider = function ThinkBlockProvider(param) {
    var expanded = param.expanded, onExpandedChange = param.onExpandedChange, children = param.children;
    return /*#__PURE__*/ React.createElement(ThinkBlockContext.Provider, {
        value: {
            expanded: expanded,
            onExpandedChange: onExpandedChange
        }
    }, children);
};
/**
 * 将特殊标记恢复为代码块格式
 * @param content - 包含特殊标记的内容
 * @returns 恢复后的内容
 */ var restoreCodeBlocks = function restoreCodeBlocks(content) {
    var marker = '\u200B'; // 零宽空格
    // 将格式：【CODE_BLOCK:lang】code【/CODE_BLOCK】
    // 恢复为：```lang\ncode\n```
    return content.replace(new RegExp("".concat(marker, "【CODE_BLOCK:([\\w]*)】\\n?([\\s\\S]*?)\\n?【/CODE_BLOCK】").concat(marker), 'g'), function(_, lang, code) {
        return "```".concat(lang, "\n").concat(code, "\n```");
    });
};
export function ThinkBlock(props) {
    var _ref, _ref1;
    var _editorProps_codeProps, _editorProps_codeProps1;
    var element = props.element;
    var locale = useContext(I18nContext).locale;
    var editorProps = (useContext(EditorStoreContext) || {}).editorProps;
    var message = useContext(MessagesContext).message;
    var markdownEditorRef = useEditorStore().markdownEditorRef;
    var thinkBlockContext = useContext(ThinkBlockContext);
    // 获取当前 Bubble 的 isFinished 状态
    var bubbleIsFinished = message === null || message === void 0 ? void 0 : message.isFinished;
    // 获取当前元素的 path
    var elementPath = useMemo(function() {
        if (!markdownEditorRef.current) {
            return null;
        }
        try {
            return EditorUtils.findPath(markdownEditorRef.current, element);
        } catch (error) {
            console.error('Error finding element path:', error);
            return null;
        }
    }, [
        markdownEditorRef.current,
        element
    ]);
    // 判断是否是最后一个节点
    var isLastNode = useMemo(function() {
        if (!markdownEditorRef.current || !elementPath) {
            return false;
        }
        try {
            return EditorUtils.checkSelEnd(markdownEditorRef.current, elementPath);
        } catch (error) {
            console.error('Error checking if last node:', error);
            return false;
        }
    }, [
        markdownEditorRef.current,
        elementPath
    ]);
    // 状态优先级（从高到低）：
    // 1. Context 提供的 expanded（受控模式）
    // 2. editorProps?.codeProps?.alwaysExpandedDeepThink
    // 3. 默认值（false）
    var _useMergedState = _sliced_to_array(useMergedState((_ref = editorProps === null || editorProps === void 0 ? void 0 : (_editorProps_codeProps = editorProps.codeProps) === null || _editorProps_codeProps === void 0 ? void 0 : _editorProps_codeProps.alwaysExpandedDeepThink) !== null && _ref !== void 0 ? _ref : false, {
        value: (editorProps === null || editorProps === void 0 ? void 0 : (_editorProps_codeProps1 = editorProps.codeProps) === null || _editorProps_codeProps1 === void 0 ? void 0 : _editorProps_codeProps1.alwaysExpandedDeepThink) ? true : (_ref1 = thinkBlockContext === null || thinkBlockContext === void 0 ? void 0 : thinkBlockContext.expanded) !== null && _ref1 !== void 0 ? _ref1 : undefined,
        defaultValue: false,
        onChange: thinkBlockContext === null || thinkBlockContext === void 0 ? void 0 : thinkBlockContext.onExpandedChange
    }), 2), expanded = _useMergedState[0], setExpanded = _useMergedState[1];
    // 当 bubble 完成时，自动展开
    useEffect(function() {
        if (bubbleIsFinished) {
            setExpanded(false);
        }
    }, [
        bubbleIsFinished
    ]);
    // 如果不是最后一个节点，自动收起
    useEffect(function() {
        if (!isLastNode) {
            setExpanded(false);
        }
    }, [
        isLastNode
    ]);
    // 跟踪 thinkBlockContext?.expanded 的之前值
    var prevExpandedRef = useRef(thinkBlockContext === null || thinkBlockContext === void 0 ? void 0 : thinkBlockContext.expanded);
    // 当 thinkBlockContext?.expanded 从其他值变成 undefined 时，自动收起
    useEffect(function() {
        var prevExpanded = prevExpandedRef.current;
        var currentExpanded = thinkBlockContext === null || thinkBlockContext === void 0 ? void 0 : thinkBlockContext.expanded;
        // 如果之前有值（true 或 false），现在变成 undefined，则收起
        if (prevExpanded !== undefined && currentExpanded === undefined) {
            setExpanded(false);
        }
        // 更新之前的值
        prevExpandedRef.current = currentExpanded;
    }, [
        thinkBlockContext === null || thinkBlockContext === void 0 ? void 0 : thinkBlockContext.expanded
    ]);
    var rawContent = (element === null || element === void 0 ? void 0 : element.value) !== null && (element === null || element === void 0 ? void 0 : element.value) !== undefined ? String(element.value).trim() : '';
    // 恢复内容中被转义的代码块
    var content = restoreCodeBlocks(rawContent);
    // 判断是否正在加载：内容以...结尾 或者 bubble 还未完成
    var isLoading = content.endsWith('...');
    var toolNameText = isLoading ? (locale === null || locale === void 0 ? void 0 : locale['think.deepThinkingInProgress']) || '深度思考...' : (locale === null || locale === void 0 ? void 0 : locale['think.deepThinking']) || '深度思考';
    var thinkBlockRootStyles = useMemo(function() {
        return {
            root: {
                boxSizing: 'border-box',
                maxWidth: '680px',
                marginTop: 8
            }
        };
    }, []);
    return /*#__PURE__*/ React.createElement(ToolUseBarThink, {
        testId: "think-block",
        styles: thinkBlockRootStyles,
        expanded: expanded,
        onExpandedChange: setExpanded,
        toolName: toolNameText,
        thinkContent: content,
        status: isLoading ? 'loading' : 'success'
    });
}
