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 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 _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        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 { ConfigProvider } from "antd";
import classNames from "classnames";
import React, { useContext, useEffect, useMemo, useRef } from "react";
import { Node } from "slate";
import stringWidth from "string-width";
import { MOBILE_BREAKPOINT, MOBILE_TABLE_MIN_COLUMN_WIDTH } from "../../../../Constants/mobile";
import { useEditorStore } from "../../store";
import { ReadonlyTableComponent } from "./ReadonlyTableComponent";
import { TablePropsContext } from "./TableContext";
import { TableRowIndex } from "./TableRowIndex";
import useScrollShadow from "./useScrollShadow";
/**
 * 表格组
 *
 * @param {RenderElementProps} props - 渲染元素的属性。
 *
 * @returns {JSX.Element} 表格组件的 JSX 元素。
 *
 * @component
 *
 * @example
 * ```tsx
 * <Table {...props} />
 * ```
 *
 * @remarks
 * 该组件使用了多个 React 钩子函数，包括 `useState`、`useEffect`、`useCallback` 和 `useRef`。
 *
 * - `useState` 用于管理组件的状态。
 * - `useEffect` 用于处理组件挂载和卸载时的副作用。
 * - `useCallback` 用于优化回调函数的性能。
 * - `useRef` 用于获取 DOM 元素的引用。
 *
 * 组件还使用了 `IntersectionObserver` 来检测表格是否溢出，并相应地添加或移除 CSS 类。
 *
 * @see https://reactjs.org/docs/hooks-intro.html React Hooks
 */ export var SlateTable = function(_0) {
    var hashId = _0.hashId, children = _0.children, props = _object_without_properties(_0, [
        "hashId",
        "children"
    ]);
    var _props_element_children__children, _props_element_children_, _props_element_children, _props_element, _props_element_otherProps, _props_element1, _props_element_children1, _props_element2;
    var _useEditorStore = useEditorStore(), readonly = _useEditorStore.readonly, markdownContainerRef = _useEditorStore.markdownContainerRef;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var tablePath = useContext(TablePropsContext).tablePath;
    var baseCls = getPrefixCls('agentic-md-editor-content-table');
    var tableTargetRef = useRef(null);
    var columnCount = ((_props_element = props.element) === null || _props_element === void 0 ? void 0 : (_props_element_children = _props_element.children) === null || _props_element_children === void 0 ? void 0 : (_props_element_children_ = _props_element_children[0]) === null || _props_element_children_ === void 0 ? void 0 : (_props_element_children__children = _props_element_children_.children) === null || _props_element_children__children === void 0 ? void 0 : _props_element_children__children.length) || 0;
    var mobileBreakpointValue = parseInt(MOBILE_BREAKPOINT, 10) || 768;
    // 总是调用 hooks，避免条件调用
    var _useScrollShadow = _sliced_to_array(useScrollShadow(), 2), tableRef = _useScrollShadow[0], scrollState = _useScrollShadow[1];
    // 只在编辑模式下进行复杂的列宽计算
    var colWidths = useMemo(function() {
        var _props_element_otherProps, _props_element, _props_element_children, _props_element1, _tableRows__children, _tableRows_, _markdownContainerRef_current_querySelector, _markdownContainerRef_current;
        // readonly 模式下使用简化计算
        if (readonly) {
            var _props_element2, _props_element_children__children, _props_element_children_, _props_element_children1, _props_element3;
            var otherProps = (_props_element2 = props.element) === null || _props_element2 === void 0 ? void 0 : _props_element2.otherProps;
            if (otherProps === null || otherProps === void 0 ? void 0 : otherProps.colWidths) {
                return otherProps.colWidths;
            }
            var columnCount1 = ((_props_element3 = props.element) === null || _props_element3 === void 0 ? void 0 : (_props_element_children1 = _props_element3.children) === null || _props_element_children1 === void 0 ? void 0 : (_props_element_children_ = _props_element_children1[0]) === null || _props_element_children_ === void 0 ? void 0 : (_props_element_children__children = _props_element_children_.children) === null || _props_element_children__children === void 0 ? void 0 : _props_element_children__children.length) || 0;
            if (columnCount1 === 0) return [];
            return Array(columnCount1).fill(80); // 固定宽度
        }
        // 如果在props中存在，直接使用以避免计算
        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.colWidths) {
            var _props_element_otherProps1, _props_element4;
            return (_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.colWidths;
        }
        if (typeof window === 'undefined' || !((_props_element1 = props.element) === null || _props_element1 === void 0 ? void 0 : (_props_element_children = _props_element1.children) === null || _props_element_children === void 0 ? void 0 : _props_element_children.length)) return [];
        var tableRows = props.element.children;
        if (!(tableRows === null || tableRows === void 0 ? void 0 : (_tableRows_ = tableRows[0]) === null || _tableRows_ === void 0 ? void 0 : (_tableRows__children = _tableRows_.children) === null || _tableRows__children === void 0 ? void 0 : _tableRows__children.length)) return [];
        // 只获取一次容器宽度
        var containerWidth = ((markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : (_markdownContainerRef_current_querySelector = _markdownContainerRef_current.querySelector('.ant-agentic-md-editor-content')) === null || _markdownContainerRef_current_querySelector === void 0 ? void 0 : _markdownContainerRef_current_querySelector.clientWidth) || 400) - 32 - 12;
        var isMobileLayout = containerWidth <= mobileBreakpointValue;
        var minColumnWidth = isMobileLayout ? MOBILE_TABLE_MIN_COLUMN_WIDTH : 60;
        var maxColumnWidth = isMobileLayout ? containerWidth : containerWidth / 4;
        var rowsToSample = Math.min(5, tableRows.length);
        // 一次性计算宽度
        var calculatedWidths = Array.from({
            length: columnCount
        }, function(_, colIndex) {
            var _Math;
            var cellWidths = [];
            for(var rowIndex = 0; rowIndex < rowsToSample; rowIndex++){
                var _tableRows_rowIndex_children, _tableRows_rowIndex;
                var cell = (_tableRows_rowIndex = tableRows[rowIndex]) === null || _tableRows_rowIndex === void 0 ? void 0 : (_tableRows_rowIndex_children = _tableRows_rowIndex.children) === null || _tableRows_rowIndex_children === void 0 ? void 0 : _tableRows_rowIndex_children[colIndex];
                if (cell) {
                    var textWidth = stringWidth(Node.string(cell)) * 12;
                    cellWidths.push(textWidth);
                }
            }
            return Math.min((_Math = Math).max.apply(_Math, [
                minColumnWidth
            ].concat(_to_consumable_array(cellWidths))), maxColumnWidth);
        });
        // 如果表格少于5行且总宽度超过容器宽度，则均匀分配宽度
        if (tableRows.length < 5 && columnCount > 0) {
            var totalWidth = calculatedWidths.reduce(function(sum, width) {
                return sum + width;
            }, 0);
            if (totalWidth > containerWidth) {
                var evenWidth = Math.max(minColumnWidth, Math.floor(containerWidth / columnCount));
                return Array(columnCount).fill(evenWidth);
            }
        }
        return calculatedWidths;
    }, [
        readonly,
        (_props_element1 = props.element) === null || _props_element1 === void 0 ? void 0 : (_props_element_otherProps = _props_element1.otherProps) === null || _props_element_otherProps === void 0 ? void 0 : _props_element_otherProps.colWidths,
        (_props_element2 = props.element) === null || _props_element2 === void 0 ? void 0 : (_props_element_children1 = _props_element2.children) === null || _props_element_children1 === void 0 ? void 0 : _props_element_children1.length,
        columnCount,
        markdownContainerRef
    ]);
    // 只在编辑模式下添加resize事件监听
    useEffect(function() {
        if (readonly || typeof window === 'undefined') return;
        var resize = function() {
            var _markdownContainerRef_current_querySelector, _markdownContainerRef_current;
            if (process.env.NODE_ENV === 'test') return;
            var maxWidth = colWidths ? (colWidths === null || colWidths === void 0 ? void 0 : colWidths.reduce(function(a, b) {
                return a + b;
            }, 0)) + 8 : 0;
            var minWidth = markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : (_markdownContainerRef_current_querySelector = _markdownContainerRef_current.querySelector('.ant-agentic-md-editor-content')) === null || _markdownContainerRef_current_querySelector === void 0 ? void 0 : _markdownContainerRef_current_querySelector.clientWidth;
            var dom = tableRef.current;
            if (dom) {
                setTimeout(function() {
                    var _markdownContainerRef_current_querySelector, _markdownContainerRef_current;
                    var containerWidthForBreakpoint = ((markdownContainerRef === null || markdownContainerRef === void 0 ? void 0 : (_markdownContainerRef_current = markdownContainerRef.current) === null || _markdownContainerRef_current === void 0 ? void 0 : (_markdownContainerRef_current_querySelector = _markdownContainerRef_current.querySelector('.ant-agentic-md-editor-content')) === null || _markdownContainerRef_current_querySelector === void 0 ? void 0 : _markdownContainerRef_current_querySelector.clientWidth) || 400) - 32 - 12;
                    var isMobileLayout = containerWidthForBreakpoint <= mobileBreakpointValue;
                    var computedMinColumnWidth = isMobileLayout ? MOBILE_TABLE_MIN_COLUMN_WIDTH : 60;
                    var fallbackMinWidth = Number(((minWidth || 200) * 0.95).toFixed(0));
                    var requiredMinWidth = Math.max(columnCount * computedMinColumnWidth, maxWidth, fallbackMinWidth, 200);
                    dom.style.minWidth = "".concat(requiredMinWidth, "px");
                }, 200);
            }
        };
        document.addEventListener('md-resize', resize);
        window.addEventListener('resize', resize);
        resize();
        return function() {
            document.removeEventListener('md-resize', resize);
            window.removeEventListener('resize', resize);
        };
    }, [
        colWidths,
        readonly,
        markdownContainerRef,
        tableRef
    ]);
    useEffect(function() {
        if (readonly) return;
        document.dispatchEvent(new CustomEvent('md-resize', {
            detail: {}
        }));
    }, [
        readonly
    ]);
    // 缓存表格DOM，减少重复渲染
    var tableDom = useMemo(function() {
        return /*#__PURE__*/ React.createElement("table", {
            ref: tableTargetRef,
            className: classNames("".concat(baseCls, "-editor-table"), hashId),
            onDragStart: function(e) {
                // 阻止拖拽开始事件
                e.preventDefault();
                return false;
            }
        }, /*#__PURE__*/ React.createElement("colgroup", null, /*#__PURE__*/ React.createElement("col", {
            style: {
                width: 12,
                minWidth: 12,
                maxWidth: 12
            }
        }), (colWidths || []).map(function(colWidth, index) {
            return /*#__PURE__*/ React.createElement("col", {
                key: index,
                style: {
                    width: colWidth,
                    minWidth: colWidth,
                    maxWidth: colWidth
                }
            });
        }) || null), /*#__PURE__*/ React.createElement("tbody", null, readonly ? null : /*#__PURE__*/ React.createElement(TableRowIndex, {
            colWidths: colWidths,
            tablePath: tablePath
        }), children));
    }, [
        colWidths,
        children,
        hashId,
        baseCls
    ]);
    // 缓存boxShadow样式，只在scrollState变化时重新计算
    var boxShadowStyle = useMemo(function() {
        return {
            flex: 1,
            minWidth: 0,
            boxShadow: readonly ? undefined : "\n      ".concat(scrollState.vertical.hasScroll && !scrollState.vertical.isAtStart ? 'inset 0 8px 8px -8px rgba(0,0,0,0.1)' : '', "\n      ").concat(scrollState.vertical.hasScroll && !scrollState.vertical.isAtEnd ? 'inset 0 -8px 8px -8px rgba(0,0,0,0.1)' : '', "\n      ").concat(scrollState.horizontal.hasScroll && !scrollState.horizontal.isAtStart ? 'inset 8px 0 8px -8px rgba(0,0,0,0.1)' : '', "\n      ").concat(scrollState.horizontal.hasScroll && !scrollState.horizontal.isAtEnd ? 'inset -8px 0 8px -8px rgba(0,0,0,0.1)' : '', "\n    ")
        };
    }, [
        scrollState,
        readonly
    ]);
    // readonly 模式渲染 - 使用优化的组件（早期返回）
    if (readonly) {
        return /*#__PURE__*/ React.createElement(ReadonlyTableComponent, {
            hashId: hashId,
            element: props.element,
            baseCls: baseCls
        }, children);
    }
    // 编辑模式渲染
    return /*#__PURE__*/ React.createElement("div", {
        className: classNames(baseCls, hashId),
        ref: tableRef,
        style: _object_spread_props(_object_spread({}, boxShadowStyle), {
            position: 'relative'
        }),
        onDragStart: function(e) {
            // 阻止拖拽开始时的文字选择
            e.preventDefault();
        },
        onDoubleClick: function(e) {
            // 阻止双击选择文字
            e.preventDefault();
        }
    }, tableDom);
};
