/* ============================================
   RSL Smart Table Component
   Version: 2.0.0
   Description: Premium data table with sorting, filtering,
   pagination, export, row selection, and full accessibility

   FilterBus Date Range Support (v2.0.0):
   - Subscribes to date range filters from Date Picker
   - Use data-filterbus-date-field="columnKey" to specify date column
   - Filters rows where date falls within published range
   ============================================ */

(function() {
    'use strict';

    // Initialize RSL namespace
    window.RSL = window.RSL || {};

    /**
     * Default configuration
     * @const
     */
    const DEFAULT_CONFIG = {
        pageSize: 10,
        pageSizes: [10, 25, 50, 100],
        searchDebounce: 300,
        serverMode: false,
        stickyHeader: false,
        striped: true,
        responsive: 'card', // 'card', 'scroll', 'stack'
        selectable: false,
        exportable: true,
        exportFormats: ['csv', 'json'],
        showInfo: true,
        showPagination: true,
        showPageSize: true,
        emptyMessage: 'No data available',
        noResultsMessage: 'No matching records found',
        loadingMessage: 'Loading...',
        // New features
        rowActions: false,          // Enable row action menu
        rowActionItems: ['view', 'edit', 'delete'], // Default actions
        quickFilters: [],           // Array of {label, column, value} or {label, filter: fn}
        copyable: false,            // Enable copy to clipboard
        conditionalFormatting: [],  // Array of {column, rules: [{condition, value, class/style}]}
        // Advanced features
        inlineEditing: false,       // Enable click-to-edit cells
        editableColumns: [],        // Which columns can be edited (empty = all)
        summaryRow: false,          // Enable summary/totals row
        summaryColumns: [],         // Array of {column, type: 'sum'|'avg'|'count'|'min'|'max', label}
        expandableRows: false,      // Enable row expansion
        expandTemplate: null,       // Function(rowData) => HTML string for expanded content
        expandableColumns: [],      // Which columns to show in expanded view (empty = all)
        // Column manipulation features
        columnResizing: false,      // Enable column resize by dragging borders
        minColumnWidth: 100,        // Minimum column width in pixels
        columnReordering: false,    // Enable drag-and-drop column reordering
        // Frozen/Pinned columns
        frozenColumns: {            // Columns to freeze
            left: [],               // Array of column keys to pin left
            right: []               // Array of column keys to pin right
        },
        // Bulk actions
        bulkActions: false,         // Enable bulk actions bar
        bulkActionItems: ['delete', 'export'], // Default bulk actions
        bulkStatusOptions: [],      // Status options for bulk status change
        // Saved views
        savedViews: false,          // Enable saved views feature
        viewStorageKey: null,       // localStorage key for views (auto-generated if null)
        // Full page mode
        fullPageMode: false,        // Enable full page toggle
        fullPagePadding: 20         // Padding when in full page mode
    };

    /**
     * Track initialized instances
     * @type {Map<HTMLElement, SmartTable>}
     */
    const instances = new Map();

    /**
     * SmartTable Class
     * Main class for handling all table functionality
     */
    class SmartTable {
        constructor(element, options = {}) {
            this.table = element;
            this.config = { ...DEFAULT_CONFIG, ...this._parseDataAttributes(), ...options };
            this.state = {
                sort: [],
                filters: {},
                externalFilters: new Set(),  // Track which filters came from FilterBus (for exact matching)
                dateRangeFilter: null,       // Track date range filter { startDate, endDate, key }
                globalSearch: '',
                page: 1,
                pageSize: this.config.pageSize,
                selectedRows: new Set(),
                columns: [],
                visibleColumns: new Set(),
                originalData: [],
                filteredData: [],
                initialized: false,
                // Column manipulation state
                columnWidths: {},           // Store custom column widths
                columnOrder: [],            // Store column order for reordering
                isResizing: false,          // Track resize operation
                isDraggingColumn: false,    // Track column drag operation
                isFullPage: false,          // Full page mode state
                savedViews: {}              // Stored view configurations
            };

            // Callbacks for server mode
            this.onSortChange = null;
            this.onFilterChange = null;
            this.onPageChange = null;
            this.onSelectionChange = null;
            this.onExport = null;

            // Register instance
            instances.set(this.table, this);

            this._init();
        }

        /**
         * Parse data attributes from table element
         */
        _parseDataAttributes() {
            const el = this.table;
            return {
                pageSize: parseInt(el.dataset.pageSize) || DEFAULT_CONFIG.pageSize,
                serverMode: el.dataset.serverMode === 'true',
                stickyHeader: el.hasAttribute('data-sticky-header'),
                striped: el.hasAttribute('data-striped') || el.dataset.striped !== 'false',
                responsive: el.dataset.responsive || DEFAULT_CONFIG.responsive,
                selectable: el.hasAttribute('data-selectable'),
                exportable: el.hasAttribute('data-exportable') || el.dataset.exportable !== 'false',
                exportFormats: el.dataset.exportFormats ? el.dataset.exportFormats.split(',') : DEFAULT_CONFIG.exportFormats,
                searchable: el.hasAttribute('data-searchable') || el.dataset.searchable !== 'false',
                // New features
                rowActions: el.hasAttribute('data-row-actions'),
                rowActionItems: el.dataset.rowActionItems ? el.dataset.rowActionItems.split(',') : DEFAULT_CONFIG.rowActionItems,
                quickFilters: el.dataset.quickFilters ? JSON.parse(el.dataset.quickFilters) : DEFAULT_CONFIG.quickFilters,
                copyable: el.hasAttribute('data-copyable'),
                conditionalFormatting: el.dataset.conditionalFormatting ? JSON.parse(el.dataset.conditionalFormatting) : DEFAULT_CONFIG.conditionalFormatting,
                // Advanced features
                inlineEditing: el.hasAttribute('data-inline-editing'),
                editableColumns: el.dataset.editableColumns ? el.dataset.editableColumns.split(',') : DEFAULT_CONFIG.editableColumns,
                summaryRow: el.hasAttribute('data-summary-row'),
                summaryColumns: el.dataset.summaryColumns ? JSON.parse(el.dataset.summaryColumns) : DEFAULT_CONFIG.summaryColumns,
                expandableRows: el.hasAttribute('data-expandable-rows'),
                expandableColumns: el.dataset.expandableColumns ? el.dataset.expandableColumns.split(',') : DEFAULT_CONFIG.expandableColumns,
                // Column manipulation features
                columnResizing: el.hasAttribute('data-column-resizing'),
                minColumnWidth: parseInt(el.dataset.minColumnWidth) || DEFAULT_CONFIG.minColumnWidth,
                columnReordering: el.hasAttribute('data-column-reordering'),
                // Frozen/Pinned columns
                frozenColumns: el.dataset.frozenColumns ? JSON.parse(el.dataset.frozenColumns) : DEFAULT_CONFIG.frozenColumns,
                // Bulk actions
                bulkActions: el.hasAttribute('data-bulk-actions'),
                bulkActionItems: el.dataset.bulkActionItems ? el.dataset.bulkActionItems.split(',') : DEFAULT_CONFIG.bulkActionItems,
                bulkStatusOptions: el.dataset.bulkStatusOptions ? el.dataset.bulkStatusOptions.split(',') : DEFAULT_CONFIG.bulkStatusOptions,
                // Saved views
                savedViews: el.hasAttribute('data-saved-views'),
                viewStorageKey: el.dataset.viewStorageKey || null,
                // Full page mode
                fullPageMode: el.hasAttribute('data-full-page-mode'),
                fullPagePadding: parseInt(el.dataset.fullPagePadding) || DEFAULT_CONFIG.fullPagePadding,
                // FilterBus integration
                filterSubscribe: el.dataset.filterSubscribe ? el.dataset.filterSubscribe.split(',').map(k => k.trim()) : [],
                filterMap: el.dataset.filterMap ? this._parseFilterMap(el.dataset.filterMap) : {},
                filterPublish: el.hasAttribute('data-filter-publish'),
                // FilterBus date range support
                filterBusDateField: el.dataset.filterbusDateField || el.dataset.filterBusDateField || null
            };
        }

        /**
         * Parse filter map attribute (format: "busKey:columnKey,busKey2:columnKey2")
         */
        _parseFilterMap(mapStr) {
            const map = {};
            mapStr.split(',').forEach(pair => {
                const [busKey, columnKey] = pair.split(':').map(s => s.trim());
                if (busKey && columnKey) {
                    map[busKey] = columnKey;
                }
            });
            return map;
        }

        /**
         * Initialize the Smart Table
         */
        _init() {
            if (this.state.initialized) return;

            // Setup columns FIRST so we have column keys
            this._setupColumns();

            // Store original data using column keys
            this._captureOriginalData();

            // Build UI wrapper
            this._buildWrapper();

            // Setup event listeners
            this._setupEventListeners();

            // Initial render
            this._applyFiltersAndSort();
            this._render();

            this.state.initialized = true;

            // Subscribe to FilterBus if configured
            this._setupFilterBusSubscription();

            // Dispatch init event
            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:init', {
                detail: { instance: this }
            }));
        }

        /**
         * Setup FilterBus subscription for external filtering
         */
        _setupFilterBusSubscription() {
            // Check if FilterBus is available and we have keys to subscribe to
            if (!window.RSL?.FilterBus || !this.config.filterSubscribe?.length) {
                return;
            }

            // Generate unique subscriber ID
            this._filterBusId = 'smart-table-' + (this.table.id || Math.random().toString(36).substr(2, 9));

            // Subscribe to FilterBus
            window.RSL.FilterBus.subscribe(
                this._filterBusId,
                this._handleFilterBusChange.bind(this),
                { keys: this.config.filterSubscribe }
            );

            // Apply any existing FilterBus state on init
            const currentState = window.RSL.FilterBus.getState();
            if (Object.keys(currentState).length > 0) {
                this._handleFilterBusChange(currentState, { source: 'init' });
            }
        }

        /**
         * Handle FilterBus state changes
         * @param {Object} state - Current filter state
         * @param {Object} meta - Change metadata
         */
        _handleFilterBusChange(state, meta) {
            if (!state) return;

            let hasChanges = false;

            // Process each subscribed key
            this.config.filterSubscribe.forEach(busKey => {
                const value = state[busKey];

                // Determine target: mapped column, matching column key, or global search
                let targetColumn = this.config.filterMap[busKey];

                // If no explicit mapping, check if busKey matches a column key
                if (!targetColumn) {
                    const matchingColumn = this.state.columns.find(col => col.key === busKey);
                    if (matchingColumn) {
                        targetColumn = busKey;
                    }
                }

                // Special handling for 'search' key - applies to global search
                if (busKey === 'search' || busKey === 'globalSearch') {
                    const newSearch = value || '';
                    if (this.state.globalSearch !== newSearch) {
                        this.state.globalSearch = newSearch;
                        // Update search input if it exists
                        const searchInput = this.container?.querySelector('.rsl-smart-table-search input');
                        if (searchInput && searchInput.value !== newSearch) {
                            searchInput.value = newSearch;
                        }
                        hasChanges = true;
                    }
                }
                // Special handling for date range filters (from Date Picker)
                else if (value && typeof value === 'object' && (value.mode === 'range' || value.mode === 'single') && this.config.filterBusDateField) {
                    const newDateRange = value.startDate ? {
                        startDate: value.startDate,
                        endDate: value.endDate || value.startDate,  // Single mode: use same date for both
                        key: busKey
                    } : null;

                    // Check if date range changed
                    const currentRange = this.state.dateRangeFilter;
                    const rangeChanged = !currentRange && newDateRange ||
                                        currentRange && !newDateRange ||
                                        (currentRange && newDateRange &&
                                         (currentRange.startDate !== newDateRange.startDate ||
                                          currentRange.endDate !== newDateRange.endDate));

                    if (rangeChanged) {
                        this.state.dateRangeFilter = newDateRange;
                        hasChanges = true;
                    }
                }
                // Clear date range if value is null/undefined and we have a date field configured
                else if ((value === null || value === undefined) && this.config.filterBusDateField && this.state.dateRangeFilter?.key === busKey) {
                    this.state.dateRangeFilter = null;
                    hasChanges = true;
                }
                else if (targetColumn) {
                    // Apply to specific column filter
                    const currentFilter = this.state.filters[targetColumn];
                    // Treat 'all', 'All', 'ALL', empty string, null, undefined as "clear filter"
                    const valueLower = (value || '').toString().toLowerCase();
                    const newFilter = valueLower === 'all' || value === '' || value === null || value === undefined ? undefined : value;

                    if (currentFilter !== newFilter) {
                        if (newFilter === undefined) {
                            delete this.state.filters[targetColumn];
                            // Remove from external filters tracking
                            this.state.externalFilters.delete(targetColumn);
                        } else {
                            this.state.filters[targetColumn] = newFilter;
                            // Mark as external filter (from FilterBus) for exact matching
                            this.state.externalFilters.add(targetColumn);
                        }
                        hasChanges = true;
                    }
                }
            });

            // Re-render if there were changes
            if (hasChanges) {
                this._applyFiltersAndSort();
                this._render();

                // Dispatch filter change event
                this.table.dispatchEvent(new CustomEvent('rsl-smart-table:filterbus-update', {
                    detail: { state, meta, instance: this }
                }));
            }
        }

        /**
         * Capture original table data
         */
        _captureOriginalData() {
            const tbody = this.table.querySelector('tbody');
            if (!tbody) return;

            const rows = Array.from(tbody.querySelectorAll('tr'));
            this.state.originalData = rows.map((row, index) => {
                const cells = Array.from(row.querySelectorAll('td'));
                const rowData = {
                    _element: row,
                    _index: index,
                    _id: row.dataset.id || `row-${index}`
                };

                cells.forEach((cell, cellIndex) => {
                    // Use the column key from state.columns (set up in _setupColumns)
                    // This ensures consistency between header keys and cell keys
                    const colKey = this.state.columns[cellIndex]?.key || `col-${cellIndex}`;
                    rowData[colKey] = {
                        value: this._getCellValue(cell),
                        display: cell.innerHTML,
                        element: cell
                    };
                });

                return rowData;
            });

            this.state.filteredData = [...this.state.originalData];
        }

        /**
         * Get sortable/filterable value from cell
         */
        _getCellValue(cell) {
            // Check for data-value attribute first
            if (cell.dataset.value !== undefined) {
                return cell.dataset.value;
            }
            // Use text content for sorting/filtering
            return cell.textContent.trim();
        }

        /**
         * Setup column configuration from headers
         */
        _setupColumns() {
            const thead = this.table.querySelector('thead');
            if (!thead) return;

            const headers = Array.from(thead.querySelectorAll('th'));
            this.state.columns = headers.map((th, index) => {
                const col = {
                    key: th.dataset.col || `col-${index}`,
                    label: th.textContent.trim(),
                    element: th,
                    // Sortable by default unless explicitly set to false
                    sortable: th.dataset.sortable !== 'false',
                    filterable: th.hasAttribute('data-filterable') || th.dataset.filter,
                    filterType: th.dataset.filter || 'text',
                    filterOptions: th.dataset.filterOptions ? th.dataset.filterOptions.split(',') : null,
                    type: th.dataset.type || 'string',
                    visible: th.dataset.visible !== 'false',
                    width: th.dataset.width || null
                };

                // Add sortable attribute and accessibility for keyboard navigation
                if (col.sortable) {
                    th.setAttribute('data-sortable', '');
                    th.setAttribute('tabindex', '0');
                    th.setAttribute('role', 'columnheader');
                    th.setAttribute('aria-sort', 'none');
                }

                this.state.visibleColumns.add(col.key);
                return col;
            });
        }

        /**
         * Build the wrapper UI (toolbar, footer, etc.)
         */
        _buildWrapper() {
            // Create container
            this.container = document.createElement('div');
            this.container.className = 'rsl-smart-table-container';

            if (this.config.stickyHeader) {
                this.container.setAttribute('data-sticky-header', '');
            }

            // Insert container around table
            this.table.parentNode.insertBefore(this.container, this.table);

            // Build toolbar
            if (this.config.searchable || this.config.exportable) {
                this._buildToolbar();
            }

            // Add selection bar
            if (this.config.selectable) {
                this._buildSelectionBar();
                this._addSelectionColumn();
            }

            // Add row actions column
            if (this.config.rowActions) {
                this._addRowActionsColumn();
            }

            // Wrap table for scroll
            this.tableWrapper = document.createElement('div');
            this.tableWrapper.className = 'rsl-smart-table-wrapper';
            this.tableWrapper.appendChild(this.table);
            this.container.appendChild(this.tableWrapper);

            // Set custom sticky height if specified
            if (this.config.stickyHeader) {
                const stickyHeight = this.table.dataset.stickyHeight;
                if (stickyHeight) {
                    this.tableWrapper.style.maxHeight = stickyHeight;
                }
            }

            // Build column filters
            if (this.state.columns.some(col => col.filterable)) {
                this._buildColumnFilters();
            }

            // Build footer
            if (this.config.showInfo || this.config.showPagination) {
                this._buildFooter();
            }

            // Add expandable row column
            if (this.config.expandableRows) {
                this._addExpandColumn();
            }

            // Add necessary classes to table
            this.table.classList.add('rsl-smart-table');
            if (this.config.striped) {
                this.table.setAttribute('data-striped', '');
            }
            if (this.config.responsive) {
                this.table.setAttribute('data-responsive', this.config.responsive);
            }

            // Enable inline editing
            if (this.config.inlineEditing) {
                this._setupInlineEditing();
            }

            // Enable column resizing
            if (this.config.columnResizing) {
                this._setupColumnResizing();
            }

            // Enable column reordering
            if (this.config.columnReordering) {
                this._setupColumnReordering();
            }

            // Setup frozen/pinned columns
            if (this.config.frozenColumns.left.length > 0 || this.config.frozenColumns.right.length > 0) {
                this._setupFrozenColumns();
            }

            // Setup bulk actions bar
            if (this.config.bulkActions && this.config.selectable) {
                this._buildBulkActionsBar();
            }

            // Setup saved views
            if (this.config.savedViews) {
                this._setupSavedViews();
            }

            // Setup full page mode button
            if (this.config.fullPageMode) {
                this._setupFullPageMode();
            }
        }

        /**
         * Build toolbar with search and actions
         */
        _buildToolbar() {
            this.toolbar = document.createElement('div');
            this.toolbar.className = 'rsl-smart-table-toolbar';
            this.toolbar.setAttribute('role', 'toolbar');
            this.toolbar.setAttribute('aria-label', 'Table controls');

            // Left side - Search
            const toolbarLeft = document.createElement('div');
            toolbarLeft.className = 'rsl-smart-table-toolbar-left';

            if (this.config.searchable) {
                const searchContainer = document.createElement('div');
                searchContainer.className = 'rsl-smart-table-search';

                const searchIcon = document.createElement('span');
                searchIcon.className = 'rsl-smart-table-search-icon';
                searchIcon.innerHTML = '<i class="fas fa-search" aria-hidden="true"></i>';

                this.searchInput = document.createElement('input');
                this.searchInput.type = 'search';
                this.searchInput.placeholder = 'Search...';
                this.searchInput.setAttribute('aria-label', 'Search table');

                const clearBtn = document.createElement('button');
                clearBtn.className = 'rsl-smart-table-search-clear';
                clearBtn.innerHTML = '<i class="fas fa-times" aria-hidden="true"></i>';
                clearBtn.setAttribute('aria-label', 'Clear search');
                clearBtn.type = 'button';

                searchContainer.appendChild(searchIcon);
                searchContainer.appendChild(this.searchInput);
                searchContainer.appendChild(clearBtn);
                toolbarLeft.appendChild(searchContainer);
            }

            // Quick Filters (between search and right actions)
            if (this.config.quickFilters && this.config.quickFilters.length > 0) {
                const quickFiltersContainer = document.createElement('div');
                quickFiltersContainer.className = 'rsl-smart-table-quick-filters';
                quickFiltersContainer.setAttribute('role', 'group');
                quickFiltersContainer.setAttribute('aria-label', 'Quick filters');

                this.config.quickFilters.forEach((filter, index) => {
                    const chip = document.createElement('button');
                    chip.className = 'rsl-smart-table-quick-filter';
                    chip.type = 'button';
                    chip.innerHTML = filter.icon ? `<i class="${filter.icon}" aria-hidden="true"></i> ${filter.label}` : filter.label;
                    chip.dataset.filterIndex = index;

                    if (filter.color) {
                        chip.style.setProperty('--chip-color', filter.color);
                        chip.classList.add('rsl-quick-filter-colored');
                    }

                    chip.addEventListener('click', () => this._applyQuickFilter(filter, chip));
                    quickFiltersContainer.appendChild(chip);
                });

                // Add "Clear" chip
                const clearChip = document.createElement('button');
                clearChip.className = 'rsl-smart-table-quick-filter rsl-quick-filter-clear';
                clearChip.type = 'button';
                clearChip.innerHTML = '<i class="fas fa-times" aria-hidden="true"></i> Clear';
                clearChip.style.display = 'none';
                clearChip.addEventListener('click', () => this._clearQuickFilters());
                quickFiltersContainer.appendChild(clearChip);
                this.quickFilterClearBtn = clearChip;

                toolbarLeft.appendChild(quickFiltersContainer);
            }

            // Right side - Actions
            const toolbarRight = document.createElement('div');
            toolbarRight.className = 'rsl-smart-table-toolbar-right';

            // Copy to Clipboard button
            if (this.config.copyable) {
                const copyBtn = document.createElement('button');
                copyBtn.className = 'rsl-smart-table-btn';
                copyBtn.type = 'button';
                copyBtn.innerHTML = '<i class="fas fa-copy" aria-hidden="true"></i> Copy';
                copyBtn.setAttribute('aria-label', 'Copy table data to clipboard');
                copyBtn.addEventListener('click', () => this.copyToClipboard());
                toolbarRight.appendChild(copyBtn);
            }

            // Column visibility toggle
            if (this.state.columns.length > 0) {
                const columnsBtn = this._createDropdownButton(
                    '<i class="fas fa-columns" aria-hidden="true"></i> Columns',
                    this._buildColumnsPanel(),
                    'Toggle column visibility'
                );
                toolbarRight.appendChild(columnsBtn);
            }

            // Export dropdown
            if (this.config.exportable && this.config.exportFormats.length > 0) {
                const exportBtn = this._createDropdownButton(
                    '<i class="fas fa-download" aria-hidden="true"></i> Export',
                    this._buildExportMenu(),
                    'Export table data',
                    'rsl-smart-table-btn-export'
                );
                toolbarRight.appendChild(exportBtn);
            }

            this.toolbar.appendChild(toolbarLeft);
            this.toolbar.appendChild(toolbarRight);
            this.container.appendChild(this.toolbar);
        }

        /**
         * Create a dropdown button
         */
        _createDropdownButton(label, content, ariaLabel, extraClass = '') {
            const wrapper = document.createElement('div');
            wrapper.className = `rsl-smart-table-btn-dropdown ${extraClass}`.trim();

            const btn = document.createElement('button');
            btn.className = `rsl-smart-table-btn ${extraClass}`.trim();
            btn.innerHTML = `${label} <i class="fas fa-chevron-down" aria-hidden="true"></i>`;
            btn.setAttribute('aria-label', ariaLabel);
            btn.setAttribute('aria-expanded', 'false');
            btn.setAttribute('aria-haspopup', 'true');
            btn.type = 'button';

            const dropdown = document.createElement('div');
            dropdown.className = 'rsl-smart-table-dropdown';
            dropdown.setAttribute('role', 'menu');
            dropdown.appendChild(content);

            wrapper.appendChild(btn);
            wrapper.appendChild(dropdown);

            // Toggle dropdown
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const isOpen = wrapper.classList.contains('open');

                // Close all other dropdowns
                document.querySelectorAll('.rsl-smart-table-btn-dropdown.open').forEach(d => {
                    d.classList.remove('open');
                    d.querySelector('button').setAttribute('aria-expanded', 'false');
                });

                if (!isOpen) {
                    wrapper.classList.add('open');
                    btn.setAttribute('aria-expanded', 'true');
                }
            });

            // Close on click outside
            document.addEventListener('click', () => {
                wrapper.classList.remove('open');
                btn.setAttribute('aria-expanded', 'false');
            });

            return wrapper;
        }

        /**
         * Build columns visibility panel
         */
        _buildColumnsPanel() {
            const panel = document.createElement('div');
            panel.className = 'rsl-smart-table-columns-panel';

            this.state.columns.forEach(col => {
                const toggle = document.createElement('div');
                toggle.className = 'rsl-smart-table-column-toggle';

                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.id = `col-toggle-${col.key}`;
                checkbox.checked = this.state.visibleColumns.has(col.key);

                const label = document.createElement('label');
                label.htmlFor = checkbox.id;
                label.textContent = col.label;

                checkbox.addEventListener('change', () => {
                    this.toggleColumn(col.key, checkbox.checked);
                });

                toggle.appendChild(checkbox);
                toggle.appendChild(label);
                panel.appendChild(toggle);
            });

            return panel;
        }

        /**
         * Build export menu
         */
        _buildExportMenu() {
            const menu = document.createElement('div');

            // Scope selection header
            const scopeHeader = document.createElement('div');
            scopeHeader.className = 'rsl-smart-table-dropdown-header';
            scopeHeader.textContent = 'What to export:';
            menu.appendChild(scopeHeader);

            // Scope options
            const scopeOptions = document.createElement('div');
            scopeOptions.className = 'rsl-smart-table-export-scope';

            const scopes = [
                { id: 'filtered', icon: 'fa-filter', label: 'Current View', desc: 'Filtered/sorted rows' },
                { id: 'all', icon: 'fa-table', label: 'All Data', desc: 'All rows in table' },
                { id: 'selected', icon: 'fa-check-square', label: 'Selected', desc: 'Checked rows only' }
            ];

            scopes.forEach(scope => {
                const btn = document.createElement('button');
                btn.className = 'rsl-smart-table-dropdown-item rsl-smart-table-scope-btn';
                btn.setAttribute('role', 'menuitemradio');
                btn.setAttribute('aria-checked', scope.id === 'filtered' ? 'true' : 'false');
                btn.dataset.scope = scope.id;
                btn.innerHTML = `<i class="fas ${scope.icon}" aria-hidden="true"></i> ${scope.label}`;
                btn.title = scope.desc;

                if (scope.id === 'filtered') {
                    btn.classList.add('active');
                }

                btn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    // Update active state
                    scopeOptions.querySelectorAll('.rsl-smart-table-scope-btn').forEach(b => {
                        b.classList.remove('active');
                        b.setAttribute('aria-checked', 'false');
                    });
                    btn.classList.add('active');
                    btn.setAttribute('aria-checked', 'true');
                    this.state.exportScope = scope.id;
                });

                scopeOptions.appendChild(btn);
            });

            menu.appendChild(scopeOptions);

            // Divider
            const divider = document.createElement('div');
            divider.className = 'rsl-smart-table-dropdown-divider';
            menu.appendChild(divider);

            // Format header
            const formatHeader = document.createElement('div');
            formatHeader.className = 'rsl-smart-table-dropdown-header';
            formatHeader.textContent = 'Export format:';
            menu.appendChild(formatHeader);

            const formatIcons = {
                csv: 'fa-file-csv',
                json: 'fa-file-code',
                excel: 'fa-file-excel'
            };

            const formatLabels = {
                csv: 'Download CSV',
                json: 'Download JSON',
                excel: 'Download Excel'
            };

            this.config.exportFormats.forEach(format => {
                const btn = document.createElement('button');
                btn.className = 'rsl-smart-table-dropdown-item';
                btn.setAttribute('role', 'menuitem');
                btn.innerHTML = `<i class="fas ${formatIcons[format] || 'fa-file'}" aria-hidden="true"></i> ${formatLabels[format] || format.toUpperCase()}`;
                btn.addEventListener('click', () => {
                    const scope = this.state.exportScope || 'filtered';
                    this.export(format, scope);
                });
                menu.appendChild(btn);
            });

            // Initialize export scope state
            this.state.exportScope = 'filtered';

            return menu;
        }

        /**
         * Build selection bar
         */
        _buildSelectionBar() {
            this.selectionBar = document.createElement('div');
            this.selectionBar.className = 'rsl-smart-table-selection-bar';
            this.selectionBar.setAttribute('role', 'status');
            this.selectionBar.setAttribute('aria-live', 'polite');

            const info = document.createElement('div');
            info.className = 'rsl-smart-table-selection-info';
            info.innerHTML = '<span class="selection-count">0</span> rows selected';

            const actions = document.createElement('div');
            actions.className = 'rsl-smart-table-selection-actions';

            const clearBtn = document.createElement('button');
            clearBtn.className = 'rsl-smart-table-btn';
            clearBtn.innerHTML = '<i class="fas fa-times" aria-hidden="true"></i> Clear';
            clearBtn.addEventListener('click', () => this.clearSelection());

            actions.appendChild(clearBtn);

            this.selectionBar.appendChild(info);
            this.selectionBar.appendChild(actions);
            this.container.appendChild(this.selectionBar);
        }

        /**
         * Add selection checkbox column
         */
        _addSelectionColumn() {
            const thead = this.table.querySelector('thead tr');
            const tbody = this.table.querySelector('tbody');

            // Add header checkbox
            const th = document.createElement('th');
            th.className = 'rsl-select-col';

            const selectAll = document.createElement('input');
            selectAll.type = 'checkbox';
            selectAll.className = 'rsl-smart-table-checkbox rsl-smart-table-select-all';
            selectAll.setAttribute('aria-label', 'Select all rows');

            th.appendChild(selectAll);
            thead.insertBefore(th, thead.firstChild);

            // Add body checkboxes
            tbody.querySelectorAll('tr').forEach(row => {
                const td = document.createElement('td');
                td.className = 'rsl-select-col';

                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'rsl-smart-table-checkbox';
                checkbox.setAttribute('aria-label', 'Select row');

                td.appendChild(checkbox);
                row.insertBefore(td, row.firstChild);
            });
        }

        /**
         * Add row actions column
         */
        _addRowActionsColumn() {
            const thead = this.table.querySelector('thead tr:not(.rsl-smart-table-filter-row)');
            const tbody = this.table.querySelector('tbody');

            // Add header
            const th = document.createElement('th');
            th.className = 'rsl-actions-col';
            th.textContent = 'Actions';
            thead.appendChild(th);

            // Add action buttons to each row
            tbody.querySelectorAll('tr').forEach((row, index) => {
                const td = document.createElement('td');
                td.className = 'rsl-actions-col';

                const actionsWrapper = document.createElement('div');
                actionsWrapper.className = 'rsl-row-actions';

                // Create action buttons based on config
                const actionIcons = {
                    view: { icon: 'fa-eye', label: 'View' },
                    edit: { icon: 'fa-edit', label: 'Edit' },
                    delete: { icon: 'fa-trash', label: 'Delete' },
                    copy: { icon: 'fa-copy', label: 'Copy' },
                    download: { icon: 'fa-download', label: 'Download' },
                    archive: { icon: 'fa-archive', label: 'Archive' }
                };

                this.config.rowActionItems.forEach(action => {
                    const actionInfo = actionIcons[action] || { icon: 'fa-cog', label: action };
                    const btn = document.createElement('button');
                    btn.className = `rsl-row-action-btn rsl-row-action-${action}`;
                    btn.type = 'button';
                    btn.innerHTML = `<i class="fas ${actionInfo.icon}" aria-hidden="true"></i>`;
                    btn.setAttribute('aria-label', `${actionInfo.label} row`);
                    btn.setAttribute('title', actionInfo.label);

                    btn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this._handleRowAction(action, row, index);
                    });

                    actionsWrapper.appendChild(btn);
                });

                td.appendChild(actionsWrapper);
                row.appendChild(td);
            });

            // Add empty cell to filter row if it exists
            const filterRow = this.table.querySelector('thead tr.rsl-smart-table-filter-row');
            if (filterRow) {
                const filterTh = document.createElement('th');
                filterTh.className = 'rsl-actions-col';
                filterRow.appendChild(filterTh);
            }
        }

        /**
         * Handle row action click
         */
        _handleRowAction(action, rowElement, rowIndex) {
            const rowData = this.state.originalData.find(r => r._element === rowElement);

            // Dispatch custom event
            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:row-action', {
                bubbles: true,
                detail: {
                    action: action,
                    row: rowData,
                    rowIndex: rowIndex,
                    element: rowElement
                }
            }));

            // Call callback if provided
            if (this.onRowAction) {
                this.onRowAction(action, rowData, rowIndex, rowElement);
            }
        }

        /**
         * Build column filters
         */
        _buildColumnFilters() {
            const thead = this.table.querySelector('thead');
            const filterRow = document.createElement('tr');
            filterRow.className = 'rsl-smart-table-filter-row';

            this.state.columns.forEach(col => {
                const th = document.createElement('th');

                if (col.filterable) {
                    const filter = document.createElement('div');
                    filter.className = 'rsl-smart-table-filter';

                    if (col.filterType === 'select') {
                        const select = document.createElement('select');
                        select.setAttribute('aria-label', `Filter by ${col.label}`);

                        const defaultOption = document.createElement('option');
                        defaultOption.value = '';
                        defaultOption.textContent = `All ${col.label}`;
                        select.appendChild(defaultOption);

                        const options = col.filterOptions || this._getUniqueValues(col.key);
                        options.forEach(opt => {
                            const option = document.createElement('option');
                            option.value = opt;
                            option.textContent = opt;
                            select.appendChild(option);
                        });

                        select.addEventListener('change', () => {
                            this.filterColumn(col.key, select.value);
                        });

                        filter.appendChild(select);
                    } else {
                        const input = document.createElement('input');
                        input.type = col.filterType === 'number' ? 'number' : 'text';
                        input.placeholder = `Filter ${col.label}...`;
                        input.setAttribute('aria-label', `Filter by ${col.label}`);

                        let debounceTimer;
                        input.addEventListener('input', () => {
                            clearTimeout(debounceTimer);
                            debounceTimer = setTimeout(() => {
                                this.filterColumn(col.key, input.value);
                            }, this.config.searchDebounce);
                        });

                        filter.appendChild(input);
                    }

                    th.appendChild(filter);
                }

                filterRow.appendChild(th);
            });

            // Insert filter row if selection column exists
            if (this.config.selectable) {
                const emptyTh = document.createElement('th');
                filterRow.insertBefore(emptyTh, filterRow.firstChild);
            }

            thead.appendChild(filterRow);
        }

        /**
         * Get unique values from a column
         */
        _getUniqueValues(key) {
            const values = new Set();
            this.state.originalData.forEach(row => {
                if (row[key]) {
                    values.add(row[key].value);
                }
            });
            return Array.from(values).sort();
        }

        /**
         * Build footer with info and pagination
         */
        _buildFooter() {
            this.footer = document.createElement('div');
            this.footer.className = 'rsl-smart-table-footer';

            // Info section
            if (this.config.showInfo) {
                const info = document.createElement('div');
                info.className = 'rsl-smart-table-info';

                this.infoDisplay = document.createElement('span');
                this.infoDisplay.className = 'rsl-smart-table-info-item';
                info.appendChild(this.infoDisplay);

                if (this.config.showPageSize) {
                    const pageSizeContainer = document.createElement('div');
                    pageSizeContainer.className = 'rsl-smart-table-page-size';
                    pageSizeContainer.innerHTML = '<span>Show</span>';

                    // Store reference to select for debugging and state sync
                    this.pageSizeSelect = document.createElement('select');
                    this.pageSizeSelect.setAttribute('aria-label', 'Rows per page');

                    this.config.pageSizes.forEach(size => {
                        const option = document.createElement('option');
                        option.value = size;
                        option.textContent = size;
                        if (size === this.state.pageSize) option.selected = true;
                        this.pageSizeSelect.appendChild(option);
                    });

                    this.pageSizeSelect.addEventListener('change', (e) => {
                        const newSize = parseInt(e.target.value, 10);
                        this.setPageSize(newSize);
                    });

                    pageSizeContainer.appendChild(this.pageSizeSelect);

                    // Use createElement instead of innerHTML += to preserve event listeners
                    const entriesLabel = document.createElement('span');
                    entriesLabel.textContent = 'entries';
                    pageSizeContainer.appendChild(entriesLabel);

                    info.appendChild(pageSizeContainer);
                }

                this.footer.appendChild(info);
            }

            // Pagination
            if (this.config.showPagination) {
                this.paginationContainer = document.createElement('nav');
                this.paginationContainer.className = 'rsl-smart-table-pagination';
                this.paginationContainer.setAttribute('aria-label', 'Table pagination');
                this.footer.appendChild(this.paginationContainer);
            }

            this.container.appendChild(this.footer);
        }

        /**
         * Setup all event listeners
         */
        _setupEventListeners() {
            // Search input
            if (this.searchInput) {
                let debounceTimer;
                this.searchInput.addEventListener('input', () => {
                    const container = this.searchInput.parentElement;
                    if (this.searchInput.value) {
                        container.classList.add('has-value');
                    } else {
                        container.classList.remove('has-value');
                    }

                    clearTimeout(debounceTimer);
                    debounceTimer = setTimeout(() => {
                        this.search(this.searchInput.value);
                    }, this.config.searchDebounce);
                });

                // Clear button
                const clearBtn = this.searchInput.parentElement.querySelector('.rsl-smart-table-search-clear');
                if (clearBtn) {
                    clearBtn.addEventListener('click', () => {
                        this.searchInput.value = '';
                        this.searchInput.parentElement.classList.remove('has-value');
                        this.search('');
                        this.searchInput.focus();
                    });
                }
            }

            // Sortable headers
            this.state.columns.forEach(col => {
                if (col.sortable) {
                    col.element.addEventListener('click', (e) => {
                        this._handleSort(col.key, e.shiftKey);
                    });

                    col.element.addEventListener('keydown', (e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            this._handleSort(col.key, e.shiftKey);
                        }
                    });
                }
            });

            // Row selection
            if (this.config.selectable) {
                // Select all
                const selectAll = this.table.querySelector('.rsl-smart-table-select-all');
                if (selectAll) {
                    selectAll.addEventListener('change', () => {
                        if (selectAll.checked) {
                            this.selectAll();
                        } else {
                            this.clearSelection();
                        }
                    });
                }

                // Individual row selection
                this.table.querySelector('tbody').addEventListener('change', (e) => {
                    if (e.target.classList.contains('rsl-smart-table-checkbox')) {
                        const row = e.target.closest('tr');
                        // Find the row data to get the correct _id
                        const rowData = this.state.originalData.find(r => r._element === row);
                        const rowId = rowData ? rowData._id : (row.dataset.id || `row-${row.rowIndex}`);

                        if (e.target.checked) {
                            this.selectRow(rowId);
                        } else {
                            this.deselectRow(rowId);
                        }
                    }
                });
            }

            // Keyboard navigation for pagination
            if (this.paginationContainer) {
                this.paginationContainer.addEventListener('keydown', (e) => {
                    if (e.key === 'ArrowLeft') {
                        e.preventDefault();
                        this.prevPage();
                    } else if (e.key === 'ArrowRight') {
                        e.preventDefault();
                        this.nextPage();
                    }
                });
            }

            // Arrow key grid navigation
            this._setupGridNavigation();
        }

        /**
         * Setup arrow key navigation for table grid (WAI-ARIA grid pattern)
         */
        _setupGridNavigation() {
            // Make table focusable and add ARIA role
            this.table.setAttribute('role', 'grid');
            this.table.setAttribute('tabindex', '0');

            // Track current focused cell
            this.focusedCell = { row: 0, col: 0 };

            // Add role to rows and cells
            const allRows = this.table.querySelectorAll('tr');
            allRows.forEach((row, rowIndex) => {
                row.setAttribute('role', 'row');
                const cells = row.querySelectorAll('th, td');
                cells.forEach((cell, cellIndex) => {
                    cell.setAttribute('role', rowIndex === 0 ? 'columnheader' : 'gridcell');
                    cell.setAttribute('tabindex', '-1');
                });
            });

            // Main keyboard handler
            this.table.addEventListener('keydown', (e) => {
                const isNavigationKey = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
                                         'Home', 'End', 'PageUp', 'PageDown'].includes(e.key);

                if (!isNavigationKey) return;

                // Don't intercept if focus is on an input/select (let them handle arrows)
                const activeEl = document.activeElement;
                if (activeEl && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'SELECT')) {
                    // Only intercept up/down arrows to exit the field
                    if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') {
                        return;
                    }
                }

                e.preventDefault();

                // Build row list: header, filter row (if exists), body rows
                const headerRow = this.table.querySelector('thead tr:not(.rsl-smart-table-filter-row)');
                const filterRow = this.table.querySelector('thead tr.rsl-smart-table-filter-row');
                const bodyRows = Array.from(this.table.querySelectorAll('tbody tr:not([style*="display: none"])'));

                const allVisibleRows = [];
                if (headerRow) allVisibleRows.push(headerRow);
                if (filterRow) allVisibleRows.push(filterRow);
                allVisibleRows.push(...bodyRows);

                if (allVisibleRows.length === 0) return;

                let { row, col } = this.focusedCell;
                const currentRow = allVisibleRows[row];
                if (!currentRow) return;

                const cols = currentRow.querySelectorAll('th, td').length;

                switch (e.key) {
                    case 'ArrowUp':
                        row = Math.max(0, row - 1);
                        break;
                    case 'ArrowDown':
                        row = Math.min(allVisibleRows.length - 1, row + 1);
                        break;
                    case 'ArrowLeft':
                        col = Math.max(0, col - 1);
                        break;
                    case 'ArrowRight':
                        col = Math.min(cols - 1, col + 1);
                        break;
                    case 'Home':
                        if (e.ctrlKey) {
                            row = 0;
                        }
                        col = 0;
                        break;
                    case 'End':
                        if (e.ctrlKey) {
                            row = allVisibleRows.length - 1;
                        }
                        col = cols - 1;
                        break;
                    case 'PageUp':
                        this.prevPage();
                        return;
                    case 'PageDown':
                        this.nextPage();
                        return;
                }

                this._focusCell(row, col);
            });

            // Handle Enter/Space on focused cell
            this.table.addEventListener('keydown', (e) => {
                if (e.key !== 'Enter' && e.key !== ' ') return;

                const focusedElement = this.table.querySelector('[tabindex="0"]:not(table)');
                if (!focusedElement) return;

                // If it's a header, trigger sort
                if (focusedElement.tagName === 'TH' && focusedElement.hasAttribute('data-sortable')) {
                    e.preventDefault();
                    const colKey = focusedElement.dataset.col;
                    if (colKey) {
                        this._handleSort(colKey, e.shiftKey);
                    }
                }

                // If it contains a checkbox, toggle it
                const checkbox = focusedElement.querySelector('input[type="checkbox"]');
                if (checkbox && e.key === ' ') {
                    e.preventDefault();
                    checkbox.checked = !checkbox.checked;
                    checkbox.dispatchEvent(new Event('change', { bubbles: true }));
                }
            });

            // Focus table on click
            this.table.addEventListener('click', (e) => {
                const cell = e.target.closest('th, td');
                if (cell) {
                    const row = cell.closest('tr');
                    const allRows = Array.from(this.table.querySelectorAll('tr'));
                    const rowIndex = allRows.indexOf(row);
                    const cellIndex = Array.from(row.querySelectorAll('th, td')).indexOf(cell);
                    this._focusCell(rowIndex, cellIndex);
                }
            });
        }

        /**
         * Focus a specific cell in the grid
         */
        _focusCell(rowIndex, colIndex) {
            // Remove focus from previous cell
            const prevFocused = this.table.querySelector('[tabindex="0"]:not(table)');
            if (prevFocused) {
                prevFocused.setAttribute('tabindex', '-1');
                prevFocused.classList.remove('rsl-cell-focused');
            }

            // Get all rows (including header and filter row)
            const headerRow = this.table.querySelector('thead tr:not(.rsl-smart-table-filter-row)');
            const filterRow = this.table.querySelector('thead tr.rsl-smart-table-filter-row');
            const bodyRows = Array.from(this.table.querySelectorAll('tbody tr:not([style*="display: none"])'));

            // Build row list: header, filter row (if exists), body rows
            const allRows = [];
            if (headerRow) allRows.push(headerRow);
            if (filterRow) allRows.push(filterRow);
            allRows.push(...bodyRows);

            // Find and focus new cell
            const targetRow = allRows[rowIndex];
            if (!targetRow) return;

            const cells = targetRow.querySelectorAll('th, td');
            const targetCell = cells[colIndex];
            if (!targetCell) return;

            // Check if cell contains an interactive element (input, select, button)
            const interactive = targetCell.querySelector('select, input, button:not(.rsl-smart-table-checkbox)');

            if (interactive) {
                // Focus the interactive element directly
                interactive.focus();
                targetCell.classList.add('rsl-cell-focused');
            } else {
                // Focus the cell itself
                targetCell.setAttribute('tabindex', '0');
                targetCell.classList.add('rsl-cell-focused');
                targetCell.focus();
            }

            this.focusedCell = { row: rowIndex, col: colIndex };

            // Announce to screen readers
            this._announceCell(targetCell, rowIndex, colIndex);
        }

        /**
         * Announce cell content to screen readers
         */
        _announceCell(cell, rowIndex, colIndex) {
            // Create or get live region
            let liveRegion = this.container.querySelector('.rsl-smart-table-live-region');
            if (!liveRegion) {
                liveRegion = document.createElement('div');
                liveRegion.className = 'rsl-smart-table-live-region';
                liveRegion.setAttribute('aria-live', 'polite');
                liveRegion.setAttribute('aria-atomic', 'true');
                liveRegion.style.cssText = 'position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden;';
                this.container.appendChild(liveRegion);
            }

            // Build announcement
            const isHeader = cell.tagName === 'TH';
            const colHeader = this.state.columns[colIndex - (this.config.selectable ? 1 : 0)]?.label || '';
            const cellContent = cell.textContent.trim();

            let announcement = '';
            if (isHeader) {
                announcement = `Column header: ${cellContent}`;
                if (cell.hasAttribute('data-sort')) {
                    announcement += `, sorted ${cell.dataset.sort === 'asc' ? 'ascending' : 'descending'}`;
                }
            } else {
                announcement = `Row ${rowIndex}, ${colHeader}: ${cellContent}`;
            }

            liveRegion.textContent = announcement;
        }

        /**
         * Handle sort click/keypress
         */
        _handleSort(key, multiSort = false) {
            const existingSort = this.state.sort.find(s => s.column === key);

            if (!multiSort) {
                // Single column sort - clear others
                this.state.sort = [];
            }

            if (existingSort) {
                if (existingSort.direction === 'asc') {
                    existingSort.direction = 'desc';
                } else if (existingSort.direction === 'desc') {
                    // Remove sort
                    this.state.sort = this.state.sort.filter(s => s.column !== key);
                }
            } else {
                this.state.sort.push({ column: key, direction: 'asc' });
            }

            // Update header indicators
            this._updateSortIndicators();

            // Apply and render
            this._applyFiltersAndSort();
            this._render();

            // Callback
            if (this.onSortChange) {
                this.onSortChange(this.getState());
            }

            // Dispatch event
            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:sort', {
                detail: { sort: this.state.sort, state: this.getState() }
            }));
        }

        /**
         * Update sort indicators on headers
         */
        _updateSortIndicators() {
            // Clear all
            this.state.columns.forEach(col => {
                col.element.removeAttribute('data-sort');
                col.element.removeAttribute('data-sort-order');
                col.element.setAttribute('aria-sort', 'none');
            });

            // Set active sorts
            this.state.sort.forEach((sort, index) => {
                const col = this.state.columns.find(c => c.key === sort.column);
                if (col) {
                    col.element.setAttribute('data-sort', sort.direction);
                    col.element.setAttribute('aria-sort', sort.direction === 'asc' ? 'ascending' : 'descending');
                    if (this.state.sort.length > 1) {
                        col.element.setAttribute('data-sort-order', index + 1);
                    }
                }
            });
        }

        /**
         * Apply filters and sorting to data
         */
        _applyFiltersAndSort() {
            if (this.config.serverMode) return;

            let data = [...this.state.originalData];

            // Apply global search
            if (this.state.globalSearch) {
                const searchLower = this.state.globalSearch.toLowerCase();
                data = data.filter(row => {
                    return Object.keys(row).some(key => {
                        if (key.startsWith('_')) return false;
                        const val = row[key]?.value;
                        return val && String(val).toLowerCase().includes(searchLower);
                    });
                });
            }

            // Apply column filters
            Object.keys(this.state.filters).forEach(key => {
                const filterValue = this.state.filters[key];
                if (!filterValue) return;

                data = data.filter(row => {
                    const cellValue = row[key]?.value;
                    if (!cellValue) return false;

                    // Check if this filter came from FilterBus (external) - use exact match
                    // Internal filters (from column filter inputs) use substring match
                    const isExternalFilter = this.state.externalFilters && this.state.externalFilters.has(key);

                    if (isExternalFilter) {
                        // Exact match for external/FilterBus filters
                        return String(cellValue).toLowerCase() === String(filterValue).toLowerCase();
                    } else {
                        // Substring match for internal column filters (text input)
                        return String(cellValue).toLowerCase().includes(String(filterValue).toLowerCase());
                    }
                });
            });

            // Apply date range filter (from FilterBus Date Picker)
            if (this.state.dateRangeFilter && this.config.filterBusDateField) {
                const dateField = this.config.filterBusDateField;
                const { startDate, endDate } = this.state.dateRangeFilter;

                // Parse filter dates (ISO format from Date Picker)
                const filterStart = this._parseDate(startDate);
                const filterEnd = this._parseDate(endDate);

                if (filterStart && filterEnd) {
                    // Set end date to end of day for inclusive filtering
                    filterEnd.setHours(23, 59, 59, 999);

                    data = data.filter(row => {
                        const cellValue = row[dateField]?.value;
                        if (!cellValue) return false;

                        const rowDate = this._parseDate(cellValue);
                        if (!rowDate) return false;

                        // Check if row date is within range (inclusive)
                        return rowDate >= filterStart && rowDate <= filterEnd;
                    });
                }
            }

            // Apply quick filters
            if (this.state.quickFilterFn) {
                data = data.filter(row => this.state.quickFilterFn(row));
            } else if (this.state.quickFilterColumn && this.state.quickFilterValue !== undefined) {
                data = data.filter(row => {
                    const cellValue = row[this.state.quickFilterColumn]?.value;
                    return cellValue == this.state.quickFilterValue;
                });
            }

            // Apply sorting
            if (this.state.sort.length > 0) {
                data.sort((a, b) => {
                    for (const sort of this.state.sort) {
                        const col = this.state.columns.find(c => c.key === sort.column);
                        const aVal = a[sort.column]?.value;
                        const bVal = b[sort.column]?.value;

                        let comparison = 0;

                        if (col?.type === 'number' || col?.type === 'currency') {
                            const aNum = parseFloat(String(aVal).replace(/[^0-9.-]/g, '')) || 0;
                            const bNum = parseFloat(String(bVal).replace(/[^0-9.-]/g, '')) || 0;
                            comparison = aNum - bNum;
                        } else if (col?.type === 'date') {
                            const aDate = new Date(aVal);
                            const bDate = new Date(bVal);
                            comparison = aDate - bDate;
                        } else {
                            comparison = String(aVal || '').localeCompare(String(bVal || ''));
                        }

                        if (comparison !== 0) {
                            return sort.direction === 'asc' ? comparison : -comparison;
                        }
                    }
                    return 0;
                });
            }

            this.state.filteredData = data;
            this.state.page = 1; // Reset to first page
        }

        /**
         * Render the table (pagination, info, etc.)
         */
        _render() {
            const tbody = this.table.querySelector('tbody');
            if (!tbody) return;

            const totalRows = this.state.filteredData.length;
            const totalPages = Math.ceil(totalRows / this.state.pageSize);
            const startIndex = (this.state.page - 1) * this.state.pageSize;
            const endIndex = Math.min(startIndex + this.state.pageSize, totalRows);

            // Hide ALL rows in tbody directly (more reliable than iterating originalData)
            const allRows = tbody.querySelectorAll('tr');
            allRows.forEach(row => {
                row.style.display = 'none';
            });

            // Reorder and show current page rows
            // We need to actually move the DOM elements to reflect the sort order
            for (let i = startIndex; i < endIndex; i++) {
                if (this.state.filteredData[i]) {
                    const row = this.state.filteredData[i]._element;
                    row.style.display = '';
                    // Append to tbody moves the row to the end, creating sorted order
                    tbody.appendChild(row);
                }
            }

            // Update info
            if (this.infoDisplay) {
                if (totalRows === 0) {
                    this.infoDisplay.innerHTML = this.config.noResultsMessage;
                } else {
                    this.infoDisplay.innerHTML = `Showing <span class="rsl-smart-table-info-count">${startIndex + 1}</span> to <span class="rsl-smart-table-info-count">${endIndex}</span> of <span class="rsl-smart-table-info-count">${totalRows}</span> entries`;
                }
            }

            // Update pagination
            if (this.paginationContainer) {
                this._renderPagination(totalPages);
            }

            // Highlight search matches
            if (this.state.globalSearch) {
                this._highlightMatches();
            } else {
                this._clearHighlights();
            }

            // Apply conditional formatting
            this._applyConditionalFormatting();

            // Render summary row
            if (this.config.summaryRow) {
                this._renderSummaryRow();
            }
        }

        /**
         * Render pagination controls
         */
        _renderPagination(totalPages) {
            this.paginationContainer.innerHTML = '';

            if (totalPages <= 1) return;

            // First button
            this._addPaginationButton('«', 1, this.state.page === 1, 'Go to first page');

            // Previous button
            this._addPaginationButton('‹', this.state.page - 1, this.state.page === 1, 'Go to previous page');

            // Page numbers
            const pageNumbers = this._getPageNumbers(totalPages);
            pageNumbers.forEach(pageNum => {
                if (pageNum === '...') {
                    const ellipsis = document.createElement('span');
                    ellipsis.className = 'rsl-smart-table-pagination-ellipsis';
                    ellipsis.textContent = '...';
                    this.paginationContainer.appendChild(ellipsis);
                } else {
                    this._addPaginationButton(pageNum, pageNum, false, `Go to page ${pageNum}`, pageNum === this.state.page);
                }
            });

            // Next button
            this._addPaginationButton('›', this.state.page + 1, this.state.page === totalPages, 'Go to next page');

            // Last button
            this._addPaginationButton('»', totalPages, this.state.page === totalPages, 'Go to last page');
        }

        /**
         * Add a pagination button
         */
        _addPaginationButton(text, page, disabled, ariaLabel, active = false) {
            const btn = document.createElement('button');
            btn.textContent = text;
            btn.disabled = disabled;
            btn.setAttribute('aria-label', ariaLabel);
            if (active) {
                btn.classList.add('active');
                btn.setAttribute('aria-current', 'page');
            }
            btn.addEventListener('click', () => this.goToPage(page));
            this.paginationContainer.appendChild(btn);
        }

        /**
         * Get page numbers to display
         */
        _getPageNumbers(totalPages) {
            const current = this.state.page;
            const pages = [];
            const delta = 2; // Pages to show around current

            if (totalPages <= 7) {
                for (let i = 1; i <= totalPages; i++) {
                    pages.push(i);
                }
            } else {
                // Always show first page
                pages.push(1);

                if (current > delta + 2) {
                    pages.push('...');
                }

                // Pages around current
                for (let i = Math.max(2, current - delta); i <= Math.min(totalPages - 1, current + delta); i++) {
                    pages.push(i);
                }

                if (current < totalPages - delta - 1) {
                    pages.push('...');
                }

                // Always show last page
                pages.push(totalPages);
            }

            return pages;
        }

        /**
         * Highlight search matches in cells
         */
        _highlightMatches() {
            const searchTerm = this.state.globalSearch.toLowerCase();

            this.state.filteredData.forEach(row => {
                if (row._element.style.display === 'none') return;

                Object.keys(row).forEach(key => {
                    if (key.startsWith('_') || !row[key]?.element) return;

                    const cell = row[key].element;
                    const originalHtml = row[key].display;
                    const textContent = cell.textContent.toLowerCase();

                    if (textContent.includes(searchTerm)) {
                        const regex = new RegExp(`(${this._escapeRegex(searchTerm)})`, 'gi');
                        cell.innerHTML = originalHtml.replace(regex, '<span class="rsl-highlight">$1</span>');
                    } else {
                        cell.innerHTML = originalHtml;
                    }
                });
            });
        }

        /**
         * Clear search highlights
         */
        _clearHighlights() {
            this.state.originalData.forEach(row => {
                Object.keys(row).forEach(key => {
                    if (key.startsWith('_') || !row[key]?.element) return;
                    row[key].element.innerHTML = row[key].display;
                });
            });
        }

        /**
         * Escape regex special characters
         */
        _escapeRegex(str) {
            return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        }

        /**
         * Parse date string into Date object
         * Supports ISO format (YYYY-MM-DD), US format (MM/DD/YYYY), and various others
         * @param {string} dateStr - Date string to parse
         * @returns {Date|null} - Parsed date or null if invalid
         */
        _parseDate(dateStr) {
            if (!dateStr) return null;

            // If already a Date object
            if (dateStr instanceof Date) {
                return isNaN(dateStr.getTime()) ? null : dateStr;
            }

            const str = String(dateStr).trim();

            // Try ISO format first (YYYY-MM-DD)
            if (/^\d{4}-\d{2}-\d{2}/.test(str)) {
                const date = new Date(str);
                if (!isNaN(date.getTime())) return date;
            }

            // Try US format (MM/DD/YYYY or M/D/YYYY)
            const usMatch = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/);
            if (usMatch) {
                const [, month, day, year] = usMatch;
                const date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
                if (!isNaN(date.getTime())) return date;
            }

            // Try European format (DD/MM/YYYY or DD.MM.YYYY)
            const euMatch = str.match(/^(\d{1,2})[\/.](\d{1,2})[\/.](\d{4})/);
            if (euMatch) {
                const [, day, month, year] = euMatch;
                const date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
                if (!isNaN(date.getTime())) return date;
            }

            // Fallback to native Date parsing
            const fallback = new Date(str);
            return isNaN(fallback.getTime()) ? null : fallback;
        }

        // ==========================================
        // Public API Methods
        // ==========================================

        /**
         * Global search
         */
        search(query) {
            this.state.globalSearch = query;
            this._applyFiltersAndSort();
            this._render();

            if (this.onFilterChange) {
                this.onFilterChange(this.getState());
            }

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:search', {
                detail: { query, state: this.getState() }
            }));
        }

        /**
         * Filter specific column
         */
        filterColumn(key, value) {
            if (value) {
                this.state.filters[key] = value;
            } else {
                delete this.state.filters[key];
            }

            this._applyFiltersAndSort();
            this._render();

            if (this.onFilterChange) {
                this.onFilterChange(this.getState());
            }

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:filter', {
                detail: { column: key, value, state: this.getState() }
            }));
        }

        /**
         * Clear all filters
         */
        clearFilters() {
            this.state.filters = {};
            this.state.globalSearch = '';

            if (this.searchInput) {
                this.searchInput.value = '';
                this.searchInput.parentElement.classList.remove('has-value');
            }

            // Clear column filter inputs
            this.table.querySelectorAll('.rsl-smart-table-filter input, .rsl-smart-table-filter select').forEach(el => {
                if (el.tagName === 'SELECT') {
                    el.selectedIndex = 0;
                } else {
                    el.value = '';
                }
            });

            this._applyFiltersAndSort();
            this._render();
        }

        /**
         * Sort by column
         */
        sort(column, direction = 'asc') {
            this.state.sort = [{ column, direction }];
            this._updateSortIndicators();
            this._applyFiltersAndSort();
            this._render();
        }

        /**
         * Clear sorting
         */
        clearSort() {
            this.state.sort = [];
            this._updateSortIndicators();
            this._applyFiltersAndSort();
            this._render();
        }

        /**
         * Go to specific page
         */
        goToPage(page) {
            const totalPages = Math.ceil(this.state.filteredData.length / this.state.pageSize);
            this.state.page = Math.max(1, Math.min(page, totalPages));
            this._render();

            if (this.onPageChange) {
                this.onPageChange(this.getState());
            }

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:page', {
                detail: { page: this.state.page, state: this.getState() }
            }));
        }

        /**
         * Go to next page
         */
        nextPage() {
            this.goToPage(this.state.page + 1);
        }

        /**
         * Go to previous page
         */
        prevPage() {
            this.goToPage(this.state.page - 1);
        }

        /**
         * Set page size
         */
        setPageSize(size) {
            this.state.pageSize = size;
            this.state.page = 1;
            this._render();
        }

        /**
         * Toggle column visibility
         */
        toggleColumn(key, visible) {
            const col = this.state.columns.find(c => c.key === key);
            if (!col) return;

            const colIndex = this.state.columns.indexOf(col);

            if (visible) {
                this.state.visibleColumns.add(key);
            } else {
                this.state.visibleColumns.delete(key);
            }

            // Toggle header
            col.element.style.display = visible ? '' : 'none';

            // Toggle cells
            this.table.querySelectorAll('tbody tr').forEach(row => {
                const cells = row.querySelectorAll('td');
                // Account for selection column offset
                const offset = this.config.selectable ? 1 : 0;
                if (cells[colIndex + offset]) {
                    cells[colIndex + offset].style.display = visible ? '' : 'none';
                }
            });

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:column-toggle', {
                detail: { column: key, visible }
            }));
        }

        /**
         * Select a row
         */
        selectRow(rowId) {
            this.state.selectedRows.add(rowId);
            this._updateRowSelection(rowId, true);
            this._updateSelectionUI();
        }

        /**
         * Deselect a row
         */
        deselectRow(rowId) {
            this.state.selectedRows.delete(rowId);
            this._updateRowSelection(rowId, false);
            this._updateSelectionUI();
        }

        /**
         * Select all visible rows
         */
        selectAll() {
            this.state.filteredData.forEach(row => {
                this.state.selectedRows.add(row._id);
                this._updateRowSelection(row._id, true);
            });
            this._updateSelectionUI();
        }

        /**
         * Clear selection
         */
        clearSelection() {
            this.state.selectedRows.forEach(id => {
                this._updateRowSelection(id, false);
            });
            this.state.selectedRows.clear();
            this._updateSelectionUI();
        }

        /**
         * Alias for clearSelection
         */
        deselectAll() {
            this.clearSelection();
        }

        /**
         * Update row selection UI
         */
        _updateRowSelection(rowId, selected) {
            const row = this.state.originalData.find(r => r._id === rowId);
            if (row && row._element) {
                row._element.classList.toggle('rsl-row-selected', selected);
                const checkbox = row._element.querySelector('.rsl-smart-table-checkbox');
                if (checkbox) checkbox.checked = selected;
            }
        }

        /**
         * Update selection UI (bar, checkboxes)
         */
        _updateSelectionUI() {
            const count = this.state.selectedRows.size;

            // Update selection bar
            if (this.selectionBar) {
                this.selectionBar.classList.toggle('visible', count > 0);
                this.selectionBar.querySelector('.selection-count').textContent = count;
            }

            // Update select-all checkbox
            const selectAll = this.table.querySelector('.rsl-smart-table-select-all');
            if (selectAll) {
                const totalVisible = this.state.filteredData.length;
                selectAll.checked = count > 0 && count === totalVisible;
                selectAll.indeterminate = count > 0 && count < totalVisible;
            }

            if (this.onSelectionChange) {
                this.onSelectionChange(this.getSelectedRows());
            }

            // Update bulk actions bar
            this._updateBulkActionsBar();

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:selection', {
                detail: { selected: this.getSelectedRows() }
            }));
        }

        /**
         * Get selected row data
         */
        getSelectedRows() {
            return this.state.originalData.filter(row =>
                this.state.selectedRows.has(row._id)
            );
        }

        /**
         * Export data
         */
        export(format = 'csv', scope = 'filtered') {
            let data;
            switch (scope) {
                case 'all':
                    data = this.state.originalData;
                    break;
                case 'selected':
                    data = this.getSelectedRows();
                    if (data.length === 0) {
                        alert('No rows selected. Please check some rows first.');
                        return;
                    }
                    break;
                case 'filtered':
                default:
                    data = this.state.filteredData;
                    break;
            }
            const visibleCols = this.state.columns.filter(c => this.state.visibleColumns.has(c.key));

            let output;
            let filename;
            let mimeType;

            switch (format) {
                case 'json':
                    output = this._exportJSON(data, visibleCols);
                    filename = 'export.json';
                    mimeType = 'application/json';
                    break;
                case 'excel':
                    output = this._exportExcel(data, visibleCols);
                    filename = 'export.xls';
                    mimeType = 'application/vnd.ms-excel';
                    break;
                case 'csv':
                default:
                    output = this._exportCSV(data, visibleCols);
                    filename = 'export.csv';
                    mimeType = 'text/csv';
                    break;
            }

            // Custom export handler
            if (this.onExport) {
                this.onExport({ format, data: output, filename, mimeType });
                return;
            }

            // Download file
            this._downloadFile(output, filename, mimeType);

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:export', {
                detail: { format, scope, rowCount: data.length }
            }));
        }

        /**
         * Export to CSV
         */
        _exportCSV(data, columns) {
            const headers = columns.map(c => `"${c.label}"`).join(',');
            const rows = data.map(row => {
                return columns.map(col => {
                    const val = row[col.key]?.value || '';
                    return `"${String(val).replace(/"/g, '""')}"`;
                }).join(',');
            });
            return [headers, ...rows].join('\n');
        }

        /**
         * Export to JSON
         */
        _exportJSON(data, columns) {
            const exported = data.map(row => {
                const obj = {};
                columns.forEach(col => {
                    obj[col.key] = row[col.key]?.value || '';
                });
                return obj;
            });
            return JSON.stringify(exported, null, 2);
        }

        /**
         * Export to Excel-compatible HTML
         */
        _exportExcel(data, columns) {
            const headers = columns.map(c => `<th>${c.label}</th>`).join('');
            const rows = data.map(row => {
                const cells = columns.map(col => {
                    const val = row[col.key]?.value || '';
                    return `<td>${val}</td>`;
                }).join('');
                return `<tr>${cells}</tr>`;
            }).join('');

            return `
                <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">
                <head><meta charset="UTF-8"></head>
                <body>
                    <table>
                        <thead><tr>${headers}</tr></thead>
                        <tbody>${rows}</tbody>
                    </table>
                </body>
                </html>
            `;
        }

        /**
         * Trigger file download
         */
        _downloadFile(content, filename, mimeType) {
            const blob = new Blob([content], { type: mimeType + ';charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = filename;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        }

        /**
         * Get current state
         */
        getState() {
            return {
                sort: [...this.state.sort],
                filters: { ...this.state.filters },
                globalSearch: this.state.globalSearch,
                page: this.state.page,
                pageSize: this.state.pageSize,
                totalRows: this.state.filteredData.length,
                totalPages: Math.ceil(this.state.filteredData.length / this.state.pageSize),
                selectedRows: Array.from(this.state.selectedRows)
            };
        }

        /**
         * Set data (for server mode)
         */
        setData(rows) {
            const tbody = this.table.querySelector('tbody');
            if (!tbody) return;

            tbody.innerHTML = '';

            rows.forEach((rowData, index) => {
                const tr = document.createElement('tr');
                tr.dataset.id = rowData.id || `row-${index}`;

                this.state.columns.forEach(col => {
                    const td = document.createElement('td');
                    td.dataset.col = col.key;
                    td.dataset.label = col.label;
                    td.innerHTML = rowData[col.key] || '';
                    tr.appendChild(td);
                });

                tbody.appendChild(tr);
            });

            // Re-capture data
            this._captureOriginalData();
            this._applyFiltersAndSort();
            this._render();
        }

        /**
         * Show loading state
         */
        showLoading() {
            this.tableWrapper.classList.add('rsl-smart-table-loading');

            if (!this.tableWrapper.querySelector('.rsl-smart-table-spinner')) {
                const spinner = document.createElement('div');
                spinner.className = 'rsl-smart-table-spinner';
                this.tableWrapper.appendChild(spinner);
            }
        }

        /**
         * Hide loading state
         */
        hideLoading() {
            this.tableWrapper.classList.remove('rsl-smart-table-loading');
            const spinner = this.tableWrapper.querySelector('.rsl-smart-table-spinner');
            if (spinner) spinner.remove();
        }

        /**
         * Refresh/re-render table
         */
        refresh() {
            this._applyFiltersAndSort();
            this._render();
        }

        // ==========================================
        // Quick Filter Methods
        // ==========================================

        /**
         * Apply a quick filter
         */
        _applyQuickFilter(filter, chipElement) {
            // Deactivate other chips
            const container = chipElement.parentElement;
            container.querySelectorAll('.rsl-smart-table-quick-filter').forEach(c => {
                c.classList.remove('active');
                c.setAttribute('aria-pressed', 'false');
            });

            // Activate this chip
            chipElement.classList.add('active');
            chipElement.setAttribute('aria-pressed', 'true');

            // Show clear button
            if (this.quickFilterClearBtn) {
                this.quickFilterClearBtn.style.display = '';
            }

            // Apply the filter
            if (filter.filter && typeof filter.filter === 'function') {
                // Custom filter function
                this.state.quickFilterFn = filter.filter;
            } else if (filter.column && filter.value !== undefined) {
                // Simple column/value filter
                this.state.quickFilterColumn = filter.column;
                this.state.quickFilterValue = filter.value;
            }

            this._applyFiltersAndSort();
            this._render();

            // Dispatch event
            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:quick-filter', {
                detail: { filter: filter }
            }));
        }

        /**
         * Clear all quick filters
         */
        _clearQuickFilters() {
            const container = this.toolbar.querySelector('.rsl-smart-table-quick-filters');
            if (container) {
                container.querySelectorAll('.rsl-smart-table-quick-filter').forEach(c => {
                    c.classList.remove('active');
                    c.setAttribute('aria-pressed', 'false');
                });
            }

            // Hide clear button
            if (this.quickFilterClearBtn) {
                this.quickFilterClearBtn.style.display = 'none';
            }

            // Clear filter state
            delete this.state.quickFilterFn;
            delete this.state.quickFilterColumn;
            delete this.state.quickFilterValue;

            this._applyFiltersAndSort();
            this._render();
        }

        // ==========================================
        // Copy to Clipboard
        // ==========================================

        /**
         * Copy table data to clipboard
         */
        copyToClipboard(scope = 'filtered') {
            let data;
            switch (scope) {
                case 'all':
                    data = this.state.originalData;
                    break;
                case 'selected':
                    data = this.getSelectedRows();
                    break;
                case 'filtered':
                default:
                    data = this.state.filteredData;
                    break;
            }

            if (data.length === 0) {
                this._showToast('No data to copy', 'warning');
                return;
            }

            const visibleCols = this.state.columns.filter(c => this.state.visibleColumns.has(c.key));

            // Build tab-separated text (Excel-friendly)
            const headers = visibleCols.map(c => c.label).join('\t');
            const rows = data.map(row => {
                return visibleCols.map(col => {
                    const val = row[col.key]?.value || '';
                    return String(val).replace(/\t/g, ' ').replace(/\n/g, ' ');
                }).join('\t');
            });

            const text = [headers, ...rows].join('\n');

            // Copy to clipboard
            navigator.clipboard.writeText(text).then(() => {
                this._showToast(`Copied ${data.length} rows to clipboard`, 'success');

                this.table.dispatchEvent(new CustomEvent('rsl-smart-table:copy', {
                    detail: { rowCount: data.length, scope: scope }
                }));
            }).catch(err => {
                console.error('Failed to copy:', err);
                this._showToast('Failed to copy to clipboard', 'error');
            });
        }

        /**
         * Show a toast notification
         */
        _showToast(message, type = 'info') {
            // Create toast element
            const toast = document.createElement('div');
            toast.className = `rsl-smart-table-toast rsl-toast-${type}`;
            toast.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}" aria-hidden="true"></i>
                <span>${message}</span>
            `;

            // Add to container
            this.container.appendChild(toast);

            // Animate in
            requestAnimationFrame(() => {
                toast.classList.add('show');
            });

            // Remove after delay
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => toast.remove(), 300);
            }, 2500);
        }

        // ==========================================
        // Conditional Formatting
        // ==========================================

        /**
         * Apply conditional formatting to cells
         */
        _applyConditionalFormatting() {
            if (!this.config.conditionalFormatting || this.config.conditionalFormatting.length === 0) {
                return;
            }

            this.config.conditionalFormatting.forEach(format => {
                const colIndex = this.state.columns.findIndex(c => c.key === format.column);
                if (colIndex === -1) return;

                // Get offset for selection column
                const offset = this.config.selectable ? 1 : 0;

                this.table.querySelectorAll('tbody tr').forEach(row => {
                    const cells = row.querySelectorAll('td');
                    const cell = cells[colIndex + offset];
                    if (!cell) return;

                    const rowData = this.state.originalData.find(r => r._element === row);
                    if (!rowData) return;

                    const value = rowData[format.column]?.value;

                    // Check each rule
                    format.rules.forEach(rule => {
                        let matches = false;

                        switch (rule.condition) {
                            case 'equals':
                                matches = value == rule.value;
                                break;
                            case 'not_equals':
                                matches = value != rule.value;
                                break;
                            case 'contains':
                                matches = String(value).toLowerCase().includes(String(rule.value).toLowerCase());
                                break;
                            case 'greater_than':
                                matches = parseFloat(value) > parseFloat(rule.value);
                                break;
                            case 'less_than':
                                matches = parseFloat(value) < parseFloat(rule.value);
                                break;
                            case 'between':
                                const num = parseFloat(value);
                                matches = num >= parseFloat(rule.min) && num <= parseFloat(rule.max);
                                break;
                            case 'empty':
                                matches = !value || value === '';
                                break;
                            case 'not_empty':
                                matches = value && value !== '';
                                break;
                        }

                        if (matches) {
                            // Apply class if specified
                            if (rule.class) {
                                cell.classList.add(rule.class);
                            }
                            // Apply inline styles if specified
                            if (rule.style) {
                                Object.assign(cell.style, rule.style);
                            }
                            // Apply badge/chip if specified
                            if (rule.badge) {
                                const badge = document.createElement('span');
                                badge.className = `rsl-cell-badge rsl-badge-${rule.badge}`;
                                badge.textContent = cell.textContent;
                                cell.textContent = '';
                                cell.appendChild(badge);
                            }
                            // Apply icon if specified
                            if (rule.icon) {
                                const icon = document.createElement('i');
                                icon.className = `fas ${rule.icon} rsl-cell-icon`;
                                if (rule.iconColor) {
                                    icon.style.color = rule.iconColor;
                                }
                                cell.insertBefore(icon, cell.firstChild);
                            }
                            // Apply progress bar if specified
                            if (rule.progressBar) {
                                const percent = Math.min(100, Math.max(0, parseFloat(value) || 0));
                                const bar = document.createElement('div');
                                bar.className = 'rsl-cell-progress';
                                bar.innerHTML = `
                                    <div class="rsl-progress-bar" style="width: ${percent}%; background: ${rule.progressColor || '#6E7BFF'}"></div>
                                    <span class="rsl-progress-text">${percent}%</span>
                                `;
                                cell.textContent = '';
                                cell.appendChild(bar);
                            }
                        }
                    });
                });
            });
        }

        // ==========================================
        // Inline Editing Methods
        // ==========================================

        /**
         * Setup inline editing functionality
         */
        _setupInlineEditing() {
            const tbody = this.table.querySelector('tbody');
            if (!tbody) return;

            tbody.addEventListener('dblclick', (e) => {
                const cell = e.target.closest('td');
                if (!cell || cell.classList.contains('rsl-select-col') ||
                    cell.classList.contains('rsl-actions-col') ||
                    cell.classList.contains('rsl-expand-col') ||
                    cell.classList.contains('rsl-editing')) {
                    return;
                }

                const row = cell.closest('tr');
                const rowData = this.state.originalData.find(r => r._element === row);
                if (!rowData) return;

                const cellIndex = Array.from(row.children).indexOf(cell);
                const colKey = this.state.columns[cellIndex]?.key;

                // Check if this column is editable
                if (this.config.editableColumns.length > 0 &&
                    !this.config.editableColumns.includes(colKey)) {
                    return;
                }

                this._makeEditable(cell, rowData, colKey);
            });

            // Mark table as having inline editing
            this.table.setAttribute('data-inline-editing', '');
        }

        /**
         * Convert cell to editable input
         */
        _makeEditable(cell, rowData, colKey) {
            const originalValue = rowData[colKey]?.value || cell.textContent;
            const originalDisplay = cell.innerHTML;

            cell.classList.add('rsl-editing');

            const input = document.createElement('input');
            input.type = 'text';
            input.className = 'rsl-inline-edit-input';
            input.value = originalValue;
            input.setAttribute('aria-label', `Edit ${colKey}`);

            // Replace cell content with input
            cell.innerHTML = '';
            cell.appendChild(input);
            input.focus();
            input.select();

            // Handle save on Enter, cancel on Escape
            input.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this._saveEdit(cell, input, rowData, colKey, originalDisplay);
                } else if (e.key === 'Escape') {
                    e.preventDefault();
                    this._cancelEdit(cell, originalDisplay);
                }
            });

            // Save on blur
            input.addEventListener('blur', () => {
                // Small delay to allow click events to fire first
                setTimeout(() => {
                    if (cell.classList.contains('rsl-editing')) {
                        this._saveEdit(cell, input, rowData, colKey, originalDisplay);
                    }
                }, 100);
            });
        }

        /**
         * Save the edited value
         */
        _saveEdit(cell, input, rowData, colKey, originalDisplay) {
            const newValue = input.value;
            const oldValue = rowData[colKey]?.value;

            cell.classList.remove('rsl-editing');

            // Update the data
            if (rowData[colKey]) {
                rowData[colKey].value = newValue;
                rowData[colKey].display = newValue;
            }

            // Update the cell display
            cell.textContent = newValue;

            // Dispatch change event with full row data for saving
            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:cell-edit', {
                bubbles: true,
                detail: {
                    row: rowData,
                    column: colKey,
                    oldValue: oldValue,
                    newValue: newValue,
                    rowIndex: rowData._index,
                    rowId: rowData._id,
                    tableData: this.getTableData()
                }
            }));
        }

        /**
         * Cancel the edit
         */
        _cancelEdit(cell, originalDisplay) {
            cell.classList.remove('rsl-editing');
            cell.innerHTML = originalDisplay;
        }

        /**
         * Get all table data as JSON (for page builder integration)
         * @returns {Object} Complete table state and data
         */
        getTableData() {
            return {
                columns: this.state.columns.map(col => ({
                    key: col.key,
                    label: col.label,
                    type: col.type,
                    sortable: col.sortable,
                    filterable: col.filterable
                })),
                rows: this.state.originalData.map(row => {
                    const rowObj = { _id: row._id };
                    this.state.columns.forEach(col => {
                        if (row[col.key]) {
                            rowObj[col.key] = row[col.key].value;
                        }
                    });
                    return rowObj;
                }),
                config: {
                    pageSize: this.config.pageSize,
                    striped: this.config.striped,
                    selectable: this.config.selectable,
                    exportable: this.config.exportable,
                    inlineEditing: this.config.inlineEditing,
                    summaryRow: this.config.summaryRow,
                    expandableRows: this.config.expandableRows
                },
                state: {
                    sort: this.state.sort,
                    filters: this.state.filters,
                    page: this.state.page,
                    selectedRows: Array.from(this.state.selectedRows)
                }
            };
        }

        /**
         * Load data into table (for page builder integration)
         * @param {Object} data - Data object with columns and rows
         */
        loadData(data) {
            if (!data || !data.rows) return;

            const tbody = this.table.querySelector('tbody');
            if (!tbody) return;

            // Clear existing rows
            tbody.innerHTML = '';
            this.state.originalData = [];

            // Create new rows
            data.rows.forEach((rowData, index) => {
                const tr = document.createElement('tr');
                tr.dataset.id = rowData._id || `row-${index}`;

                const internalRowData = {
                    _element: tr,
                    _index: index,
                    _id: tr.dataset.id
                };

                this.state.columns.forEach(col => {
                    const td = document.createElement('td');
                    td.setAttribute('data-label', col.label);
                    td.textContent = rowData[col.key] || '';
                    tr.appendChild(td);

                    internalRowData[col.key] = {
                        value: rowData[col.key] || '',
                        display: rowData[col.key] || '',
                        element: td
                    };
                });

                tbody.appendChild(tr);
                this.state.originalData.push(internalRowData);
            });

            // Re-apply filters and render
            this._applyFiltersAndSort();
            this._render();

            // Dispatch data loaded event
            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:data-loaded', {
                bubbles: true,
                detail: { rowCount: data.rows.length }
            }));
        }

        // ==========================================
        // Summary Row Methods
        // ==========================================

        /**
         * Render summary/totals row
         */
        _renderSummaryRow() {
            // Remove existing summary row
            const existingSummary = this.table.querySelector('.rsl-summary-row');
            if (existingSummary) {
                existingSummary.remove();
            }

            // If no summary columns configured, use numeric columns with sum
            let summaryConfig = this.config.summaryColumns;
            if (summaryConfig.length === 0) {
                summaryConfig = this.state.columns
                    .filter(col => col.type === 'number' || col.type === 'currency')
                    .map(col => ({ column: col.key, type: 'sum' }));
            }

            if (summaryConfig.length === 0) return;

            const tfoot = this.table.querySelector('tfoot') || document.createElement('tfoot');
            if (!this.table.querySelector('tfoot')) {
                this.table.appendChild(tfoot);
            }

            const summaryRow = document.createElement('tr');
            summaryRow.className = 'rsl-summary-row';

            // Create cells for each column
            this.state.columns.forEach((col, index) => {
                const td = document.createElement('td');
                td.className = 'rsl-summary-cell';

                const config = summaryConfig.find(s => s.column === col.key);
                if (config) {
                    const value = this._calculateSummary(col.key, config.type);
                    const label = config.label || config.type.toUpperCase();

                    if (col.type === 'currency') {
                        td.innerHTML = `<span class="rsl-summary-label">${label}:</span> <span class="rsl-summary-value">$${value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}</span>`;
                    } else {
                        td.innerHTML = `<span class="rsl-summary-label">${label}:</span> <span class="rsl-summary-value">${value.toLocaleString(undefined, {maximumFractionDigits: 2})}</span>`;
                    }
                } else if (index === 0) {
                    // First column shows "Summary" label
                    td.innerHTML = '<span class="rsl-summary-label">Summary</span>';
                }

                summaryRow.appendChild(td);
            });

            // Add empty cells for selection and actions columns
            if (this.config.selectable) {
                const emptyTd = document.createElement('td');
                emptyTd.className = 'rsl-summary-cell rsl-select-col';
                summaryRow.insertBefore(emptyTd, summaryRow.firstChild);
            }
            if (this.config.rowActions) {
                const emptyTd = document.createElement('td');
                emptyTd.className = 'rsl-summary-cell rsl-actions-col';
                summaryRow.appendChild(emptyTd);
            }
            if (this.config.expandableRows) {
                const emptyTd = document.createElement('td');
                emptyTd.className = 'rsl-summary-cell rsl-expand-col';
                summaryRow.insertBefore(emptyTd, summaryRow.firstChild);
            }

            tfoot.innerHTML = '';
            tfoot.appendChild(summaryRow);
        }

        /**
         * Calculate summary value for a column
         */
        _calculateSummary(colKey, type) {
            const values = this.state.filteredData
                .map(row => {
                    const val = row[colKey]?.value;
                    return parseFloat(val) || 0;
                })
                .filter(v => !isNaN(v));

            if (values.length === 0) return 0;

            switch (type) {
                case 'sum':
                    return values.reduce((a, b) => a + b, 0);
                case 'avg':
                case 'average':
                    return values.reduce((a, b) => a + b, 0) / values.length;
                case 'count':
                    return values.length;
                case 'min':
                    return Math.min(...values);
                case 'max':
                    return Math.max(...values);
                default:
                    return values.reduce((a, b) => a + b, 0);
            }
        }

        // ==========================================
        // Row Expansion Methods
        // ==========================================

        /**
         * Add expand/collapse column to table
         */
        _addExpandColumn() {
            const thead = this.table.querySelector('thead tr:not(.rsl-smart-table-filter-row)');
            const tbody = this.table.querySelector('tbody');

            if (!thead || !tbody) return;

            // Add header cell
            const th = document.createElement('th');
            th.className = 'rsl-expand-col';
            th.innerHTML = '<span class="sr-only">Expand</span>';
            th.style.width = '40px';
            thead.insertBefore(th, thead.firstChild);

            // Add expand button to each row
            tbody.querySelectorAll('tr').forEach((row, index) => {
                const td = document.createElement('td');
                td.className = 'rsl-expand-col';

                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'rsl-expand-btn';
                btn.setAttribute('aria-expanded', 'false');
                btn.setAttribute('aria-label', 'Expand row');
                btn.innerHTML = '<i class="fas fa-chevron-right" aria-hidden="true"></i>';

                btn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const rowData = this.state.originalData.find(r => r._element === row);
                    this._toggleRowExpansion(row, rowData, btn);
                });

                td.appendChild(btn);
                row.insertBefore(td, row.firstChild);
            });

            // Add empty cell to filter row if it exists
            const filterRow = this.table.querySelector('thead tr.rsl-smart-table-filter-row');
            if (filterRow) {
                const filterTh = document.createElement('th');
                filterTh.className = 'rsl-expand-col';
                filterRow.insertBefore(filterTh, filterRow.firstChild);
            }
        }

        /**
         * Toggle row expansion
         */
        _toggleRowExpansion(row, rowData, btn) {
            const isExpanded = row.classList.contains('rsl-row-expanded');
            const existingPanel = row.nextElementSibling;

            if (isExpanded && existingPanel?.classList.contains('rsl-expanded-row')) {
                // Collapse
                row.classList.remove('rsl-row-expanded');
                btn.setAttribute('aria-expanded', 'false');
                btn.innerHTML = '<i class="fas fa-chevron-right" aria-hidden="true"></i>';
                existingPanel.remove();

                this.table.dispatchEvent(new CustomEvent('rsl-smart-table:row-collapse', {
                    bubbles: true,
                    detail: { row: rowData, element: row }
                }));
            } else {
                // Expand
                row.classList.add('rsl-row-expanded');
                btn.setAttribute('aria-expanded', 'true');
                btn.innerHTML = '<i class="fas fa-chevron-down" aria-hidden="true"></i>';

                const expandedRow = this._renderExpandedContent(rowData, row);
                row.parentNode.insertBefore(expandedRow, row.nextSibling);

                this.table.dispatchEvent(new CustomEvent('rsl-smart-table:row-expand', {
                    bubbles: true,
                    detail: { row: rowData, element: row, panel: expandedRow }
                }));
            }
        }

        /**
         * Render expanded row content
         */
        _renderExpandedContent(rowData, parentRow) {
            const tr = document.createElement('tr');
            tr.className = 'rsl-expanded-row';

            const td = document.createElement('td');
            const colSpan = parentRow.children.length;
            td.setAttribute('colspan', colSpan);
            td.className = 'rsl-expanded-content';

            // Use custom template if provided
            if (this.config.expandTemplate && typeof this.config.expandTemplate === 'function') {
                td.innerHTML = this.config.expandTemplate(rowData);
            } else {
                // Default expanded content - show all columns in detail view
                const columnsToShow = this.config.expandableColumns.length > 0
                    ? this.state.columns.filter(c => this.config.expandableColumns.includes(c.key))
                    : this.state.columns;

                let html = '<div class="rsl-expanded-details">';
                html += '<div class="rsl-expanded-grid">';

                columnsToShow.forEach(col => {
                    const value = rowData[col.key]?.display || rowData[col.key]?.value || '-';
                    html += `
                        <div class="rsl-expanded-item">
                            <span class="rsl-expanded-label">${col.label}</span>
                            <span class="rsl-expanded-value">${value}</span>
                        </div>
                    `;
                });

                html += '</div></div>';
                td.innerHTML = html;
            }

            tr.appendChild(td);
            return tr;
        }

        // ==========================================
        // Column Resizing Methods
        // ==========================================

        /**
         * Setup column resizing
         */
        _setupColumnResizing() {
            // Only target main header row, not filter row
            const headerRow = this.table.querySelector('thead tr:not(.rsl-smart-table-filter-row)');
            if (!headerRow) return;

            const headers = headerRow.querySelectorAll('th:not(.rsl-select-col):not(.rsl-actions-col):not(.rsl-expand-col)');

            headers.forEach((th, index) => {
                // Skip if already has resize handle
                if (th.querySelector('.rsl-column-resize-handle')) return;

                // Create resize handle
                const resizeHandle = document.createElement('div');
                resizeHandle.className = 'rsl-column-resize-handle';
                resizeHandle.setAttribute('role', 'separator');
                resizeHandle.setAttribute('aria-orientation', 'vertical');
                resizeHandle.setAttribute('aria-label', 'Resize column');
                resizeHandle.setAttribute('tabindex', '0');
                resizeHandle.setAttribute('title', 'Drag to resize column');
                th.appendChild(resizeHandle);
                th.classList.add('rsl-resizable');

                // Set initial width if not set
                if (!th.style.width) {
                    th.style.width = th.offsetWidth + 'px';
                }

                let startX, startWidth;

                const onMouseDown = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    startX = e.pageX;
                    startWidth = th.offsetWidth;
                    this.state.isResizing = true;
                    this.table.classList.add('rsl-resizing');
                    resizeHandle.classList.add('rsl-resizing-active');

                    document.addEventListener('mousemove', onMouseMove);
                    document.addEventListener('mouseup', onMouseUp);
                };

                const onMouseMove = (e) => {
                    if (!this.state.isResizing) return;
                    const diff = e.pageX - startX;
                    const newWidth = Math.max(this.config.minColumnWidth, startWidth + diff);
                    th.style.width = newWidth + 'px';
                    this.state.columnWidths[this.state.columns[index]?.key] = newWidth;

                    // Dispatch resize event
                    this.table.dispatchEvent(new CustomEvent('rsl-smart-table:column-resize', {
                        bubbles: true,
                        detail: { column: index, width: newWidth }
                    }));
                };

                const onMouseUp = () => {
                    this.state.isResizing = false;
                    this.table.classList.remove('rsl-resizing');
                    resizeHandle.classList.remove('rsl-resizing-active');
                    document.removeEventListener('mousemove', onMouseMove);
                    document.removeEventListener('mouseup', onMouseUp);
                };

                resizeHandle.addEventListener('mousedown', onMouseDown);

                // Keyboard support for resizing
                resizeHandle.addEventListener('keydown', (e) => {
                    const step = e.shiftKey ? 20 : 5;
                    if (e.key === 'ArrowLeft') {
                        e.preventDefault();
                        const newWidth = Math.max(this.config.minColumnWidth, th.offsetWidth - step);
                        th.style.width = newWidth + 'px';
                        this.state.columnWidths[this.state.columns[index]?.key] = newWidth;
                    } else if (e.key === 'ArrowRight') {
                        e.preventDefault();
                        const newWidth = th.offsetWidth + step;
                        th.style.width = newWidth + 'px';
                        this.state.columnWidths[this.state.columns[index]?.key] = newWidth;
                    }
                });
            });
        }

        /**
         * Get column widths
         */
        getColumnWidths() {
            return { ...this.state.columnWidths };
        }

        /**
         * Set column widths
         */
        setColumnWidths(widths) {
            const headers = this.table.querySelectorAll('thead th');
            this.state.columns.forEach((col, index) => {
                if (widths[col.key]) {
                    headers[index].style.width = widths[col.key] + 'px';
                    this.state.columnWidths[col.key] = widths[col.key];
                }
            });
        }

        // ==========================================
        // Column Reordering Methods
        // ==========================================

        /**
         * Setup column reordering via drag & drop
         * Simple, reliable implementation without fancy animations
         */
        _setupColumnReordering() {
            const self = this;
            const thead = this.table.querySelector('thead');

            // Initialize column order
            this.state.columnOrder = this.state.columns.map(col => col.key);

            // Shared drag state (not on instance to avoid stale closures)
            let dragSourceTh = null;

            // Get the header row fresh each time
            const getHeaderRow = () => thead.querySelector('tr:not(.rsl-smart-table-filter-row)');

            // Get draggable headers fresh each time
            const getHeaders = () => {
                const headerRow = getHeaderRow();
                return headerRow ? Array.from(headerRow.querySelectorAll('th:not(.rsl-select-col):not(.rsl-actions-col):not(.rsl-expand-col)')) : [];
            };

            // Get current index of a header
            const indexOf = (th) => getHeaders().indexOf(th);

            // Clear all visual states
            const clearVisualStates = () => {
                getHeaders().forEach(h => {
                    h.classList.remove('rsl-dragging', 'rsl-drag-over-left', 'rsl-drag-over-right');
                });
            };

            // Attach drag events to a header cell
            const attachDragEvents = (th) => {
                if (th.dataset.reorderSetup) return; // Already setup
                th.dataset.reorderSetup = 'true';

                th.setAttribute('draggable', 'true');
                th.classList.add('rsl-reorderable');

                th.addEventListener('dragstart', (e) => {
                    if (self.state.isResizing) {
                        e.preventDefault();
                        return;
                    }
                    dragSourceTh = th;
                    th.classList.add('rsl-dragging');
                    e.dataTransfer.effectAllowed = 'move';
                    e.dataTransfer.setData('text/plain', '');
                });

                th.addEventListener('dragover', (e) => {
                    if (!dragSourceTh || dragSourceTh === th) return;
                    e.preventDefault();

                    // Clear previous highlights
                    getHeaders().forEach(h => h.classList.remove('rsl-drag-over-left', 'rsl-drag-over-right'));

                    // Show drop indicator on left or right side
                    const rect = th.getBoundingClientRect();
                    if (e.clientX < rect.left + rect.width / 2) {
                        th.classList.add('rsl-drag-over-left');
                    } else {
                        th.classList.add('rsl-drag-over-right');
                    }
                });

                th.addEventListener('dragleave', () => {
                    th.classList.remove('rsl-drag-over-left', 'rsl-drag-over-right');
                });

                th.addEventListener('drop', (e) => {
                    e.preventDefault();
                    e.stopPropagation();

                    if (!dragSourceTh || dragSourceTh === th) {
                        clearVisualStates();
                        dragSourceTh = null;
                        return;
                    }

                    const fromIdx = indexOf(dragSourceTh);
                    const toIdx = indexOf(th);

                    // Determine drop position based on mouse
                    const rect = th.getBoundingClientRect();
                    const dropOnRightSide = e.clientX >= rect.left + rect.width / 2;

                    clearVisualStates();
                    dragSourceTh = null;

                    // Calculate target index
                    let targetIdx;
                    if (dropOnRightSide) {
                        targetIdx = fromIdx < toIdx ? toIdx : toIdx + 1;
                    } else {
                        targetIdx = fromIdx < toIdx ? toIdx - 1 : toIdx;
                    }

                    if (fromIdx !== targetIdx && targetIdx >= 0 && targetIdx < getHeaders().length) {
                        self._reorderColumns(fromIdx, targetIdx);
                    }
                });

                th.addEventListener('dragend', () => {
                    clearVisualStates();
                    dragSourceTh = null;
                });
            };

            // Setup all current headers
            getHeaders().forEach(attachDragEvents);

            // Store function for re-initialization after DOM changes
            this._reinitColumnReordering = () => {
                getHeaders().forEach(attachDragEvents);
            };
        }

        /**
         * Reorder columns
         */
        _reorderColumns(fromIndex, toIndex) {
            const thead = this.table.querySelector('thead');
            const tbody = this.table.querySelector('tbody');

            // Adjust indices for special columns
            let offset = 0;
            if (this.config.selectable) offset++;
            if (this.config.expandableRows) offset++;

            const adjustedFrom = fromIndex + offset;
            const adjustedTo = toIndex + offset;

            // Reorder header row
            const headerRow = thead.querySelector('tr:not(.rsl-smart-table-filter-row)');
            const headerCells = Array.from(headerRow.children);
            const movedHeader = headerCells.splice(adjustedFrom, 1)[0];
            headerCells.splice(adjustedTo, 0, movedHeader);

            // Clear and re-append
            while (headerRow.firstChild) {
                headerRow.removeChild(headerRow.firstChild);
            }
            headerCells.forEach(cell => headerRow.appendChild(cell));

            // Reorder filter row if exists
            const filterRow = thead.querySelector('.rsl-smart-table-filter-row');
            if (filterRow) {
                const filterCells = Array.from(filterRow.children);
                const movedFilter = filterCells.splice(adjustedFrom, 1)[0];
                filterCells.splice(adjustedTo, 0, movedFilter);
                while (filterRow.firstChild) {
                    filterRow.removeChild(filterRow.firstChild);
                }
                filterCells.forEach(cell => filterRow.appendChild(cell));
            }

            // Reorder body rows
            const bodyRows = tbody.querySelectorAll('tr:not(.rsl-expanded-row)');
            bodyRows.forEach((row) => {
                const cells = Array.from(row.children);
                if (cells.length <= adjustedFrom) return;
                const movedCell = cells.splice(adjustedFrom, 1)[0];
                cells.splice(adjustedTo, 0, movedCell);
                while (row.firstChild) {
                    row.removeChild(row.firstChild);
                }
                cells.forEach(cell => row.appendChild(cell));
            });

            // Update column order state
            const movedCol = this.state.columnOrder.splice(fromIndex, 1)[0];
            this.state.columnOrder.splice(toIndex, 0, movedCol);

            // Update columns array
            const movedColConfig = this.state.columns.splice(fromIndex, 1)[0];
            this.state.columns.splice(toIndex, 0, movedColConfig);

            // Re-setup column resizing handles if needed
            if (this.config.columnResizing) {
                this.table.querySelectorAll('.rsl-column-resize-handle').forEach(h => h.remove());
                this._setupColumnResizing();
            }

            // Dispatch event
            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:column-reorder', {
                bubbles: true,
                detail: { fromIndex, toIndex, columnOrder: [...this.state.columnOrder] }
            }));
        }

        /**
         * Get column order
         */
        getColumnOrder() {
            return [...this.state.columnOrder];
        }

        /**
         * Set column order
         */
        setColumnOrder(order) {
            const currentOrder = [...this.state.columnOrder];
            order.forEach((colKey, newIndex) => {
                const currentIndex = currentOrder.indexOf(colKey);
                if (currentIndex !== -1 && currentIndex !== newIndex) {
                    this._reorderColumns(currentIndex, newIndex);
                    currentOrder.splice(currentIndex, 1);
                    currentOrder.splice(newIndex, 0, colKey);
                }
            });
        }

        // ==========================================
        // Frozen/Pinned Columns Methods
        // ==========================================

        /**
         * Setup frozen columns
         */
        _setupFrozenColumns() {
            const leftCols = this.config.frozenColumns.left || [];
            const rightCols = this.config.frozenColumns.right || [];

            this.table.classList.add('rsl-has-frozen-columns');
            this.tableWrapper.classList.add('rsl-frozen-wrapper');

            // Calculate left positions for frozen left columns
            let leftOffset = 0;
            leftCols.forEach(colKey => {
                const colIndex = this.state.columns.findIndex(c => c.key === colKey);
                if (colIndex === -1) return;

                // Add offset for special columns
                let adjustedIndex = colIndex;
                if (this.config.selectable) adjustedIndex++;
                if (this.config.expandableRows) adjustedIndex++;

                this._freezeColumn(adjustedIndex, 'left', leftOffset);

                const th = this.table.querySelector(`thead th:nth-child(${adjustedIndex + 1})`);
                if (th) leftOffset += th.offsetWidth;
            });

            // Calculate right positions for frozen right columns
            let rightOffset = 0;
            const reversedRightCols = [...rightCols].reverse();
            reversedRightCols.forEach(colKey => {
                const colIndex = this.state.columns.findIndex(c => c.key === colKey);
                if (colIndex === -1) return;

                let adjustedIndex = colIndex;
                if (this.config.selectable) adjustedIndex++;
                if (this.config.expandableRows) adjustedIndex++;

                this._freezeColumn(adjustedIndex, 'right', rightOffset);

                const th = this.table.querySelector(`thead th:nth-child(${adjustedIndex + 1})`);
                if (th) rightOffset += th.offsetWidth;
            });

            // Set CSS variable for scroll shadow
            this.tableWrapper.style.setProperty('--frozen-left-width', leftOffset + 'px');
            this.tableWrapper.style.setProperty('--frozen-right-width', rightOffset + 'px');
        }

        /**
         * Freeze a single column
         */
        _freezeColumn(colIndex, side, offset) {
            const nth = colIndex + 1;
            const header = this.table.querySelector(`thead th:nth-child(${nth})`);
            const filterCell = this.table.querySelector(`thead .rsl-smart-table-filter-row th:nth-child(${nth})`);
            const cells = this.table.querySelectorAll(`tbody td:nth-child(${nth})`);

            const freezeElement = (el) => {
                el.classList.add('rsl-frozen-column', `rsl-frozen-${side}`);
                el.style.position = 'sticky';
                el.style[side] = offset + 'px';
                el.style.zIndex = side === 'left' ? '2' : '1';
            };

            if (header) freezeElement(header);
            if (filterCell) freezeElement(filterCell);
            cells.forEach(cell => freezeElement(cell));
        }

        /**
         * Pin a column
         */
        pinColumn(colKey, side = 'left') {
            if (side === 'left') {
                if (!this.config.frozenColumns.left.includes(colKey)) {
                    this.config.frozenColumns.left.push(colKey);
                }
            } else {
                if (!this.config.frozenColumns.right.includes(colKey)) {
                    this.config.frozenColumns.right.push(colKey);
                }
            }
            this._clearFrozenColumns();
            this._setupFrozenColumns();
        }

        /**
         * Unpin a column
         */
        unpinColumn(colKey) {
            this.config.frozenColumns.left = this.config.frozenColumns.left.filter(k => k !== colKey);
            this.config.frozenColumns.right = this.config.frozenColumns.right.filter(k => k !== colKey);
            this._clearFrozenColumns();
            if (this.config.frozenColumns.left.length > 0 || this.config.frozenColumns.right.length > 0) {
                this._setupFrozenColumns();
            }
        }

        /**
         * Clear frozen column styles
         */
        _clearFrozenColumns() {
            this.table.querySelectorAll('.rsl-frozen-column').forEach(el => {
                el.classList.remove('rsl-frozen-column', 'rsl-frozen-left', 'rsl-frozen-right');
                el.style.position = '';
                el.style.left = '';
                el.style.right = '';
                el.style.zIndex = '';
            });
        }

        // ==========================================
        // Bulk Actions Bar Methods
        // ==========================================

        /**
         * Build bulk actions bar
         */
        _buildBulkActionsBar() {
            this.bulkActionsBar = document.createElement('div');
            this.bulkActionsBar.className = 'rsl-bulk-actions-bar';
            this.bulkActionsBar.setAttribute('role', 'toolbar');
            this.bulkActionsBar.setAttribute('aria-label', 'Bulk actions');
            this.bulkActionsBar.style.display = 'none';

            // Selection count
            const countSpan = document.createElement('span');
            countSpan.className = 'rsl-bulk-selection-count';
            countSpan.innerHTML = '<strong>0</strong> items selected';
            this.bulkActionsBar.appendChild(countSpan);
            this.bulkSelectionCount = countSpan.querySelector('strong');

            // Actions container
            const actionsContainer = document.createElement('div');
            actionsContainer.className = 'rsl-bulk-actions-buttons';

            // Build action buttons based on config
            this.config.bulkActionItems.forEach(action => {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'rsl-bulk-action-btn';
                btn.dataset.action = action;

                switch(action) {
                    case 'delete':
                        btn.innerHTML = '<i class="fas fa-trash" aria-hidden="true"></i> Delete Selected';
                        btn.classList.add('rsl-bulk-action-danger');
                        btn.addEventListener('click', () => this._bulkDelete());
                        break;
                    case 'export':
                        btn.innerHTML = '<i class="fas fa-download" aria-hidden="true"></i> Export Selected';
                        btn.addEventListener('click', () => this._bulkExport());
                        break;
                    case 'status':
                        btn.innerHTML = '<i class="fas fa-exchange-alt" aria-hidden="true"></i> Change Status';
                        if (this.config.bulkStatusOptions.length > 0) {
                            const dropdown = this._createBulkStatusDropdown();
                            btn.appendChild(dropdown);
                        }
                        btn.addEventListener('click', (e) => {
                            if (e.target === btn || e.target.tagName === 'I') {
                                const dropdown = btn.querySelector('.rsl-bulk-status-dropdown');
                                if (dropdown) {
                                    dropdown.style.display = dropdown.style.display === 'none' ? 'block' : 'none';
                                }
                            }
                        });
                        break;
                    default:
                        btn.innerHTML = action.charAt(0).toUpperCase() + action.slice(1);
                        btn.addEventListener('click', () => {
                            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:bulk-action', {
                                bubbles: true,
                                detail: { action, selectedRows: this.getSelectedRows() }
                            }));
                        });
                }

                actionsContainer.appendChild(btn);
            });

            // Clear selection button
            const clearBtn = document.createElement('button');
            clearBtn.type = 'button';
            clearBtn.className = 'rsl-bulk-action-btn rsl-bulk-clear';
            clearBtn.innerHTML = '<i class="fas fa-times" aria-hidden="true"></i> Clear Selection';
            clearBtn.addEventListener('click', () => this.deselectAll());
            actionsContainer.appendChild(clearBtn);

            this.bulkActionsBar.appendChild(actionsContainer);
            this.container.insertBefore(this.bulkActionsBar, this.tableWrapper);
        }

        /**
         * Create bulk status change dropdown
         */
        _createBulkStatusDropdown() {
            const dropdown = document.createElement('div');
            dropdown.className = 'rsl-bulk-status-dropdown';
            dropdown.style.display = 'none';

            this.config.bulkStatusOptions.forEach(status => {
                const option = document.createElement('button');
                option.type = 'button';
                option.className = 'rsl-bulk-status-option';
                option.textContent = status;
                option.addEventListener('click', (e) => {
                    e.stopPropagation();
                    this._bulkChangeStatus(status);
                    dropdown.style.display = 'none';
                });
                dropdown.appendChild(option);
            });

            return dropdown;
        }

        /**
         * Update bulk actions bar visibility
         */
        _updateBulkActionsBar() {
            if (!this.bulkActionsBar) return;

            const count = this.state.selectedRows.size;
            if (count > 0) {
                this.bulkActionsBar.style.display = 'flex';
                this.bulkSelectionCount.textContent = count;
            } else {
                this.bulkActionsBar.style.display = 'none';
            }
        }

        /**
         * Bulk delete selected rows
         */
        _bulkDelete() {
            const selectedRows = this.getSelectedRows();

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:bulk-delete', {
                bubbles: true,
                detail: { rows: selectedRows, count: selectedRows.length }
            }));

            // Remove rows from DOM
            selectedRows.forEach(rowData => {
                const element = rowData._element;
                if (element) {
                    element.remove();
                }
            });

            // Update data
            this.state.originalData = this.state.originalData.filter(
                row => !this.state.selectedRows.has(row._id)
            );
            this.state.filteredData = this.state.filteredData.filter(
                row => !this.state.selectedRows.has(row._id)
            );

            this.deselectAll();
            this._render();
        }

        /**
         * Bulk export selected rows
         */
        _bulkExport() {
            const selectedRows = this.getSelectedRows();
            const format = this.config.exportFormats[0] || 'csv';

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:bulk-export', {
                bubbles: true,
                detail: { rows: selectedRows, format }
            }));

            // Use existing export functionality with selected data
            this._exportData(format, selectedRows);
        }

        /**
         * Bulk change status
         */
        _bulkChangeStatus(newStatus) {
            const selectedRows = this.getSelectedRows();

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:bulk-status-change', {
                bubbles: true,
                detail: { rows: selectedRows, newStatus }
            }));
        }

        // ==========================================
        // Saved Views Methods
        // ==========================================

        /**
         * Setup saved views
         */
        _setupSavedViews() {
            // Generate storage key if not provided
            if (!this.config.viewStorageKey) {
                this.config.viewStorageKey = `rsl-smart-table-views-${this.table.id || this._generateId()}`;
            }

            // Load views from localStorage
            this._loadSavedViews();

            // Add saved views dropdown to toolbar
            this._addSavedViewsUI();
        }

        /**
         * Generate unique ID
         */
        _generateId() {
            return 'st-' + Math.random().toString(36).substr(2, 9);
        }

        /**
         * Add saved views UI to toolbar
         */
        _addSavedViewsUI() {
            const toolbarRight = this.toolbar?.querySelector('.rsl-smart-table-toolbar-right');
            if (!toolbarRight) return;

            const viewsContainer = document.createElement('div');
            viewsContainer.className = 'rsl-saved-views-container';

            // Save view button
            const saveBtn = document.createElement('button');
            saveBtn.type = 'button';
            saveBtn.className = 'rsl-smart-table-btn';
            saveBtn.innerHTML = '<i class="fas fa-save" aria-hidden="true"></i> Save View';
            saveBtn.addEventListener('click', () => this._showSaveViewDialog());

            // Load view dropdown
            const loadBtn = this._createDropdownButton(
                '<i class="fas fa-bookmark" aria-hidden="true"></i> Views',
                this._getViewsDropdownContent(),
                'Load saved view'
            );
            loadBtn.classList.add('rsl-views-dropdown-btn');

            // Store reference to refresh dropdown content later
            this.viewsDropdownBtn = loadBtn;

            viewsContainer.appendChild(saveBtn);
            viewsContainer.appendChild(loadBtn);
            toolbarRight.insertBefore(viewsContainer, toolbarRight.firstChild);
        }

        /**
         * Get views dropdown content
         */
        _getViewsDropdownContent() {
            const container = document.createElement('div');
            container.className = 'rsl-saved-views-list';

            const views = Object.keys(this.state.savedViews);

            if (views.length === 0) {
                const empty = document.createElement('div');
                empty.className = 'rsl-saved-views-empty';
                empty.textContent = 'No saved views';
                container.appendChild(empty);
            } else {
                views.forEach(viewName => {
                    const viewItem = document.createElement('div');
                    viewItem.className = 'rsl-saved-view-item';

                    const nameSpan = document.createElement('span');
                    nameSpan.textContent = viewName;
                    nameSpan.addEventListener('click', () => this.loadView(viewName));

                    const deleteBtn = document.createElement('button');
                    deleteBtn.type = 'button';
                    deleteBtn.className = 'rsl-saved-view-delete';
                    deleteBtn.innerHTML = '<i class="fas fa-trash" aria-hidden="true"></i>';
                    deleteBtn.setAttribute('aria-label', `Delete view: ${viewName}`);
                    deleteBtn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.deleteView(viewName);
                    });

                    viewItem.appendChild(nameSpan);
                    viewItem.appendChild(deleteBtn);
                    container.appendChild(viewItem);
                });
            }

            // Reset to default option
            const resetItem = document.createElement('div');
            resetItem.className = 'rsl-saved-view-item rsl-saved-view-reset';
            resetItem.innerHTML = '<i class="fas fa-undo" aria-hidden="true"></i> Reset to Default';
            resetItem.addEventListener('click', () => this.resetView());
            container.appendChild(resetItem);

            return container;
        }

        /**
         * Refresh views dropdown content after save/delete
         */
        _refreshViewsDropdown() {
            if (!this.viewsDropdownBtn) return;

            const dropdown = this.viewsDropdownBtn.querySelector('.rsl-smart-table-dropdown');
            if (dropdown) {
                // Clear existing content
                dropdown.innerHTML = '';
                // Add fresh content
                dropdown.appendChild(this._getViewsDropdownContent());
            }
        }

        /**
         * Show save view dialog
         */
        _showSaveViewDialog() {
            const viewName = prompt('Enter a name for this view:');
            if (viewName && viewName.trim()) {
                this.saveView(viewName.trim());
            }
        }

        /**
         * Save current view configuration
         */
        saveView(name) {
            const viewConfig = {
                sort: [...this.state.sort],
                filters: { ...this.state.filters },
                globalSearch: this.state.globalSearch,
                pageSize: this.state.pageSize,
                visibleColumns: Array.from(this.state.visibleColumns),
                columnWidths: { ...this.state.columnWidths },
                columnOrder: [...this.state.columnOrder],
                frozenColumns: { ...this.config.frozenColumns }
            };

            this.state.savedViews[name] = viewConfig;
            this._persistViews();
            this._refreshViewsDropdown();

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:view-saved', {
                bubbles: true,
                detail: { name, config: viewConfig }
            }));
        }

        /**
         * Load a saved view
         */
        loadView(name) {
            const viewConfig = this.state.savedViews[name];
            if (!viewConfig) return;

            // Apply sort
            this.state.sort = viewConfig.sort || [];

            // Apply filters
            this.state.filters = viewConfig.filters || {};

            // Apply global search
            this.state.globalSearch = viewConfig.globalSearch || '';
            if (this.searchInput) {
                this.searchInput.value = this.state.globalSearch;
            }

            // Apply page size
            this.state.pageSize = viewConfig.pageSize || this.config.pageSize;

            // Apply column visibility
            if (viewConfig.visibleColumns) {
                this.state.visibleColumns = new Set(viewConfig.visibleColumns);
                this._applyColumnVisibility();
            }

            // Apply column widths
            if (viewConfig.columnWidths) {
                this.setColumnWidths(viewConfig.columnWidths);
            }

            // Apply column order
            if (viewConfig.columnOrder && viewConfig.columnOrder.length > 0) {
                this.setColumnOrder(viewConfig.columnOrder);
            }

            // Apply frozen columns
            if (viewConfig.frozenColumns) {
                this.config.frozenColumns = viewConfig.frozenColumns;
                this._clearFrozenColumns();
                if (this.config.frozenColumns.left.length > 0 || this.config.frozenColumns.right.length > 0) {
                    this._setupFrozenColumns();
                }
            }

            this._applyFiltersAndSort();
            this._render();

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:view-loaded', {
                bubbles: true,
                detail: { name, config: viewConfig }
            }));
        }

        /**
         * Delete a saved view
         */
        deleteView(name) {
            delete this.state.savedViews[name];
            this._persistViews();
            this._refreshViewsDropdown();

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:view-deleted', {
                bubbles: true,
                detail: { name }
            }));
        }

        /**
         * Reset to default view
         */
        resetView() {
            this.state.sort = [];
            this.state.filters = {};
            this.state.globalSearch = '';
            this.state.pageSize = this.config.pageSize;
            this.state.visibleColumns = new Set(this.state.columns.map(c => c.key));

            if (this.searchInput) {
                this.searchInput.value = '';
            }

            // Reset column widths
            this.state.columnWidths = {};
            this.table.querySelectorAll('thead th').forEach(th => {
                th.style.width = '';
            });

            this._applyColumnVisibility();
            this._applyFiltersAndSort();
            this._render();

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:view-reset', {
                bubbles: true
            }));
        }

        /**
         * Get all saved views
         */
        getSavedViews() {
            return { ...this.state.savedViews };
        }

        /**
         * Load saved views from localStorage
         */
        _loadSavedViews() {
            try {
                const stored = localStorage.getItem(this.config.viewStorageKey);
                if (stored) {
                    this.state.savedViews = JSON.parse(stored);
                }
            } catch (e) {
                console.warn('Failed to load saved views:', e);
            }
        }

        /**
         * Persist views to localStorage
         */
        _persistViews() {
            try {
                localStorage.setItem(this.config.viewStorageKey, JSON.stringify(this.state.savedViews));
            } catch (e) {
                console.warn('Failed to save views:', e);
            }
        }

        /**
         * Apply column visibility
         */
        _applyColumnVisibility() {
            this.state.columns.forEach((col, index) => {
                const isVisible = this.state.visibleColumns.has(col.key);
                let adjustedIndex = index;
                if (this.config.selectable) adjustedIndex++;
                if (this.config.expandableRows) adjustedIndex++;

                const nth = adjustedIndex + 1;
                const header = this.table.querySelector(`thead th:nth-child(${nth})`);
                const cells = this.table.querySelectorAll(`tbody td:nth-child(${nth})`);

                if (header) {
                    header.style.display = isVisible ? '' : 'none';
                }
                cells.forEach(cell => {
                    cell.style.display = isVisible ? '' : 'none';
                });
            });
        }

        // ==========================================
        // Full Page Mode Methods
        // ==========================================

        /**
         * Setup full page mode
         */
        _setupFullPageMode() {
            // Add full page button to toolbar
            const toolbarRight = this.toolbar?.querySelector('.rsl-smart-table-toolbar-right');
            if (!toolbarRight) return;

            this.fullPageBtn = document.createElement('button');
            this.fullPageBtn.type = 'button';
            this.fullPageBtn.className = 'rsl-smart-table-btn rsl-full-page-btn';
            this.fullPageBtn.innerHTML = '<i class="fas fa-expand" aria-hidden="true"></i>';
            this.fullPageBtn.setAttribute('aria-label', 'Toggle full page mode');
            this.fullPageBtn.addEventListener('click', () => this.toggleFullPage());

            toolbarRight.appendChild(this.fullPageBtn);

            // Handle escape key to exit full page
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && this.state.isFullPage) {
                    this.toggleFullPage();
                }
            });
        }

        /**
         * Toggle full page mode
         */
        toggleFullPage() {
            this.state.isFullPage = !this.state.isFullPage;

            if (this.state.isFullPage) {
                // Store original styles
                this._originalBodyStyle = {
                    overflow: document.body.style.overflow
                };

                // Apply full page mode
                this.container.classList.add('rsl-full-page-mode');
                this.container.style.position = 'fixed';
                this.container.style.top = this.config.fullPagePadding + 'px';
                this.container.style.left = this.config.fullPagePadding + 'px';
                this.container.style.right = this.config.fullPagePadding + 'px';
                this.container.style.bottom = this.config.fullPagePadding + 'px';
                this.container.style.zIndex = '10500';
                this.container.style.background = 'var(--rsl-smart-table-bg, #ffffff)';

                document.body.style.overflow = 'hidden';

                this.fullPageBtn.innerHTML = '<i class="fas fa-compress" aria-hidden="true"></i>';
                this.fullPageBtn.setAttribute('aria-label', 'Exit full page mode');

                // Adjust table wrapper height
                this._adjustFullPageHeight();
                window.addEventListener('resize', this._fullPageResizeHandler = () => this._adjustFullPageHeight());
            } else {
                // Restore original styles
                this.container.classList.remove('rsl-full-page-mode');
                this.container.style.position = '';
                this.container.style.top = '';
                this.container.style.left = '';
                this.container.style.right = '';
                this.container.style.bottom = '';
                this.container.style.zIndex = '';
                this.container.style.background = '';

                document.body.style.overflow = this._originalBodyStyle?.overflow || '';

                this.fullPageBtn.innerHTML = '<i class="fas fa-expand" aria-hidden="true"></i>';
                this.fullPageBtn.setAttribute('aria-label', 'Toggle full page mode');

                this.tableWrapper.style.maxHeight = '';

                if (this._fullPageResizeHandler) {
                    window.removeEventListener('resize', this._fullPageResizeHandler);
                }
            }

            this.table.dispatchEvent(new CustomEvent('rsl-smart-table:fullpage-toggle', {
                bubbles: true,
                detail: { isFullPage: this.state.isFullPage }
            }));
        }

        /**
         * Adjust table wrapper height in full page mode
         */
        _adjustFullPageHeight() {
            if (!this.state.isFullPage) return;

            const containerHeight = this.container.offsetHeight;
            const toolbarHeight = this.toolbar ? this.toolbar.offsetHeight : 0;
            const footerHeight = this.footer ? this.footer.offsetHeight : 0;
            const bulkBarHeight = this.bulkActionsBar && this.bulkActionsBar.style.display !== 'none'
                ? this.bulkActionsBar.offsetHeight : 0;

            const availableHeight = containerHeight - toolbarHeight - footerHeight - bulkBarHeight - 20;
            this.tableWrapper.style.maxHeight = availableHeight + 'px';
            this.tableWrapper.style.overflow = 'auto';
        }

        /**
         * Check if in full page mode
         */
        isFullPage() {
            return this.state.isFullPage;
        }

        /**
         * Destroy instance
         */
        destroy() {
            // Unsubscribe from FilterBus
            if (this._filterBusId && window.RSL?.FilterBus?.unsubscribe) {
                window.RSL.FilterBus.unsubscribe(this._filterBusId);
            }

            // Remove container wrapper
            if (this.container && this.container.parentNode) {
                this.container.parentNode.insertBefore(this.table, this.container);
                this.container.remove();
            }

            // Remove added classes
            this.table.classList.remove('rsl-smart-table');
            this.table.removeAttribute('data-striped');
            this.table.removeAttribute('data-responsive');

            // Remove from instances
            instances.delete(this.table);
        }
    }

    // ==========================================
    // Public API
    // ==========================================

    window.RSL.SmartTable = {
        /**
         * Track instances
         */
        instances: instances,

        /**
         * Initialize all Smart Tables or specific element
         * @param {HTMLElement} [element] - Optional specific element
         * @param {Object} [options] - Configuration options
         */
        init: function(element, options) {
            if (element instanceof HTMLElement) {
                return this.create(element, options);
            }

            // Auto-init all tables with data-rsl-smart-table
            document.querySelectorAll('[data-rsl-smart-table]').forEach(table => {
                if (!instances.has(table)) {
                    new SmartTable(table);
                }
            });
        },

        /**
         * Create a Smart Table instance
         * @param {HTMLElement} element - Table element
         * @param {Object} [options] - Configuration options
         * @returns {SmartTable} Instance
         */
        create: function(element, options = {}) {
            if (instances.has(element)) {
                return instances.get(element);
            }
            return new SmartTable(element, options);
        },

        /**
         * Get instance for element
         * @param {HTMLElement} element - Table element
         * @returns {SmartTable|undefined}
         */
        getInstance: function(element) {
            return instances.get(element);
        },

        /**
         * Destroy instance
         * @param {HTMLElement} element - Table element
         */
        destroy: function(element) {
            const instance = instances.get(element);
            if (instance) {
                instance.destroy();
            }
        },

        /**
         * Get default configuration
         * @returns {Object}
         */
        getDefaults: function() {
            return { ...DEFAULT_CONFIG };
        }
    };

    // Auto-initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            window.RSL.SmartTable.init();
        });
    } else {
        window.RSL.SmartTable.init();
    }

})();
