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_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
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 { Node } from "slate";
import stringWidth from "string-width";
import { TABLE_COL_WIDTH_MIN_COLUMNS, TABLE_DEFAULT_COL_WIDTH } from "../../../../../Constants/mobile";
var SMART_SAMPLE_ROWS = 5;
var SMART_CELL_PADDING = 28; // 20 基础内边距 + 8 数字等字符宽度补偿
var SMART_FONT = '14px sans-serif';
var CHAR_WIDTH_PX = 12;
var WORD_SPLIT = /[\s\u4e00-\u9fa5]/;
function getTableRows(element) {
    return element.children.flatMap(function(node) {
        return node.type === 'table-row' ? [
            node
        ] : 'children' in node ? node.children : [];
    });
}
function getSampledCellTexts(element, columnCount, maxRows) {
    return getTableRows(element).slice(0, maxRows).map(function(row) {
        return Array.from({
            length: columnCount
        }, function(_, i) {
            var _row_children;
            var cell = (_row_children = row.children) === null || _row_children === void 0 ? void 0 : _row_children[i];
            return cell && (typeof cell === "undefined" ? "undefined" : _type_of(cell)) === 'object' && 'children' in cell ? Node.string(cell) : '';
        });
    });
}
function createMeasureContext() {
    if (typeof document === 'undefined') return null;
    var ctx = document.createElement('canvas').getContext('2d');
    if (!ctx) return null;
    ctx.font = SMART_FONT;
    return ctx;
}
function measureText(ctx, text, pad) {
    return text === null || text === undefined ? pad : ctx.measureText(String(text)).width + pad;
}
function getColumnMetrics(grid, col, ctx, pad) {
    var maxW = 0;
    var minW = 0;
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = grid[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var row = _step.value;
            var _Math;
            var _row_col;
            var cellText = (_row_col = row[col]) !== null && _row_col !== void 0 ? _row_col : '';
            var full = measureText(ctx, cellText, pad);
            var words = cellText.split(WORD_SPLIT).filter(Boolean);
            var longest = words.length ? (_Math = Math).max.apply(_Math, _to_consumable_array(words.map(function(w) {
                return measureText(ctx, w, pad);
            }))) : measureText(ctx, cellText, pad);
            maxW = Math.max(maxW, full);
            minW = Math.max(minW, longest);
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    return {
        maxW: maxW,
        minW: minW
    };
}
function getSmartColWidthsPx(grid, columnCount, containerWidth) {
    if (columnCount <= TABLE_COL_WIDTH_MIN_COLUMNS || !grid.length || containerWidth <= 0) {
        return null;
    }
    var ctx = createMeasureContext();
    if (!ctx) return null;
    var metrics = Array.from({
        length: columnCount
    }, function(_, i) {
        return getColumnMetrics(grid, i, ctx, SMART_CELL_PADDING);
    });
    var totalMin = metrics.reduce(function(s, c) {
        return s + c.minW;
    }, 0);
    if (totalMin >= containerWidth) return metrics.map(function(c) {
        return c.minW;
    });
    var remaining = containerWidth - totalMin;
    var totalFlex = metrics.reduce(function(s, c) {
        return s + (c.maxW - c.minW);
    }, 0) || 1;
    return metrics.map(function(c) {
        return Math.floor(c.minW + (c.maxW - c.minW) / totalFlex * remaining);
    });
}
function getContentBasedColWidthsPx(element, columnCount) {
    var rows = getTableRows(element);
    return Array.from({
        length: columnCount
    }, function(_, colIndex) {
        var maxPx = TABLE_DEFAULT_COL_WIDTH;
        var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
        try {
            for(var _iterator = rows[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                var row = _step.value;
                var _row_children;
                var cell = (_row_children = row.children) === null || _row_children === void 0 ? void 0 : _row_children[colIndex];
                if (cell && (typeof cell === "undefined" ? "undefined" : _type_of(cell)) === 'object' && 'children' in cell) {
                    var w = stringWidth(Node.string(cell)) * CHAR_WIDTH_PX;
                    if (w > maxPx) maxPx = w;
                }
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally{
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally{
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
        return maxPx;
    });
}
function pxToPercent(px) {
    var total = px.reduce(function(a, b) {
        return a + b;
    }, 0);
    return total <= 0 ? px.map(function() {
        return '0%';
    }) : px.map(function(w) {
        return "".concat((w / total * 100).toFixed(2), "%");
    });
}
/** 只读表格列宽：显式 colWidths > 智能算法(6+列) > 内容比例 > 平分 */ export function getReadonlyTableColWidths(input) {
    var _otherProps_colWidths, _element_children, _element_children1;
    var columnCount = input.columnCount, otherProps = input.otherProps, element = input.element, containerWidth = input.containerWidth;
    if (otherProps === null || otherProps === void 0 ? void 0 : (_otherProps_colWidths = otherProps.colWidths) === null || _otherProps_colWidths === void 0 ? void 0 : _otherProps_colWidths.length) return otherProps.colWidths;
    if (columnCount === 0) return [];
    var useSmart = (element === null || element === void 0 ? void 0 : (_element_children = element.children) === null || _element_children === void 0 ? void 0 : _element_children.length) && typeof containerWidth === 'number' && containerWidth > 0;
    if (useSmart) {
        var grid = getSampledCellTexts(element, columnCount, SMART_SAMPLE_ROWS);
        var smart = getSmartColWidthsPx(grid, columnCount, containerWidth);
        if (smart) return smart;
    }
    if (element === null || element === void 0 ? void 0 : (_element_children1 = element.children) === null || _element_children1 === void 0 ? void 0 : _element_children1.length) return pxToPercent(getContentBasedColWidthsPx(element, columnCount));
    var pct = (100 / columnCount).toFixed(2);
    return Array(columnCount).fill("".concat(pct, "%"));
}
