import * as React from 'react';
import { flexRender, useReactTable } from '../../cn-ai-table/react-table';
import { getCoreRowModel } from '../../cn-ai-table/table-core';
/**
 * 列宽同步逻辑 Hook
 * 用于同步表头和内容列的宽度（以基础表格demo的表头列宽为基准）
 */
export function useColumnWidthSync({ data, columns, grouping, }) {
    // 用于测量基础表格demo表头列宽的隐藏表格 ref
    const referenceTableRef = React.useRef(null);
    // 获取列宽信息
    const [columnWidths, setColumnWidths] = React.useState([]);
    // 保存第一列的固定宽度，一旦计算完成就不再改变
    const firstColumnWidthRef = React.useRef(null);
    // 标记列宽是否已初始化
    const columnWidthsInitializedRef = React.useRef(false);
    // 创建用于测量基础表格demo表头列宽的参考表格（不分组）
    const referenceTableInstance = useReactTable({
        data,
        columns,
        getCoreRowModel: getCoreRowModel(),
    });
    // 同步表头和内容列的宽度（以基础表格demo的表头列宽为基准）
    React.useEffect(() => {
        // 如果列宽已初始化，不再重新计算（避免编辑时触发）
        if (columnWidthsInitializedRef.current)
            return;
        const syncColumnWidths = () => {
            // 从隐藏的参考表格（基础表格demo）获取表头列宽
            if (!referenceTableRef.current)
                return;
            const referenceTableElement = referenceTableRef.current;
            const headerCells = referenceTableElement.querySelectorAll('thead th');
            if (headerCells.length === 0)
                return;
            // 获取参考表格表头每列的实际宽度（这些宽度与基础表格demo一致）
            const widths = [];
            headerCells.forEach((th) => {
                const cell = th;
                // 使用 scrollWidth 和 offsetWidth 的较大值，确保获取完整宽度
                const width = Math.max(cell.scrollWidth, cell.offsetWidth);
                widths.push(width);
            });
            // 保存第一列的固定宽度（使用表头宽度）
            const firstHeaderWidth = widths[0] || 200;
            firstColumnWidthRef.current = firstHeaderWidth;
            // 更新列宽数组
            setColumnWidths(widths);
            // 标记列宽已初始化
            columnWidthsInitializedRef.current = true;
        };
        // 延迟执行以确保 DOM 已渲染（包括参考表格）
        const timer = setTimeout(() => {
            requestAnimationFrame(() => {
                syncColumnWidths();
            });
        }, 200);
        // 监听窗口大小变化（只在未初始化时）
        const handleResize = () => {
            if (!columnWidthsInitializedRef.current) {
                syncColumnWidths();
            }
        };
        window.addEventListener('resize', handleResize);
        return () => {
            clearTimeout(timer);
            window.removeEventListener('resize', handleResize);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [grouping]);
    // 渲染隐藏的参考表格，用于测量基础表格demo的表头列宽
    const ReferenceTable = (React.createElement("div", { style: {
            position: 'absolute',
            left: '-9999px',
            top: '-9999px',
            opacity: 0,
            pointerEvents: 'none',
            zIndex: -1,
            visibility: 'hidden',
        } },
        React.createElement("div", { className: "ai-table-container" },
            React.createElement("table", { ref: referenceTableRef, className: "ai-table-table" },
                React.createElement("thead", null, referenceTableInstance.getHeaderGroups().map((headerGroup) => (React.createElement("tr", { key: headerGroup.id }, headerGroup.headers.map((header, index) => {
                    return (React.createElement("th", { key: header.id, className: `ai-table-header-cell ${index === 0 ? 'ai-table-sticky-column' : ''}` }, header.isPlaceholder ? null : (React.createElement("div", { className: "ai-table-header-content" }, flexRender(header.column.columnDef.header, header.getContext())))));
                }))))),
                React.createElement("tbody", null, referenceTableInstance
                    .getRowModel()
                    .rows.slice(0, 1)
                    .map((row) => (React.createElement("tr", { key: row.id, className: "ai-table-row" }, row.getVisibleCells().map((cell, index) => {
                    return (React.createElement("td", { key: cell.id, className: `ai-table-data-cell ${index === 0 ? 'ai-table-sticky-column' : ''}` },
                        React.createElement("div", { className: "ai-table-cell-content" }, flexRender(cell.column.columnDef.cell, cell.getContext()))));
                })))))))));
    return {
        columnWidths,
        firstColumnWidthRef,
        referenceTableRef,
        referenceTableInstance,
        ReferenceTable,
    };
}
