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);
}
/**
 * @fileoverview 代码渲染器组件
 * 封装代码编辑器的所有渲染逻辑
 */ import { ConfigProvider, Skeleton, theme as antdTheme } from "antd";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { MarkdownEditor } from "../../../MarkdownEditor";
import { useEditorStore } from "../../../MarkdownEditor/editor/store";
import { useCodeEditorState, useRenderConditions, useToolbarConfig } from "../hooks";
import { openHtmlLocalPreview, openMarkdownLocalPreview } from "../utils/localPreview";
import { AceEditor, AceEditorContainer, CodeContainer, CodeToolbar, HtmlPreview, ThinkBlock } from "./index";
/**
 * 检测 HTML 代码中是否包含 JavaScript
 * @param htmlCode HTML 代码字符串
 * @returns 如果包含 JavaScript 返回 true，否则返回 false
 */ function containsJavaScript(htmlCode) {
    if (!htmlCode || typeof htmlCode !== 'string') {
        return false;
    }
    var code = htmlCode.toLowerCase().trim();
    // 检测 <script> 标签
    if (/<script[\s>]/.test(code) || /<\/script>/.test(code)) {
        return true;
    }
    // 检测事件处理器属性（onclick, onerror, onload 等）
    if (/on\w+\s*=/i.test(code)) {
        return true;
    }
    // 检测 javascript: URL
    if (/javascript\s*:/i.test(code)) {
        return true;
    }
    // 检测 eval() 调用
    if (/\beval\s*\(/i.test(code)) {
        return true;
    }
    // 检测 Function() 构造函数
    if (/\bFunction\s*\(/i.test(code)) {
        return true;
    }
    // 检测 setTimeout/setInterval 中的字符串代码
    if (/(setTimeout|setInterval)\s*\([^,]*['"`]/i.test(code)) {
        return true;
    }
    return false;
}
// 简单的 CSV -> Markdown table 转换器
/**
 * 代码渲染器组件
 *
 * 功能特性：
 * - 基于 Ace Editor 的代码编辑
 * - 支持 100+ 种编程语言语法高亮
 * - 支持代码复制、全屏编辑
 * - 支持 HTML 代码实时预览
 * - 支持拖拽排序
 * - 响应式布局适配
 * - 支持代码框选中状态管理
 */ export function CodeRenderer(props) {
    var _ref;
    var _editorProps_codeProps, _props_element_language, _props_element, _props_element1, _props_element2, _props_element_otherProps, _props_element3, _props_element_otherProps1, _props_element4, _editorProps_codeProps1, _editorProps_codeProps2;
    var _useEditorStore = useEditorStore(), editorProps = _useEditorStore.editorProps, readonly = _useEditorStore.readonly;
    // 使用状态管理Hook
    var _useCodeEditorState = useCodeEditorState(props.element), state = _useCodeEditorState.state, update = _useCodeEditorState.update, path = _useCodeEditorState.path, handleCloseClick = _useCodeEditorState.handleCloseClick, handleHtmlPreviewClose = _useCodeEditorState.handleHtmlPreviewClose, handleShowBorderChange = _useCodeEditorState.handleShowBorderChange, handleHideChange = _useCodeEditorState.handleHideChange;
    var _useState = _sliced_to_array(useState('github'), 2), theme = _useState[0], setTheme = _useState[1];
    var _useState1 = _sliced_to_array(useState(true), 2), isExpanded = _useState1[0], setIsExpanded = _useState1[1];
    // 选中状态管理
    var _React_useState = _sliced_to_array(React.useState(false), 2), isSelected = _React_useState[0], setIsSelected = _React_useState[1];
    // 视图模式状态管理（用于HTML和Markdown）
    // 如果是 markdown 或 html，默认打开预览模式
    // 但如果禁用了 HTML 预览，则强制使用代码模式
    var disableHtmlPreview = (_ref = (_editorProps_codeProps = editorProps.codeProps) === null || _editorProps_codeProps === void 0 ? void 0 : _editorProps_codeProps.disableHtmlPreview) !== null && _ref !== void 0 ? _ref : false;
    var language = (_props_element = props.element) === null || _props_element === void 0 ? void 0 : (_props_element_language = _props_element.language) === null || _props_element_language === void 0 ? void 0 : _props_element_language.toLowerCase();
    var htmlValue = ((_props_element1 = props.element) === null || _props_element1 === void 0 ? void 0 : _props_element1.value) || '';
    // 检测 HTML 代码中是否包含 JavaScript
    var hasJavaScript = language === 'html' && containsJavaScript(htmlValue);
    // 如果禁用了 HTML 预览或包含 JavaScript，强制使用代码模式
    var shouldDisablePreview = disableHtmlPreview || hasJavaScript;
    var _useState2 = _sliced_to_array(useState(function() {
        // 如果禁用了 HTML 预览或包含 JavaScript，强制使用代码模式
        if (shouldDisablePreview && language === 'html') {
            return 'code';
        }
        return language === 'html' || language === 'markdown' ? 'preview' : 'code';
    }), 2), viewMode = _useState2[0], setViewMode = _useState2[1];
    // 使用Ace编辑器Hook
    var _AceEditor = AceEditor({
        element: props.element,
        theme: theme,
        onUpdate: update,
        onShowBorderChange: handleShowBorderChange,
        onHideChange: handleHideChange,
        path: path,
        isSelected: isSelected,
        onSelectionChange: setIsSelected
    }), dom = _AceEditor.dom, setLanguage = _AceEditor.setLanguage, focusEditor = _AceEditor.focusEditor;
    // 使用渲染条件Hook
    var _useRenderConditions = useRenderConditions(props.element, readonly), shouldHideConfigHtml = _useRenderConditions.shouldHideConfigHtml, shouldRenderAsThinkBlock = _useRenderConditions.shouldRenderAsThinkBlock, shouldRenderAsCodeEditor = _useRenderConditions.shouldRenderAsCodeEditor;
    // 视图模式切换处理函数
    var handleViewModeToggle = function handleViewModeToggle() {
        // 如果禁用了 HTML 预览或包含 JavaScript，不允许切换到预览模式
        if (shouldDisablePreview && language === 'html') {
            setViewMode('code');
            return;
        }
        setViewMode(function(prev) {
            return prev === 'preview' ? 'code' : 'preview';
        });
    };
    // 本地预览处理函数
    var handleLocalPreview = useCallback(function() {
        var _props_element;
        var value = ((_props_element = props.element) === null || _props_element === void 0 ? void 0 : _props_element.value) || '';
        if (language === 'markdown') {
            openMarkdownLocalPreview(value);
        } else if (language === 'html') {
            openHtmlLocalPreview(value);
        }
    }, [
        language,
        (_props_element2 = props.element) === null || _props_element2 === void 0 ? void 0 : _props_element2.value
    ]);
    // 使用工具栏配置Hook
    var toolbarProps = useToolbarConfig({
        element: props.element,
        readonly: readonly,
        onCloseClick: handleCloseClick,
        setLanguage: setLanguage,
        onSelectionChange: setIsSelected,
        onViewModeToggle: handleViewModeToggle,
        viewMode: viewMode,
        onLocalPreview: handleLocalPreview
    }).toolbarProps;
    // 检查代码块是否未闭合
    var isUnclosed = ((_props_element3 = props.element) === null || _props_element3 === void 0 ? void 0 : (_props_element_otherProps = _props_element3.otherProps) === null || _props_element_otherProps === void 0 ? void 0 : _props_element_otherProps.finished) === false;
    // 5 秒超时机制：如果代码块未闭合，5 秒后自动设置为完成
    useEffect(function() {
        if (isUnclosed && !readonly) {
            var timer = setTimeout(function() {
                var _props_element_otherProps, _props_element;
                // 检查 finished 是否仍然是 false（可能已经被其他逻辑更新）
                if (((_props_element = props.element) === null || _props_element === void 0 ? void 0 : (_props_element_otherProps = _props_element.otherProps) === null || _props_element_otherProps === void 0 ? void 0 : _props_element_otherProps.finished) === false) {
                    var _props_element1;
                    update({
                        otherProps: _object_spread_props(_object_spread({}, (_props_element1 = props.element) === null || _props_element1 === void 0 ? void 0 : _props_element1.otherProps), {
                            finished: true
                        })
                    });
                }
            }, 5000); // 5 秒超时
            return function() {
                clearTimeout(timer);
            };
        }
    }, [
        isUnclosed,
        readonly,
        (_props_element4 = props.element) === null || _props_element4 === void 0 ? void 0 : (_props_element_otherProps1 = _props_element4.otherProps) === null || _props_element_otherProps1 === void 0 ? void 0 : _props_element_otherProps1.finished,
        update
    ]);
    // 如果禁用了 HTML 预览或包含 JavaScript，强制使用代码模式
    useEffect(function() {
        if (shouldDisablePreview && language === 'html' && viewMode === 'preview') {
            setViewMode('code');
        }
    }, [
        shouldDisablePreview,
        language,
        viewMode
    ]);
    // 渲染组件
    return useMemo(function() {
        // 配置型 HTML 代码块：如果未完成且内容较长，显示 skeleton
        if (shouldHideConfigHtml) {
            var _props_element_otherProps, _props_element, _props_element_value, _props_element1;
            var isUnclosed = ((_props_element = props.element) === null || _props_element === void 0 ? void 0 : (_props_element_otherProps = _props_element.otherProps) === null || _props_element_otherProps === void 0 ? void 0 : _props_element_otherProps.finished) === false;
            var contentLength = ((_props_element1 = props.element) === null || _props_element1 === void 0 ? void 0 : (_props_element_value = _props_element1.value) === null || _props_element_value === void 0 ? void 0 : _props_element_value.length) || 0;
            var isLongContent = contentLength > 100; // 内容超过 100 字符视为较长
            // 如果未完成且内容较长，显示 skeleton
            if (isUnclosed && isLongContent) {
                return /*#__PURE__*/ React.createElement("div", _object_spread_props(_object_spread({}, props.attributes), {
                    style: {
                        padding: '20px'
                    }
                }), /*#__PURE__*/ React.createElement(Skeleton, {
                    active: true,
                    paragraph: {
                        rows: 3
                    }
                }));
            }
            return null;
        }
        // 只读模式下的思考块特殊渲染
        if (shouldRenderAsThinkBlock) {
            return /*#__PURE__*/ React.createElement(ThinkBlock, props);
        }
        // 主要的代码编辑器渲染
        if (shouldRenderAsCodeEditor) {
            var _editorProps_codeProps, _props_element2, _props_element3;
            return /*#__PURE__*/ React.createElement(ConfigProvider, {
                theme: {
                    algorithm: theme === 'chaos' ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm
                }
            }, /*#__PURE__*/ React.createElement("div", props.attributes, /*#__PURE__*/ React.createElement(CodeContainer, {
                theme: theme,
                element: props.element,
                showBorder: state.showBorder,
                hide: state.hide,
                onEditorClick: focusEditor
            }, !props.element.frontmatter && !((_editorProps_codeProps = editorProps.codeProps) === null || _editorProps_codeProps === void 0 ? void 0 : _editorProps_codeProps.hideToolBar) && /*#__PURE__*/ React.createElement(CodeToolbar, _object_spread({
                theme: theme,
                setTheme: setTheme,
                isExpanded: isExpanded,
                onExpandToggle: function onExpandToggle() {
                    return setIsExpanded(!isExpanded);
                }
            }, toolbarProps)), /*#__PURE__*/ React.createElement("div", {
                className: "code-editor-content",
                style: {
                    borderBottomLeftRadius: 'inherit',
                    borderBottomRightRadius: 'inherit',
                    display: isExpanded ? 'block' : 'none'
                }
            }, viewMode === 'preview' && props.element.language === 'html' && !shouldDisablePreview && /*#__PURE__*/ React.createElement(HtmlPreview, {
                htmlStr: (_props_element2 = props.element) === null || _props_element2 === void 0 ? void 0 : _props_element2.value
            }), viewMode === 'preview' && props.element.language && props.element.language === 'markdown' && /*#__PURE__*/ React.createElement(MarkdownEditor, {
                initValue: (_props_element3 = props.element) === null || _props_element3 === void 0 ? void 0 : _props_element3.value
            }), /*#__PURE__*/ React.createElement("div", {
                style: {
                    height: '100%',
                    width: '100%',
                    borderRadius: 'inherit',
                    padding: '12px 0',
                    display: viewMode === 'code' ? 'block' : 'none'
                }
            }, /*#__PURE__*/ React.createElement(AceEditorContainer, {
                dom: dom,
                element: props.element
            }, props.children))))));
        }
        return null;
    }, [
        shouldHideConfigHtml,
        shouldRenderAsThinkBlock,
        shouldRenderAsCodeEditor,
        props.element,
        props.attributes,
        props.children,
        state.showBorder,
        state.hide,
        isSelected,
        (_editorProps_codeProps1 = editorProps.codeProps) === null || _editorProps_codeProps1 === void 0 ? void 0 : _editorProps_codeProps1.hideToolBar,
        (_editorProps_codeProps2 = editorProps.codeProps) === null || _editorProps_codeProps2 === void 0 ? void 0 : _editorProps_codeProps2.disableHtmlPreview,
        shouldDisablePreview,
        hasJavaScript,
        htmlValue,
        toolbarProps,
        handleHtmlPreviewClose,
        viewMode,
        handleViewModeToggle,
        disableHtmlPreview,
        handleLocalPreview
    ]);
}
