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 copy from "copy-to-clipboard";
import React, { useMemo, useState } from "react";
import { useRefFunction } from "../../Hooks/useRefFunction";
import { useDetectTheme } from "../../Plugins/chart/hooks";
import { CodeContainer } from "../../Plugins/code/components/CodeContainer";
import { debugInfo } from "../../Utils/debugUtils";
import { extractBlockTextContent } from "../extractBlockTextContent";
import { CodeBlockToolbar } from "./CodeBlockToolbar";
/**
 * 代码块渲染器——复用 MarkdownEditor 的 CodeContainer 和样式体系。
 * 不依赖 Slate 上下文，提供与 CodeRenderer readonly 模式一致的视觉效果。
 */ var CONTENT_OUTER_BASE_STYLE = {
    borderBottomLeftRadius: 'inherit',
    borderBottomRightRadius: 'inherit'
};
var CONTENT_INNER_STYLE = {
    height: '100%',
    width: '100%',
    borderRadius: 'inherit',
    padding: '12px 16px',
    overflow: 'auto',
    fontSize: '0.9em',
    lineHeight: 1.6,
    fontFamily: "'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace",
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-all'
};
/**
 * 计算代码内容外层容器样式：通过 display: none 实现折叠态。
 * 提取为函数以避免 inline 表达式让 React diff 失稳。
 */ var buildContentOuterStyle = function buildContentOuterStyle(expanded) {
    return _object_spread_props(_object_spread({}, CONTENT_OUTER_BASE_STYLE), {
        display: expanded ? 'block' : 'none'
    });
};
export var CodeBlockRenderer = function CodeBlockRenderer(props) {
    var language = props.language, children = props.children, editorCodeProps = props.editorCodeProps;
    var detectedTheme = useDetectTheme();
    var theme = (editorCodeProps === null || editorCodeProps === void 0 ? void 0 : editorCodeProps.theme) || (detectedTheme === 'dark' ? 'chaos' : 'github');
    var _useState = _sliced_to_array(useState(true), 2), isExpanded = _useState[0], setIsExpanded = _useState[1];
    var code = useMemo(function() {
        return extractBlockTextContent(children);
    }, [
        children
    ]);
    var fakeElement = useMemo(function() {
        return {
            type: 'code',
            language: language || '',
            value: code,
            children: [
                {
                    text: code
                }
            ]
        };
    }, [
        language,
        code
    ]);
    var handleCopy = useRefFunction(function() {
        try {
            copy(code);
        } catch (error) {
            debugInfo('CodeBlockRenderer - 复制失败', {
                error: (error === null || error === void 0 ? void 0 : error.message) || String(error)
            });
        }
    });
    var handleToggleExpanded = useRefFunction(function() {
        setIsExpanded(function(prev) {
            return !prev;
        });
    });
    var defaultDom = /*#__PURE__*/ React.createElement(CodeContainer, {
        element: fakeElement,
        showBorder: false,
        hide: false,
        onEditorClick: function onEditorClick() {}
    }, /*#__PURE__*/ React.createElement(CodeBlockToolbar, {
        language: language,
        expanded: isExpanded,
        theme: theme === 'chaos' ? 'dark' : 'light',
        onCopy: handleCopy,
        onToggleExpanded: handleToggleExpanded
    }), /*#__PURE__*/ React.createElement("div", {
        className: "code-editor-content",
        style: buildContentOuterStyle(isExpanded)
    }, /*#__PURE__*/ React.createElement("div", {
        style: CONTENT_INNER_STYLE
    }, /*#__PURE__*/ React.createElement("code", {
        className: language ? "language-".concat(language) : undefined
    }, children))));
    var customRender = editorCodeProps === null || editorCodeProps === void 0 ? void 0 : editorCodeProps.render;
    if (!customRender) {
        return defaultDom;
    }
    try {
        // customRender 接受 Slate-like 结构。MarkdownRenderer 不依赖 Slate，
        // 构造一个形状兼容的对象即可；因 customRender 的 `props` 类型为 `CustomLeaf<...> & { children }`，
        // 与此处 `element` 字段类型并不严格匹配，故在调用边界保留一次必要的类型断言。
        var renderElementProps = {
            attributes: {},
            children: null,
            element: fakeElement
        };
        var rendered = customRender(renderElementProps, defaultDom, editorCodeProps);
        if (rendered === undefined) {
            return defaultDom;
        }
        return rendered;
    } catch (error) {
        debugInfo('CodeBlockRenderer - codeProps.render 异常，回退默认', {
            error: (error === null || error === void 0 ? void 0 : error.message) || String(error)
        });
        return defaultDom;
    }
};
CodeBlockRenderer.displayName = 'CodeBlockRenderer';
