/**
 * @fileoverview 代码编辑器工具栏组件
 * 提供代码块的各种操作功能，包括语言切换、复制、运行等
 * @author Code Plugin Team
 */ import { CloseCircleOutlined } from "@ant-design/icons";
import { ChevronsUpDown, Copy, Moon } from "@sofa-design/icons";
import { message, Segmented } from "antd";
import copy from "copy-to-clipboard";
import React, { useContext, useMemo } from "react";
import { ActionIconBox } from "../../../Components/ActionIconBox";
import { I18nContext } from "../../../I18n";
import { useEditorStore } from "../../../MarkdownEditor/editor/store";
import { langIconMap } from "../langIconMap";
import { LanguageSelector } from "./LanguageSelector";
import { LoadImage } from "./LoadImage";
/**
 * 检测 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;
}
/**
 * 代码编辑器工具栏组件
 *
 * 功能：
 * - 语言选择器（非只读模式）
 * - 只读模式下的语言显示
 * - 复制代码功能
 * - 全屏切换功能
 * - HTML 代码运行功能（仅限 HTML 语言）
 * - 关闭功能（仅限公式和 mermaid）
 *
 * 布局：
 * - 左侧：语言选择器或语言显示
 * - 右侧：操作按钮组（关闭、运行、复制、全屏）
 *
 * @param props - 组件属性
 * @returns React 工具栏元素
 *
 * @example
 * ```tsx
 * <CodeToolbar
 *   element={codeElement}
 *   readonly={false}
 *   onCloseClick={() => setHidden(true)}
 *   languageSelectorProps={langProps}
 * />
 * ```
 */ export var CodeToolbar = function CodeToolbar(props) {
    var _ref;
    var _editorProps_codeProps, _editorProps_codeProps1, _element_language, _element_language1, _i18n_locale, _i18n_locale1, _i18n_locale2, _i18n_locale3;
    // 获取国际化上下文
    var i18n = useContext(I18nContext);
    // 获取编辑器配置
    var editorProps = useEditorStore().editorProps;
    var disableHtmlPreview = (_ref = (_editorProps_codeProps = editorProps.codeProps) === null || _editorProps_codeProps === void 0 ? void 0 : _editorProps_codeProps.disableHtmlPreview) !== null && _ref !== void 0 ? _ref : false;
    var viewModeLabels = (_editorProps_codeProps1 = editorProps.codeProps) === null || _editorProps_codeProps1 === void 0 ? void 0 : _editorProps_codeProps1.viewModeLabels;
    var element = props.element, readonly = props.readonly, onCloseClick = props.onCloseClick, languageSelectorProps = props.languageSelectorProps, onViewModeToggle = props.onViewModeToggle, theme = props.theme, isExpanded = props.isExpanded, onExpandToggle = props.onExpandToggle, setTheme = props.setTheme, _props_viewMode = props.viewMode, viewMode = _props_viewMode === void 0 ? 'code' : _props_viewMode;
    // 检测 HTML 代码中是否包含 JavaScript
    var hasJavaScript = useMemo(function() {
        var _element_language;
        var language = element === null || element === void 0 ? void 0 : (_element_language = element.language) === null || _element_language === void 0 ? void 0 : _element_language.toLowerCase();
        if (language === 'html') {
            return containsJavaScript((element === null || element === void 0 ? void 0 : element.value) || '');
        }
        return false;
    }, [
        element === null || element === void 0 ? void 0 : element.language,
        element === null || element === void 0 ? void 0 : element.value
    ]);
    // 如果禁用了 HTML 预览或包含 JavaScript，则禁用预览
    var shouldDisablePreview = disableHtmlPreview || hasJavaScript;
    return /*#__PURE__*/ React.createElement("div", {
        "data-testid": "code-toolbar",
        contentEditable: false,
        style: {
            borderTopLeftRadius: 'inherit',
            borderTopRightRadius: 'inherit',
            backgroundColor: 'transparent',
            paddingLeft: '0.25em',
            paddingRight: '0.25em',
            width: '100%',
            position: 'sticky',
            left: 0,
            top: 0,
            fontSize: '1em',
            font: 'var(--font-text-h6-base)',
            color: 'inherit',
            justifyContent: 'space-between',
            zIndex: 50,
            height: '38px',
            display: 'flex',
            alignItems: 'center',
            padding: '9px 12px',
            gap: '16px',
            alignSelf: 'stretch',
            boxSizing: 'border-box',
            userSelect: 'none',
            borderBottom: isExpanded ? theme === 'chaos' ? '1px solid #161616' : '1px solid var(--color-gray-border-light)' : 'none'
        }
    }, /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            alignItems: 'center',
            gap: 8
        }
    }, readonly ? // 只读模式：仅显示当前语言信息
    /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            alignItems: 'center',
            cursor: 'pointer',
            gap: 4,
            font: 'inherit',
            color: 'inherit',
            userSelect: 'none'
        },
        contentEditable: false
    }, langIconMap.get(((_element_language = element.language) === null || _element_language === void 0 ? void 0 : _element_language.toLowerCase()) || '') && !element.katex && /*#__PURE__*/ React.createElement("div", {
        style: {
            height: '1em',
            width: '1em',
            fontSize: '16px',
            display: 'flex'
        }
    }, /*#__PURE__*/ React.createElement(LoadImage, {
        style: {
            height: '1em',
            width: '1em'
        },
        src: langIconMap.get(((_element_language1 = element.language) === null || _element_language1 === void 0 ? void 0 : _element_language1.toLowerCase()) || '')
    })), /*#__PURE__*/ React.createElement("div", null, element.language ? /*#__PURE__*/ React.createElement("span", null, element.katex ? 'Formula' : element.language === 'html' && element.render ? 'Html Renderer' : element.language) : /*#__PURE__*/ React.createElement("span", null, 'plain text'))) : // 非只读模式：显示语言选择器
    /*#__PURE__*/ React.createElement(LanguageSelector, languageSelectorProps)), /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            gap: 5,
            alignItems: 'center'
        }
    }, element.katex || element.language === 'mermaid' ? /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: (i18n === null || i18n === void 0 ? void 0 : (_i18n_locale = i18n.locale) === null || _i18n_locale === void 0 ? void 0 : _i18n_locale.close) || '关闭',
        onClick: onCloseClick,
        theme: theme === 'chaos' ? 'dark' : 'light'
    }, /*#__PURE__*/ React.createElement(CloseCircleOutlined, null)) : null, (element === null || element === void 0 ? void 0 : element.language) === 'html' && !shouldDisablePreview || (element === null || element === void 0 ? void 0 : element.language) === 'markdown' ? /*#__PURE__*/ React.createElement(Segmented, {
        className: theme === 'chaos' ? 'chaos-segmented' : '',
        "data-testid": "preview",
        options: [
            {
                label: (viewModeLabels === null || viewModeLabels === void 0 ? void 0 : viewModeLabels.preview) || '预览',
                value: 'preview'
            },
            {
                label: (viewModeLabels === null || viewModeLabels === void 0 ? void 0 : viewModeLabels.code) || '代码',
                value: 'code'
            }
        ],
        value: viewMode,
        onChange: function onChange(value) {
            return onViewModeToggle === null || onViewModeToggle === void 0 ? void 0 : onViewModeToggle(value);
        }
    }) : null, /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: (i18n === null || i18n === void 0 ? void 0 : (_i18n_locale1 = i18n.locale) === null || _i18n_locale1 === void 0 ? void 0 : _i18n_locale1.theme) || '主题',
        theme: theme === 'chaos' ? 'dark' : 'light',
        onClick: function onClick() {
            setTheme(theme === 'github' ? 'chaos' : 'github');
        }
    }, /*#__PURE__*/ React.createElement(Moon, null)), /*#__PURE__*/ React.createElement(ActionIconBox, {
        theme: theme === 'chaos' ? 'dark' : 'light',
        title: (i18n === null || i18n === void 0 ? void 0 : (_i18n_locale2 = i18n.locale) === null || _i18n_locale2 === void 0 ? void 0 : _i18n_locale2.copy) || '复制',
        style: {
            fontSize: '1em',
            lineHeight: '1.75em',
            marginLeft: '0.125em'
        },
        onClick: function onClick(e) {
            e.stopPropagation();
            try {
                var _i18n_locale;
                var code = element.value || '';
                copy(code);
                // 显示成功提示
                message.success(((_i18n_locale = i18n.locale) === null || _i18n_locale === void 0 ? void 0 : _i18n_locale.copySuccess) || '复制成功');
            } catch (error) {
                // 复制失败时静默处理
                console.error('复制失败:', error);
            }
        }
    }, /*#__PURE__*/ React.createElement(Copy, null)), /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: (i18n === null || i18n === void 0 ? void 0 : (_i18n_locale3 = i18n.locale) === null || _i18n_locale3 === void 0 ? void 0 : _i18n_locale3.expandCollapse) || '展开/收起',
        theme: theme === 'chaos' ? 'dark' : 'light',
        onClick: function onClick() {
            onExpandToggle === null || onExpandToggle === void 0 ? void 0 : onExpandToggle();
        }
    }, /*#__PURE__*/ React.createElement(ChevronsUpDown, null))));
};
