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 _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(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(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread 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 _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 _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
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 { DeleteOutlined, InsertRowLeftOutlined, InsertRowRightOutlined } from "@ant-design/icons";
import { ConfigProvider } from "antd";
import classNames from "classnames";
import React, { useContext, useRef } from "react";
import { Editor, Transforms } from "slate";
import { ReactEditor, useSlate } from "slate-react";
import { useClickAway } from "../../../../../Hooks/useClickAway";
import { useRefFunction } from "../../../../../Hooks/useRefFunction";
import { NativeTableEditor } from "../../../../utils/native-table";
import { TablePropsContext } from "../TableContext";
import { useStyle } from "./style";
/**
 * TableCellIndexSpacer 组件 - 表格索引间隔单元格组件
 *
 * 该组件用于渲染表格行索引中的间隔单元格，用于占位和布局。
 * 使用 context 来生成 className，支持样式自定义。
 *
 * @component
 * @description 表格索引间隔单元格组件，用于占位和布局
 * @param {TableCellIndexSpacerProps} props - 组件属性
 * @param {React.CSSProperties} [props.style] - 自定义样式
 * @param {string} [props.className] - 自定义类名
 * @param {React.Key} [props.key] - 单元格的唯一标识
 * @param {number} [props.columnIndex] - 列索引，用于选中整列
 * @param {number[]} [props.tablePath] - 表格路径，用于定位表格元素
 *
 * @example
 * ```tsx
 * <TableCellIndexSpacer
 *   style={{ backgroundColor: '#f5f5f5' }}
 *   className="custom-spacer-cell"
 *   key={0}
 *   columnIndex={1}
 *   tablePath={[0, 2]}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的表格索引间隔单元格组件
 *
 * @remarks
 * - 使用 ConfigProvider context 生成 className
 * - 支持自定义样式覆盖
 * - 不可编辑状态
 * - 用于占位和布局
 * - 支持点击选中整列功能
 */ export var TableCellIndexSpacer = function(param) {
    var style = param.style, className = param.className, columnIndex = param.columnIndex, tablePath = param.tablePath;
    var context = useContext(ConfigProvider.ConfigContext);
    var baseClassName = context === null || context === void 0 ? void 0 : context.getPrefixCls('agentic-md-editor-table-cell-index-spacer');
    var _useStyle = useStyle(baseClassName), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var editor = useSlate();
    var tableContext = useContext(TablePropsContext);
    var deleteIconPosition = tableContext.deleteIconPosition, setDeleteIconPosition = tableContext.setDeleteIconPosition;
    var clearSelect = useRefFunction(function() {
        var clearIcon = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
        var _tableElement_children;
        if (clearIcon) {
            setDeleteIconPosition === null || setDeleteIconPosition === void 0 ? void 0 : setDeleteIconPosition(null);
        }
        if (!tablePath) return;
        var tableElement = Editor.node(editor, tablePath)[0];
        if (!tableElement || tableElement.type !== 'table') return;
        var rowCount = ((_tableElement_children = tableElement.children) === null || _tableElement_children === void 0 ? void 0 : _tableElement_children.length) || 0;
        if (rowCount === 0) return;
        for(var rowIndex = 0; rowIndex < rowCount; rowIndex++){
            var rowElement = tableElement.children[rowIndex];
            if (rowElement && rowElement.children) {
                for(var colIndex = 0; colIndex < rowElement.children.length; colIndex++){
                    var cellPath = _to_consumable_array(tablePath).concat([
                        rowIndex,
                        colIndex
                    ]);
                    if (Editor.hasPath(editor, cellPath)) {
                        var _Editor_node = _sliced_to_array(Editor.node(editor, cellPath), 1), cellNode = _Editor_node[0];
                        if (cellNode && cellNode.type === 'table-cell') {
                            var domNode = ReactEditor.toDOMNode(editor, cellNode);
                            if (domNode) {
                                domNode.removeAttribute('data-select');
                            }
                        }
                    }
                }
            }
        }
    });
    /**
   * 处理点击事件，选中整列或显示删除图标
   */ var handleClick = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        // 如果提供了列索引，显示删除图标
        setDeleteIconPosition === null || setDeleteIconPosition === void 0 ? void 0 : setDeleteIconPosition({
            columnIndex: columnIndex
        });
        if (columnIndex === undefined || !tablePath) {
            return;
        }
        try {
            var _tableElement_children;
            // 获取表格元素
            var tableElement = Editor.node(editor, tablePath)[0];
            if (!tableElement || tableElement.type !== 'table') {
                return;
            }
            // 获取表格的行数
            var rowCount = ((_tableElement_children = tableElement.children) === null || _tableElement_children === void 0 ? void 0 : _tableElement_children.length) || 0;
            if (rowCount === 0) {
                return;
            }
            // 根据 columnIndex 的值决定选中逻辑
            if (columnIndex === -1) {
                // 选中所有单元格 - 只使用 DOM 操作
                for(var rowIndex = 0; rowIndex < rowCount; rowIndex++){
                    var rowElement = tableElement.children[rowIndex];
                    if (rowElement && rowElement.children) {
                        for(var colIndex = 0; colIndex < rowElement.children.length; colIndex++){
                            var cellPath = _to_consumable_array(tablePath).concat([
                                rowIndex,
                                colIndex
                            ]);
                            if (Editor.hasPath(editor, cellPath)) {
                                var _Editor_node = _sliced_to_array(Editor.node(editor, cellPath), 1), cellNode = _Editor_node[0];
                                if (cellNode && cellNode.type === 'table-cell') {
                                    // 只使用 DOM 操作设置 data-select 属性
                                    var domNode = ReactEditor.toDOMNode(editor, cellNode);
                                    if (domNode) {
                                        domNode.setAttribute('data-select', 'true');
                                    }
                                }
                            }
                        }
                    }
                }
                return;
            }
            clearSelect(false);
            // 选中指定列的所有单元格 - 只使用 DOM 操作
            for(var rowIndex1 = 0; rowIndex1 < rowCount; rowIndex1++){
                var cellPath1 = _to_consumable_array(tablePath).concat([
                    rowIndex1,
                    columnIndex
                ]);
                if (Editor.hasPath(editor, cellPath1)) {
                    var _Editor_node1 = _sliced_to_array(Editor.node(editor, cellPath1), 1), cellNode1 = _Editor_node1[0];
                    if (cellNode1 && cellNode1.type === 'table-cell') {
                        // 只使用 DOM 操作设置 data-select 属性
                        var domNode1 = ReactEditor.toDOMNode(editor, cellNode1);
                        if (domNode1) {
                            domNode1.setAttribute('data-select', 'true');
                        }
                    }
                }
            }
        } catch (error) {
            console.warn('Failed to select table column:', error);
        }
    });
    /**
   * 处理删除图标点击事件
   */ var handleDeleteClick = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        try {
            if (!tablePath || columnIndex === undefined) {
                return;
            }
            // 获取表格元素
            var tableElement = Editor.node(editor, tablePath)[0];
            if (!tableElement || tableElement.type !== 'table') {
                return;
            }
            var rowCount = tableElement.children.length;
            var firstRow = tableElement.children[0];
            var colCount = firstRow.children.length;
            // 检查是否只有一列
            if (colCount <= 1) {
                // 如果只有一列，删除整个表格
                NativeTableEditor.removeTable(editor, tablePath);
                return;
            }
            // 删除每一行的指定列
            for(var rowIndex = 0; rowIndex < rowCount; rowIndex++){
                var cellPath = _to_consumable_array(tablePath).concat([
                    rowIndex,
                    columnIndex
                ]);
                if (Editor.hasPath(editor, cellPath)) {
                    Transforms.removeNodes(editor, {
                        at: cellPath
                    });
                }
            }
            clearSelect();
        } catch (error) {
            console.warn('Failed to delete table column:', error);
        }
    });
    /**
   * 处理在前面增加一列点击事件
   */ var handleInsertColumnBefore = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        try {
            if (!tablePath || columnIndex === undefined) {
                return;
            }
            // 获取表格元素
            var tableElement = Editor.node(editor, tablePath)[0];
            if (!tableElement || tableElement.type !== 'table') {
                return;
            }
            var rowCount = tableElement.children.length;
            // 为每一行在当前列之前插入新单元格
            for(var rowIndex = 0; rowIndex < rowCount; rowIndex++){
                var cellPath = _to_consumable_array(tablePath).concat([
                    rowIndex,
                    columnIndex
                ]);
                var newCell = {
                    type: 'table-cell',
                    children: [
                        {
                            type: 'paragraph',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        }
                    ]
                };
                Transforms.insertNodes(editor, newCell, {
                    at: cellPath
                });
            }
            clearSelect();
        } catch (error) {
            console.warn('Failed to insert column before:', error);
        }
    });
    /**
   * 处理在后面增加一列点击事件
   */ var handleInsertColumnAfter = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        try {
            if (!tablePath || columnIndex === undefined) {
                return;
            }
            // 获取表格元素
            var tableElement = Editor.node(editor, tablePath)[0];
            if (!tableElement || tableElement.type !== 'table') {
                return;
            }
            var rowCount = tableElement.children.length;
            // 为每一行在当前列之后插入新单元格
            for(var rowIndex = 0; rowIndex < rowCount; rowIndex++){
                var cellPath = _to_consumable_array(tablePath).concat([
                    rowIndex,
                    columnIndex + 1
                ]);
                var newCell = {
                    type: 'table-cell',
                    children: [
                        {
                            type: 'paragraph',
                            children: [
                                {
                                    text: ''
                                }
                            ]
                        }
                    ]
                };
                Transforms.insertNodes(editor, newCell, {
                    at: cellPath
                });
            }
            clearSelect();
        } catch (error) {
            console.warn('Failed to insert column after:', error);
        }
    });
    var ref = useRef(null);
    useClickAway(function() {
        if (deleteIconPosition && deleteIconPosition.columnIndex === columnIndex) {
            clearSelect();
        }
    }, ref);
    // 检查是否应该显示删除图标
    var shouldShowDeleteIcon = deleteIconPosition && deleteIconPosition.columnIndex === columnIndex;
    // 判断是否应该显示增加列的按钮（总是显示）
    var shouldShowInsertButtons = shouldShowDeleteIcon;
    return wrapSSR(/*#__PURE__*/ React.createElement("td", {
        ref: ref,
        className: classNames(baseClassName, hashId, className, 'config-td'),
        contentEditable: false,
        style: _object_spread({
            cursor: columnIndex !== undefined ? 'pointer' : 'default',
            padding: 0,
            position: 'relative',
            backgroundColor: shouldShowDeleteIcon ? 'var(--color-primary-control-fill-primary-active)' : undefined
        }, style),
        onClick: handleClick,
        title: columnIndex !== undefined ? columnIndex === -1 ? '点击选中整个表格' : '点击选中整列，显示操作按钮' : undefined
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-buttons"), shouldShowDeleteIcon && "".concat(baseClassName, "-action-buttons-visible"), hashId)
    }, shouldShowInsertButtons && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-button"), "".concat(baseClassName, "-insert-column-before"), hashId),
        onClick: handleInsertColumnBefore,
        title: "在前面增加一列"
    }, /*#__PURE__*/ React.createElement(InsertRowLeftOutlined, null)), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-button"), "".concat(baseClassName, "-delete-icon"), hashId),
        onClick: handleDeleteClick,
        title: "删除整列"
    }, /*#__PURE__*/ React.createElement(DeleteOutlined, null)), shouldShowInsertButtons && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-button"), "".concat(baseClassName, "-insert-column-after"), hashId),
        onClick: handleInsertColumnAfter,
        title: "在后面增加一列"
    }, /*#__PURE__*/ React.createElement(InsertRowRightOutlined, null)))));
};
