/**
 * 将 TanStack 分组行树拍平为虚拟列表项。
 * 展开态由 row.getIsExpanded() + subRows 驱动，不依赖 getExpandedRowModel 的扁平行顺序。
 * （调用方 useMemo 请把 `table.getState().expanded` 列入依赖，以便折叠/展开时重算。）
 */
export function buildGroupedVirtualRows(table) {
    const rows = [];
    const groupedRows = table.getRowModel().rows.filter((row) => row.getIsGrouped());
    rows.push({ type: 'custom', data: { type: 'spacer' } });
    const flattenNestedGroupRows = (rowsToFlatten, groupIndexCounter, isFirstGroup) => {
        rowsToFlatten.forEach((row, index) => {
            var _a;
            const isLastInSubGroup = index === rowsToFlatten.length - 1;
            if (row.getIsGrouped()) {
                rows.push({
                    type: 'custom',
                    data: { type: 'group', row, depth: row.depth || 0, isFirstGroup },
                });
                if (((_a = row.subRows) === null || _a === void 0 ? void 0 : _a.length) > 0 && row.getIsExpanded()) {
                    // 嵌套分组子树使用独立序号，与历史实现一致
                    const subGroupCounter = { value: 0 };
                    flattenNestedGroupRows(row.subRows, subGroupCounter, false);
                }
            }
            else {
                // eslint-disable-next-line no-param-reassign -- 递归拍平需在闭包内递增共享计数器
                groupIndexCounter.value += 1;
                rows.push({
                    type: 'data',
                    row,
                    groupRowIndex: groupIndexCounter.value,
                    isLastInGroup: isLastInSubGroup,
                });
            }
        });
    };
    groupedRows.forEach((groupRow, groupIndex) => {
        var _a;
        const isFirstGroup = groupIndex === 0;
        if (groupRow.getIsGrouped()) {
            rows.push({
                type: 'custom',
                data: { type: 'group', row: groupRow, depth: 0, isFirstGroup },
            });
            if (((_a = groupRow.subRows) === null || _a === void 0 ? void 0 : _a.length) > 0 && groupRow.getIsExpanded()) {
                const groupIndexCounter = { value: 0 };
                flattenNestedGroupRows(groupRow.subRows, groupIndexCounter, isFirstGroup);
                const last = rows[rows.length - 1];
                if ((last === null || last === void 0 ? void 0 : last.type) === 'data') {
                    last.isLastInGroup = true;
                }
            }
        }
        else {
            rows.push({ type: 'data', row: groupRow, groupRowIndex: groupIndex + 1 });
        }
        if (groupIndex < groupedRows.length - 1) {
            rows.push({ type: 'custom', data: { type: 'spacer' } });
        }
    });
    return rows;
}
