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, InsertRowAboveOutlined, InsertRowBelowOutlined } 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";
/**
 * TableCellIndex 组件 - 表格行索引单元格组件
 *
 * 该组件用于渲染表格行的索引单元格，显示行号或索引信息。
 * 使用 context 来生成 className，支持样式自定义。
 *
 * @component
 * @description 表格行索引单元格组件，用于显示行索引
 * @param {TableCellIndexProps} props - 组件属性
 * @param {React.CSSProperties} [props.style] - 自定义样式
 * @param {string} [props.className] - 自定义类名
 * @param {any} props.targetRow - 目标行元素
 * @param {number} [props.rowIndex] - 行索引，用于选中整行
 * @param {number[]} [props.tablePath] - 表格路径，用于定位表格元素
 *
 * @example
 * ```tsx
 * <TableCellIndex
 *   style={{ backgroundColor: '#f5f5f5' }}
 *   className="custom-index-cell"
 *   targetRow={rowElement}
 *   rowIndex={0}
 *   tablePath={[0]}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的表格索引单元格组件
 *
 * @remarks
 * - 使用 ConfigProvider context 生成 className
 * - 支持自定义样式覆盖
 * - 不可编辑状态
 * - 固定宽度和垂直对齐
 * - 支持点击选中整行功能
 */ export var TableCellIndex = function(param) {
    var style = param.style, className = param.className, rowIndex = param.rowIndex, 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');
    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;
        if (clearIcon) {
            setDeleteIconPosition === null || setDeleteIconPosition === void 0 ? void 0 : setDeleteIconPosition(null);
        }
        if (!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;
            }
            // 清除所有行的选中状态 - 通过 DOM 操作移除 data-select 属性
            for(var rowIdx = 0; rowIdx < rowCount; rowIdx++){
                var rowElement = tableElement.children[rowIdx];
                if (rowElement && rowElement.children) {
                    for(var colIdx = 0; colIdx < rowElement.children.length; colIdx++){
                        var cellPath = _to_consumable_array(tablePath).concat([
                            rowIdx,
                            colIdx
                        ]);
                        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.removeAttribute('data-select');
                                }
                            }
                        }
                    }
                }
            }
        } catch (error) {
            console.warn('Failed to clear table selection:', error);
        }
    });
    /**
   * 处理点击事件，选中整行或显示删除图标
   */ var handleClick = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        // 如果提供了行索引，显示删除图标
        if (rowIndex !== undefined) {
            setDeleteIconPosition === null || setDeleteIconPosition === void 0 ? void 0 : setDeleteIconPosition({
                rowIndex: rowIndex,
                columnIndex: undefined
            });
        }
        if (rowIndex === 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;
            }
            clearSelect(false);
            // 选中指定行的所有单元格 - 通过 DOM 操作设置 data-select 属性
            var rowElement = tableElement.children[rowIndex];
            if (rowElement && rowElement.children) {
                for(var colIdx = 0; colIdx < rowElement.children.length; colIdx++){
                    var cellPath = _to_consumable_array(tablePath).concat([
                        rowIndex,
                        colIdx
                    ]);
                    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');
                            }
                        }
                    }
                }
            }
        } catch (error) {
            console.warn('Failed to select table row:', error);
        }
    });
    /**
   * 处理删除图标点击事件
   */ var handleDeleteClick = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        try {
            if (!tablePath || rowIndex === 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 (rowCount <= 1 && colCount <= 1) {
                // 如果只有一行一列，删除整个表格
                NativeTableEditor.removeTable(editor, tablePath);
                return;
            }
            // 检查是否只有一行
            if (rowCount <= 1) {
                // 如果只有一行，删除整个表格
                NativeTableEditor.removeTable(editor, tablePath);
                return;
            }
            // 删除指定行
            var rowPath = _to_consumable_array(tablePath).concat([
                rowIndex
            ]);
            if (Editor.hasPath(editor, rowPath)) {
                Transforms.removeNodes(editor, {
                    at: rowPath
                });
            }
            clearSelect();
        } catch (error) {
            console.warn('Failed to delete table row:', error);
        }
    });
    /**
   * 处理在前面增加一行点击事件
   */ var handleInsertRowBefore = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        try {
            if (!tablePath || rowIndex === undefined) {
                return;
            }
            // 获取表格元素
            var tableElement = Editor.node(editor, tablePath)[0];
            if (!tableElement || tableElement.type !== 'table') {
                return;
            }
            var firstRow = tableElement.children[0];
            var colCount = firstRow.children.length;
            // 创建新行
            var newRow = {
                type: 'table-row',
                children: Array.from({
                    length: colCount
                }).map(function() {
                    return {
                        type: 'table-cell',
                        children: [
                            {
                                type: 'paragraph',
                                children: [
                                    {
                                        text: ''
                                    }
                                ]
                            }
                        ]
                    };
                })
            };
            // 在当前行之前插入新行
            var rowPath = _to_consumable_array(tablePath).concat([
                rowIndex
            ]);
            Transforms.insertNodes(editor, newRow, {
                at: rowPath
            });
            clearSelect();
        } catch (error) {
            console.warn('Failed to insert row before:', error);
        }
    });
    /**
   * 处理在后面增加一行点击事件
   */ var handleInsertRowAfter = useRefFunction(function(e) {
        e.preventDefault();
        e.stopPropagation();
        try {
            if (!tablePath || rowIndex === undefined) {
                return;
            }
            // 获取表格元素
            var tableElement = Editor.node(editor, tablePath)[0];
            if (!tableElement || tableElement.type !== 'table') {
                return;
            }
            var firstRow = tableElement.children[0];
            var colCount = firstRow.children.length;
            // 创建新行
            var newRow = {
                type: 'table-row',
                children: Array.from({
                    length: colCount
                }).map(function() {
                    return {
                        type: 'table-cell',
                        children: [
                            {
                                type: 'paragraph',
                                children: [
                                    {
                                        text: ''
                                    }
                                ]
                            }
                        ]
                    };
                })
            };
            // 在当前行之后插入新行
            // 获取表格的行数来检查边界
            var rowCount = tableElement.children.length;
            var insertRowIndex = Math.min(rowIndex + 1, rowCount);
            var rowPath = _to_consumable_array(tablePath).concat([
                insertRowIndex
            ]);
            Transforms.insertNodes(editor, newRow, {
                at: rowPath
            });
            clearSelect();
        } catch (error) {
            console.warn('Failed to insert row after:', error);
        }
    });
    var ref = useRef(null);
    // 检查是否应该显示删除图标
    var shouldShowDeleteIcon = deleteIconPosition && deleteIconPosition.rowIndex === rowIndex && deleteIconPosition.columnIndex === undefined;
    useClickAway(function() {
        if (shouldShowDeleteIcon && deleteIconPosition && deleteIconPosition.rowIndex === rowIndex) {
            clearSelect();
        }
    }, ref);
    return wrapSSR(/*#__PURE__*/ React.createElement("td", {
        ref: ref,
        className: classNames(baseClassName, hashId, className, 'config-td'),
        contentEditable: false,
        style: _object_spread({
            padding: 0,
            cursor: rowIndex !== undefined ? 'pointer' : 'default',
            position: 'relative',
            backgroundColor: shouldShowDeleteIcon ? 'var(--color-primary-control-fill-primary-active)' : undefined
        }, style),
        onClick: handleClick,
        title: rowIndex !== undefined ? '点击显示操作按钮' : undefined
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-buttons"), shouldShowDeleteIcon && "".concat(baseClassName, "-action-buttons-visible"), hashId)
    }, shouldShowDeleteIcon && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-button"), "".concat(baseClassName, "-insert-row-before"), hashId),
        onClick: handleInsertRowBefore,
        title: "在上面增加一行"
    }, /*#__PURE__*/ React.createElement(InsertRowAboveOutlined, null)), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-button"), "".concat(baseClassName, "-delete-icon"), hashId),
        onClick: handleDeleteClick,
        title: "删除整行"
    }, /*#__PURE__*/ React.createElement(DeleteOutlined, null)), shouldShowDeleteIcon && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-action-button"), "".concat(baseClassName, "-insert-row-after"), hashId),
        onClick: handleInsertRowAfter,
        title: "在下面增加一行"
    }, /*#__PURE__*/ React.createElement(InsertRowBelowOutlined, null)))));
};
