"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("@testing-library/react");
const user_event_1 = __importDefault(require("@testing-library/user-event"));
require("@testing-library/jest-dom");
const DataTable_1 = require("../DataTable");
const BFUIProvider_1 = require("../../../core/BFUIProvider");
// Mock IntersectionObserver for virtualization
global.IntersectionObserver = jest.fn().mockImplementation(() => ({
    observe: jest.fn(),
    unobserve: jest.fn(),
    disconnect: jest.fn(),
}));
// Mock ResizeObserver for responsive features
global.ResizeObserver = jest.fn().mockImplementation(() => ({
    observe: jest.fn(),
    unobserve: jest.fn(),
    disconnect: jest.fn(),
}));
const TestWrapper = ({ children }) => ((0, jsx_runtime_1.jsx)(BFUIProvider_1.BFUIProvider, { children: children }));
describe('DataTable Component - Advanced Features', () => {
    const mockData = [
        {
            id: '1',
            name: 'Agent Alpha',
            status: 'active',
            health: 95,
            conversations: 1250,
            success_rate: 94.2,
            cost: 124.50,
            created_at: '2024-01-15T10:30:00Z',
            tags: ['production', 'coding'],
            nested: {
                metrics: {
                    uptime: 99.5,
                    errors: 5
                }
            }
        },
        {
            id: '2',
            name: 'Agent Beta',
            status: 'paused',
            health: 87,
            conversations: 890,
            success_rate: 91.8,
            cost: 89.30,
            created_at: '2024-01-12T14:20:00Z',
            tags: ['staging', 'support'],
            nested: {
                metrics: {
                    uptime: 98.2,
                    errors: 12
                }
            }
        },
        {
            id: '3',
            name: 'Agent Gamma',
            status: 'failed',
            health: 23,
            conversations: 45,
            success_rate: 67.3,
            cost: 15.75,
            created_at: '2024-01-10T08:15:00Z',
            tags: ['development', 'research'],
            nested: {
                metrics: {
                    uptime: 45.8,
                    errors: 89
                }
            }
        }
    ];
    const defaultColumns = [
        {
            key: 'name',
            title: 'Name',
            sortable: true,
            filterable: true,
            width: 200,
            render: (value) => (0, jsx_runtime_1.jsx)("strong", { children: value })
        },
        {
            key: 'status',
            title: 'Status',
            sortable: true,
            filterable: true,
            width: 120,
            render: (value) => ((0, jsx_runtime_1.jsx)("span", { className: `status-badge ${value}`, children: value }))
        },
        {
            key: 'health',
            title: 'Health',
            sortable: true,
            filterable: true,
            width: 100,
            type: 'number',
            render: (value) => `${value}%`
        },
        {
            key: 'conversations',
            title: 'Conversations',
            sortable: true,
            filterable: true,
            width: 150,
            type: 'number',
            format: 'number'
        },
        {
            key: 'success_rate',
            title: 'Success Rate',
            sortable: true,
            width: 120,
            type: 'number',
            render: (value) => `${value.toFixed(1)}%`
        },
        {
            key: 'cost',
            title: 'Cost',
            sortable: true,
            width: 100,
            type: 'number',
            format: 'currency'
        },
        {
            key: 'created_at',
            title: 'Created',
            sortable: true,
            width: 150,
            type: 'date',
            format: 'date'
        }
    ];
    beforeEach(() => {
        jest.clearAllMocks();
    });
    /**
     * Test Suite 1: Advanced Rendering and Virtualization
     */
    describe('Advanced Rendering & Virtualization', () => {
        it('should render with virtual scrolling for large datasets', async () => {
            const largeDataset = Array.from({ length: 10000 }, (_, i) => ({
                ...mockData[0],
                id: `item-${i}`,
                name: `Agent ${i}`,
                conversations: Math.floor(Math.random() * 2000)
            }));
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: largeDataset, columns: defaultColumns, virtualized: true, itemHeight: 50, containerHeight: 400, "data-testid": "virtualized-table" }), { wrapper: TestWrapper });
            // Should render only visible items
            expect(react_1.screen.getByTestId('virtualized-table')).toBeInTheDocument();
            expect(react_1.screen.getByTestId('table-virtual-container')).toBeInTheDocument();
            // Should not render all 10000 items in DOM
            const renderedRows = react_1.screen.getAllByTestId(/table-row-/);
            expect(renderedRows.length).toBeLessThan(20); // Only visible items
        });
        it('should support dynamic row heights with auto-sizing', async () => {
            const dataWithVariableContent = mockData.map((item, i) => ({
                ...item,
                description: i === 0 ? 'Short' : 'This is a much longer description that should cause the row to be taller than others and test the dynamic height calculation'
            }));
            const columnsWithDynamic = [
                ...defaultColumns,
                {
                    key: 'description',
                    title: 'Description',
                    width: 300,
                    render: (value) => (0, jsx_runtime_1.jsx)("div", { style: { wordWrap: 'break-word' }, children: value })
                }
            ];
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: dataWithVariableContent, columns: columnsWithDynamic, virtualized: true, dynamicRowHeight: true, "data-testid": "dynamic-height-table" }), { wrapper: TestWrapper });
            expect(react_1.screen.getByTestId('dynamic-height-table')).toBeInTheDocument();
            // Check that rows have different heights
            const rows = react_1.screen.getAllByTestId(/table-row-/);
            expect(rows.length).toBeGreaterThan(0);
        });
        it('should render with sticky headers and columns', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, stickyHeader: true, stickyColumns: ['name'], "data-testid": "sticky-table" }), { wrapper: TestWrapper });
            const headerRow = react_1.screen.getByTestId('table-header');
            expect(headerRow).toHaveClass('sticky');
            const nameColumn = react_1.screen.getByTestId('column-name');
            expect(nameColumn).toHaveClass('sticky-column');
        });
    });
    /**
     * Test Suite 2: Advanced Sorting and Filtering
     */
    describe('Advanced Sorting & Filtering', () => {
        it('should support multi-column sorting with priority indicators', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, multiSort: true, "data-testid": "multi-sort-table" }), { wrapper: TestWrapper });
            // Click first sort column
            react_1.fireEvent.click(react_1.screen.getByTestId('sort-header-name'));
            // Hold Ctrl and click second sort column
            react_1.fireEvent.click(react_1.screen.getByTestId('sort-header-health'), {
                ctrlKey: true
            });
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('sort-indicator-name')).toHaveTextContent('1');
                expect(react_1.screen.getByTestId('sort-indicator-health')).toHaveTextContent('2');
            });
        });
        it('should provide advanced filtering with multiple filter types', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableFiltering: true, enableAdvancedFiltering: true, "data-testid": "advanced-filter-table" }), { wrapper: TestWrapper });
            // Open filter panel
            react_1.fireEvent.click(react_1.screen.getByTestId('filter-toggle'));
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('advanced-filters-panel')).toBeInTheDocument();
            });
            // Test text filter
            const nameFilter = react_1.screen.getByTestId('filter-name');
            await user_event_1.default.type(nameFilter, 'Alpha');
            // Test range filter for health
            const healthMinFilter = react_1.screen.getByTestId('filter-health-min');
            await user_event_1.default.type(healthMinFilter, '90');
            // Test select filter for status
            const statusFilter = react_1.screen.getByTestId('filter-status');
            react_1.fireEvent.change(statusFilter, { target: { value: 'active' } });
            await (0, react_1.waitFor)(() => {
                const filteredRows = react_1.screen.getAllByTestId(/table-row-/);
                expect(filteredRows).toHaveLength(1); // Only Agent Alpha should match
            });
        });
        it('should support global search across all columns', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableGlobalSearch: true, searchHighlight: true, "data-testid": "searchable-table" }), { wrapper: TestWrapper });
            const globalSearch = react_1.screen.getByTestId('global-search-input');
            await user_event_1.default.type(globalSearch, 'production');
            await (0, react_1.waitFor)(() => {
                // Should find the agent with 'production' tag
                const visibleRows = react_1.screen.getAllByTestId(/table-row-/);
                expect(visibleRows).toHaveLength(1);
                // Should highlight the search term
                expect(react_1.screen.getByTestId('search-highlight')).toBeInTheDocument();
            });
        });
        it('should support saved filter presets', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableFiltering: true, enableFilterPresets: true, "data-testid": "filter-presets-table" }), { wrapper: TestWrapper });
            // Apply filters
            react_1.fireEvent.click(react_1.screen.getByTestId('filter-toggle'));
            const statusFilter = react_1.screen.getByTestId('filter-status');
            react_1.fireEvent.change(statusFilter, { target: { value: 'active' } });
            // Save filter preset
            react_1.fireEvent.click(react_1.screen.getByTestId('save-filter-preset'));
            const presetNameInput = react_1.screen.getByTestId('preset-name-input');
            await user_event_1.default.type(presetNameInput, 'Active Agents');
            react_1.fireEvent.click(react_1.screen.getByTestId('save-preset-confirm'));
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('filter-preset-Active Agents')).toBeInTheDocument();
            });
        });
    });
    /**
     * Test Suite 3: Selection and Bulk Operations
     */
    describe('Selection & Bulk Operations', () => {
        it('should support row selection with shift-click range selection', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableSelection: true, enableRangeSelection: true, "data-testid": "selectable-table" }), { wrapper: TestWrapper });
            // Select first row
            react_1.fireEvent.click(react_1.screen.getByTestId('row-checkbox-1'));
            // Shift-click third row to select range
            react_1.fireEvent.click(react_1.screen.getByTestId('row-checkbox-3'), {
                shiftKey: true
            });
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('row-checkbox-1')).toBeChecked();
                expect(react_1.screen.getByTestId('row-checkbox-2')).toBeChecked();
                expect(react_1.screen.getByTestId('row-checkbox-3')).toBeChecked();
            });
            // Check bulk operations toolbar
            expect(react_1.screen.getByTestId('bulk-operations-toolbar')).toBeInTheDocument();
            expect(react_1.screen.getByText('3 items selected')).toBeInTheDocument();
        });
        it('should support keyboard navigation for selection', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableSelection: true, enableKeyboardNavigation: true, "data-testid": "keyboard-nav-table" }), { wrapper: TestWrapper });
            const table = react_1.screen.getByTestId('keyboard-nav-table');
            table.focus();
            // Navigate with arrow keys
            react_1.fireEvent.keyDown(table, { key: 'ArrowDown' });
            react_1.fireEvent.keyDown(table, { key: 'ArrowDown' });
            // Select with space
            react_1.fireEvent.keyDown(table, { key: ' ' });
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('row-checkbox-2')).toBeChecked();
            });
        });
        it('should provide smart bulk operation suggestions', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableSelection: true, enableSmartBulkOperations: true, "data-testid": "smart-bulk-table" }), { wrapper: TestWrapper });
            // Select agents with different statuses
            react_1.fireEvent.click(react_1.screen.getByTestId('row-checkbox-1')); // active
            react_1.fireEvent.click(react_1.screen.getByTestId('row-checkbox-2')); // paused
            await (0, react_1.waitFor)(() => {
                const bulkToolbar = react_1.screen.getByTestId('bulk-operations-toolbar');
                // Should suggest relevant operations based on selection
                expect((0, react_1.within)(bulkToolbar).getByText('Resume')).toBeInTheDocument();
                expect((0, react_1.within)(bulkToolbar).getByText('Pause')).toBeInTheDocument();
                expect((0, react_1.within)(bulkToolbar).getByText('Export')).toBeInTheDocument();
            });
        });
    });
    /**
     * Test Suite 4: Column Management and Customization
     */
    describe('Column Management & Customization', () => {
        it('should support column reordering with drag and drop', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableColumnReordering: true, "data-testid": "reorderable-columns-table" }), { wrapper: TestWrapper });
            const nameHeader = react_1.screen.getByTestId('column-header-name');
            const statusHeader = react_1.screen.getByTestId('column-header-status');
            // Simulate drag and drop
            react_1.fireEvent.dragStart(nameHeader);
            react_1.fireEvent.dragOver(statusHeader);
            react_1.fireEvent.drop(statusHeader);
            await (0, react_1.waitFor)(() => {
                // Column order should have changed
                const headers = react_1.screen.getAllByTestId(/column-header-/);
                expect(headers[0]).toHaveAttribute('data-testid', 'column-header-status');
                expect(headers[1]).toHaveAttribute('data-testid', 'column-header-name');
            });
        });
        it('should support column resizing with double-click auto-fit', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableColumnResizing: true, "data-testid": "resizable-columns-table" }), { wrapper: TestWrapper });
            const nameColumnResizer = react_1.screen.getByTestId('column-resizer-name');
            // Test manual resize
            react_1.fireEvent.mouseDown(nameColumnResizer, { clientX: 200 });
            react_1.fireEvent.mouseMove(document, { clientX: 300 });
            react_1.fireEvent.mouseUp(document);
            // Test auto-fit on double-click
            react_1.fireEvent.doubleClick(nameColumnResizer);
            await (0, react_1.waitFor)(() => {
                const nameColumn = react_1.screen.getByTestId('column-name');
                expect(nameColumn).toHaveStyle('width: auto');
            });
        });
        it('should provide column visibility controls', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableColumnVisibility: true, "data-testid": "column-visibility-table" }), { wrapper: TestWrapper });
            // Open column visibility menu
            react_1.fireEvent.click(react_1.screen.getByTestId('column-visibility-toggle'));
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('column-visibility-menu')).toBeInTheDocument();
            });
            // Hide the status column
            react_1.fireEvent.click(react_1.screen.getByTestId('toggle-column-status'));
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.queryByTestId('column-header-status')).not.toBeInTheDocument();
            });
        });
        it('should support column grouping and aggregation', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableColumnGrouping: true, enableAggregation: true, "data-testid": "grouped-table" }), { wrapper: TestWrapper });
            // Group by status
            const statusHeader = react_1.screen.getByTestId('column-header-status');
            react_1.fireEvent.dragStart(statusHeader);
            const groupDropZone = react_1.screen.getByTestId('group-drop-zone');
            react_1.fireEvent.dragOver(groupDropZone);
            react_1.fireEvent.drop(groupDropZone);
            await (0, react_1.waitFor)(() => {
                // Should show grouped rows
                expect(react_1.screen.getByTestId('group-header-active')).toBeInTheDocument();
                expect(react_1.screen.getByTestId('group-header-paused')).toBeInTheDocument();
                expect(react_1.screen.getByTestId('group-header-failed')).toBeInTheDocument();
                // Should show aggregated values
                expect(react_1.screen.getByTestId('group-aggregate-active')).toBeInTheDocument();
            });
        });
    });
    /**
     * Test Suite 5: Export and Data Management
     */
    describe('Export & Data Management', () => {
        it('should support multiple export formats with configuration', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableExport: true, exportFormats: ['csv', 'excel', 'json', 'pdf'], "data-testid": "exportable-table" }), { wrapper: TestWrapper });
            react_1.fireEvent.click(react_1.screen.getByTestId('export-menu-toggle'));
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('export-option-csv')).toBeInTheDocument();
                expect(react_1.screen.getByTestId('export-option-excel')).toBeInTheDocument();
                expect(react_1.screen.getByTestId('export-option-json')).toBeInTheDocument();
                expect(react_1.screen.getByTestId('export-option-pdf')).toBeInTheDocument();
            });
            // Test CSV export with options
            react_1.fireEvent.click(react_1.screen.getByTestId('export-option-csv'));
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('export-options-dialog')).toBeInTheDocument();
            });
            // Configure export options
            react_1.fireEvent.click(react_1.screen.getByTestId('export-include-headers'));
            react_1.fireEvent.click(react_1.screen.getByTestId('export-selected-only'));
            react_1.fireEvent.click(react_1.screen.getByTestId('confirm-export'));
        });
        it('should support data import with validation', async () => {
            const onImport = jest.fn();
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableImport: true, onImport: onImport, "data-testid": "importable-table" }), { wrapper: TestWrapper });
            react_1.fireEvent.click(react_1.screen.getByTestId('import-data-button'));
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('import-dialog')).toBeInTheDocument();
            });
            // Upload file
            const fileInput = react_1.screen.getByTestId('file-input');
            const file = new File(['name,status\nTest Agent,active'], 'test.csv', {
                type: 'text/csv'
            });
            await user_event_1.default.upload(fileInput, file);
            await (0, react_1.waitFor)(() => {
                expect(react_1.screen.getByTestId('import-preview')).toBeInTheDocument();
                expect(react_1.screen.getByText('Test Agent')).toBeInTheDocument();
            });
            react_1.fireEvent.click(react_1.screen.getByTestId('confirm-import'));
            expect(onImport).toHaveBeenCalledWith(expect.arrayContaining([
                expect.objectContaining({
                    name: 'Test Agent',
                    status: 'active'
                })
            ]));
        });
    });
    /**
     * Test Suite 6: Performance and Accessibility
     */
    describe('Performance & Accessibility', () => {
        it('should implement proper ARIA labels and keyboard navigation', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, enableAccessibility: true, "data-testid": "accessible-table" }), { wrapper: TestWrapper });
            const table = react_1.screen.getByRole('table');
            expect(table).toHaveAttribute('aria-label');
            const columnHeaders = react_1.screen.getAllByRole('columnheader');
            columnHeaders.forEach(header => {
                expect(header).toHaveAttribute('aria-sort');
            });
            const firstCell = react_1.screen.getByRole('cell', { name: /Agent Alpha/ });
            expect(firstCell).toHaveAttribute('aria-describedby');
        });
        it('should support high contrast mode and theming', async () => {
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: mockData, columns: defaultColumns, theme: "high-contrast", "data-testid": "themed-table" }), { wrapper: TestWrapper });
            const table = react_1.screen.getByTestId('themed-table');
            expect(table).toHaveClass('theme-high-contrast');
        });
        it('should optimize rendering for large datasets', async () => {
            const startTime = performance.now();
            const largeDataset = Array.from({ length: 1000 }, (_, i) => ({
                ...mockData[0],
                id: `item-${i}`,
                name: `Agent ${i}`
            }));
            (0, react_1.render)((0, jsx_runtime_1.jsx)(DataTable_1.DataTable, { data: largeDataset, columns: defaultColumns, virtualized: true, optimizeForPerformance: true, "data-testid": "performance-table" }), { wrapper: TestWrapper });
            const endTime = performance.now();
            const renderTime = endTime - startTime;
            // Should render quickly even with large dataset
            expect(renderTime).toBeLessThan(1000); // Less than 1 second
            expect(react_1.screen.getByTestId('performance-table')).toBeInTheDocument();
        });
    });
});
//# sourceMappingURL=DataTable.test.js.map