/**
 * UltraGuard Pro - Components Module
 * Version: 1.2.0
 */

(function($) {
    'use strict';

    // Check if jQuery is available
    if (typeof $ === 'undefined') {
        console.error('UltraGuard Components: jQuery not found or $ is not available');
        return;
    }

    window.UltraGuardComponents = window.UltraGuardComponents || {};

    // ==================== Tabs Component ====================
    window.UltraGuardComponents.initializeTabs = function(instance) {
        if (!$ || !$('.ultraguard-tabs').length) return;
        
        $('.ultraguard-tabs').each((index, element) => {
            const $tabs = $(element);
            const activeTab = $tabs.find('.ultraguard-tab-nav-item.ultraguard-tab-active').first();
            
            if (activeTab.length) {
                const tabId = activeTab.find('.ultraguard-tab-nav-link').data('tab');
                // tabId may be 0 (integer) — use explicit null check, NOT if(tabId)
                if (tabId !== null && tabId !== undefined && tabId !== '') {
                    window.UltraGuardComponents.showTab(instance, $tabs, tabId);
                }
            } else {
                const firstTab = $tabs.find('.ultraguard-tab-nav-item:first');
                if (firstTab.length) {
                    const tabId = firstTab.find('.ultraguard-tab-nav-link').data('tab');
                    if (tabId !== null && tabId !== undefined && tabId !== '') {
                        window.UltraGuardComponents.showTab(instance, $tabs, tabId);
                    }
                }
            }
        });
    };

    window.UltraGuardComponents.showTab = function(instance, $tabs, tabId) {
        // NOTE: tabId can legitimately be 0 (integer) when PHP uses indexed arrays
        // for tab keys. Use explicit null check — never !tabId — to avoid treating
        // 0 as "no tab", which would make the first tab permanently unclickable.
        if (!$tabs || !$tabs.length || tabId === null || tabId === undefined || tabId === '') return;

        $tabs.find('.ultraguard-tab-nav-item').removeClass('ultraguard-tab-active');
        $tabs.find('.ultraguard-tab-nav-link[data-tab]').filter(function() {
            return $(this).data('tab') == tabId; // use == for loose match (string vs number)
        }).closest('.ultraguard-tab-nav-item').addClass('ultraguard-tab-active');

        $tabs.find('.ultraguard-tab-pane').removeClass('ultraguard-tab-active');

        // Safe jQuery selector: escape special characters in ID
        let $tabContent;
        try {
            // First try by ID attribute (most common case)
            $tabContent = $tabs.find('[id="' + tabId + '"]');
            if (!$tabContent.length) {
                // Fallback: search globally (for legacy layouts where pane is outside the tabs wrapper)
                $tabContent = $('[id="' + tabId + '"]');
            }
        } catch(e) {
            console.warn('UltraGuard: Invalid tab ID selector:', tabId, e);
            $tabContent = $();
        }

        if ($tabContent.length) {
            $tabContent.addClass('ultraguard-tab-active');
            $tabs.trigger('ultraguard:tab:changed', [tabId]);
            window.UltraGuardComponents.initializeTabComponents(instance, $tabContent);
        } else {
            console.warn('UltraGuard: Tab content not found for tab ID:', tabId);
            $tabs.trigger('ultraguard:tab:changed', [tabId]);
        }
    };

    window.UltraGuardComponents.initializeTabComponents = function(instance, $tab) {
        if (!$tab || !$tab.length) return;
        
        // Check if methods exist before calling
        if (window.UltraGuardComponents.initializeCharts) {
            window.UltraGuardComponents.initializeCharts(instance, $tab);
        }
        
        if (window.UltraGuardComponents.initializeDataTables) {
            window.UltraGuardComponents.initializeDataTables(instance, $tab);
        }
        
        if (window.UltraGuardComponents.initializeProgressBars) {
            window.UltraGuardComponents.initializeProgressBars($tab);
        }
    };

    window.UltraGuardComponents.handleTabClick = function(instance, e) {
        e.preventDefault();
        
        const $link = $(e.currentTarget);
        if (!$link || !$link.length) return;
        
        const $tabs = $link.closest('.ultraguard-tabs');
        const tabId = $link.data('tab');
        
        // tabId can be 0 (integer) — do NOT use !tabId falsy check here
        if (tabId === null || tabId === undefined || tabId === '') {
            console.warn('UltraGuard: Tab click missing data-tab attribute');
            return;
        }
        
        window.UltraGuardComponents.showTab(instance, $tabs, tabId);
    };

    // ==================== Accordion Component ====================
    window.UltraGuardComponents.initializeAccordions = function() {
        $('.ultraguard-accordion-panel').each((index, element) => {
            const $panel = $(element);
            const isActive = $panel.hasClass('active');
            
            if (isActive) {
                $panel.find('.ultraguard-accordion-content').show();
            } else {
                $panel.find('.ultraguard-accordion-content').hide();
            }
        });
    };

    window.UltraGuardComponents.handleAccordionClick = function(e) {
        e.preventDefault();
        
        const $header = $(e.currentTarget);
        if (!$header || !$header.length) return;
        
        const $panel = $header.closest('.ultraguard-accordion-panel');
        const $content = $panel.find('.ultraguard-accordion-content');
        
        if ($panel.hasClass('active')) {
            $content.slideUp(300, () => {
                $panel.removeClass('active');
            });
        } else {
            $content.slideDown(300, () => {
                $panel.addClass('active');
            });
        }
    };

    // ==================== Slider Component ====================
    window.UltraGuardComponents.initializeSliders = function() {
        $('.ultraguard-slider').each((index, element) => {
            const $slider = $(element);
            const $value = $slider.siblings('.ultraguard-slider-value');
            
            if ($value.length) {
                $value.text($slider.val());
            }
        });
    };

    window.UltraGuardComponents.handleSliderInput = function(e) {
        const $slider = $(e.currentTarget);
        if (!$slider || !$slider.length) return;
        
        const $value = $slider.siblings('.ultraguard-slider-value');
        const value = $slider.val();
        
        if ($value.length) {
            $value.text(value);
        }
        
        $slider.trigger('ultraguard:slider:changed', [value]);
    };

    // ==================== Toggle Component ====================
    window.UltraGuardComponents.handleToggleChange = function(e) {
        const $toggle = $(e.currentTarget);
        if (!$toggle || !$toggle.length) return;
        
        const $container = $toggle.closest('.ultraguard-toggle');
        const isChecked = $toggle.is(':checked');
        
        $container.toggleClass('active', isChecked);
        $toggle.trigger('ultraguard:toggle:changed', [isChecked]);
    };

    // ==================== Color Picker Component ====================
    window.UltraGuardComponents.initializeColorPickers = function() {
        if (typeof wp !== 'undefined' && wp.wpColorPicker && $.fn && $.fn.wpColorPicker) {
            $('.ultraguard-color-field').each(function() {
                const $this = $(this);
                if (!$this.data('wp-color-picker-initialized')) {
                    try {
                        $this.wpColorPicker({
                            change: function(event, ui) {
                                $(this).trigger('ultraguard:color:changed', [ui.color.toString()]);
                            }
                        }).data('wp-color-picker-initialized', true);
                    } catch (error) {
                        console.warn('Color picker initialization error:', error);
                    }
                }
            });
        }
    };

    // ==================== Icon Selector Component ====================
    window.UltraGuardComponents.handleIconSelect = function(e) {
        e.preventDefault();
        
        const $item = $(e.currentTarget);
        if (!$item || !$item.length) return;
        
        const $selector = $item.closest('.ultraguard-icon-selector');
        const $input = $selector.find('input[type="hidden"]');
        const icon = $item.data('icon');
        
        if (!icon) {
            console.warn('Icon item missing data-icon attribute');
            return;
        }
        
        $selector.find('.ultraguard-icon-item').removeClass('ultraguard-icon-selected');
        $item.addClass('ultraguard-icon-selected');
        $input.val(icon).trigger('change');
        
        $selector.trigger('ultraguard:icon:selected', [icon]);
    };

    // ==================== Upload Component ====================
    window.UltraGuardComponents.handleUploadClick = function(e, instance) {
        e.preventDefault();
        
        const $button = $(e.currentTarget);
        if (!$button || !$button.length || !instance) return;
        
        const $uploader = $button.closest('.ultraguard-uploader');
        const $input = $uploader.find('input[type="hidden"]');
        const multiple = $button.data('multiple') === true || $button.data('multiple') === 'true';
        const fileTypes = $button.data('file-types') || '*';
        
        if (typeof wp === 'undefined' || !wp.media) {
            if (instance.showMessage) {
                instance.showMessage('WordPress media library not available', 'error');
            } else {
                alert('WordPress media library not available');
            }
            return;
        }
        
        try {
            const frame = wp.media({
                title: 'Select File',
                multiple: multiple,
                library: {
                    type: fileTypes === '*' ? '' : fileTypes.split(',')
                },
                button: {
                    text: 'Select'
                }
            });
            
            frame.on('select', () => {
                const attachments = frame.state().get('selection').toJSON();
                window.UltraGuardComponents.handleUploadSelection(attachments, $uploader, $input, instance);
            });
            
            frame.open();
        } catch (error) {
            console.error('Media frame error:', error);
            if (instance.showMessage) {
                instance.showMessage('Error opening media library', 'error');
            }
        }
    };

    window.UltraGuardComponents.handleUploadSelection = function(attachments, $uploader, $input, instance) {
        if (!attachments || attachments.length === 0) return;
        
        const attachment = attachments[0];
        $input.val(attachment.id).trigger('change');
        
        const $preview = $uploader.find('.ultraguard-upload-preview');
        let previewHtml = '';
        
        if (attachment.type === 'image') {
            previewHtml = `<img src="${attachment.url}" alt="${attachment.alt || ''}" style="max-width: 100%; max-height: 150px;">`;
        } else {
            previewHtml = `
                <div class="ultraguard-file-info">
                    <span class="dashicons dashicons-media-document"></span>
                    <span>${attachment.filename || 'File'}</span>
                </div>
            `;
        }
        
        $preview.html(previewHtml);
        $uploader.find('.ultraguard-remove-button').show();
        
        $uploader.trigger('ultraguard:upload:selected', [attachment]);
    };

    window.UltraGuardComponents.handleRemoveClick = function(e) {
        e.preventDefault();
        
        const $button = $(e.currentTarget);
        if (!$button || !$button.length) return;
        
        const $uploader = $button.closest('.ultraguard-uploader');
        const $input = $uploader.find('input[type="hidden"]');
        const $preview = $uploader.find('.ultraguard-upload-preview');
        
        $input.val('').trigger('change');
        $preview.empty();
        $button.hide();
        
        $uploader.trigger('ultraguard:upload:removed');
    };

    // ==================== Repeater Component ====================
    window.UltraGuardComponents.initializeRepeaters = function(instance) {
        $('.ultraguard-repeater').each((index, element) => {
            window.UltraGuardComponents.updateRepeaterState($(element));
        });
    };

    window.UltraGuardComponents.handleRepeaterAdd = function(e, instance) {
        e.preventDefault();
        
        const $button = $(e.currentTarget);
        if (!$button || !$button.length || !instance) return;
        
        const $repeater = $button.closest('.ultraguard-repeater');
        const $template = $repeater.find('.ultraguard-repeater-template');
        const $rows = $repeater.find('.ultraguard-repeater-rows');
        
        if (!$template.length) {
            console.error('Repeater template not found');
            return;
        }
        
        const newRow = $template.html();
        const $newRow = $(newRow);
        
        $rows.append($newRow);
        window.UltraGuardComponents.updateRepeaterState($repeater);
        
        window.UltraGuardComponents.initializeRowComponents(instance, $newRow);
        
        $repeater.trigger('ultraguard:repeater:row:added', [$newRow]);
    };

    window.UltraGuardComponents.handleRepeaterRemove = function(e) {
        e.preventDefault();
        
        const $button = $(e.currentTarget);
        if (!$button || !$button.length) return;
        
        const $row = $button.closest('.ultraguard-repeater-row');
        const $repeater = $button.closest('.ultraguard-repeater');
        
        $row.remove();
        window.UltraGuardComponents.updateRepeaterState($repeater);
        
        $repeater.trigger('ultraguard:repeater:row:removed');
    };

    window.UltraGuardComponents.updateRepeaterState = function($repeater) {
        if (!$repeater || !$repeater.length) return;
        
        const $rows = $repeater.find('.ultraguard-repeater-row');
        const minRows = parseInt($repeater.data('min-rows') || 0);
        const maxRows = parseInt($repeater.data('max-rows') || 999);
        
        $rows.find('.ultraguard-repeater-remove').toggle($rows.length > minRows);
        $repeater.find('.ultraguard-repeater-add').toggle($rows.length < maxRows);
        
        $rows.each((index, row) => {
            const $row = $(row);
            const newIndex = index;
            
            $row.find('[name]').each((fieldIndex, field) => {
                const $field = $(field);
                const name = $field.attr('name');
                if (!name) return;
                
                const newName = name.replace(/\[\d+\]/, `[${newIndex}]`);
                $field.attr('name', newName);
                
                const id = $field.attr('id');
                if (id) {
                    const newId = id.replace(/_\d+$/, `_${newIndex}`);
                    $field.attr('id', newId);
                    
                    const $label = $(`label[for="${id}"]`);
                    if ($label.length) {
                        $label.attr('for', newId);
                    }
                }
            });
        });
    };

    window.UltraGuardComponents.initializeRowComponents = function(instance, $row) {
        if (!$row || !$row.length) return;
        
        if (window.UltraGuardComponents.initializeColorPickers) {
            window.UltraGuardComponents.initializeColorPickers();
        }
        
        if (window.UltraGuardComponents.initializeSliders) {
            window.UltraGuardComponents.initializeSliders();
        }
        
        if (window.UltraGuardComponents.initializeAccordions) {
            window.UltraGuardComponents.initializeAccordions();
        }
    };

    // ==================== Chart Component ====================
    window.UltraGuardComponents.initializeCharts = function(instance, container = document) {
        if (!window.Chart) {
            console.warn('Chart.js library not loaded');
            return;
        }
        
        const $container = $(container);
        $container.find('.ultraguard-chart-container canvas').each((index, element) => {
            const $canvas = $(element);
            const chartId = $canvas.attr('id');
            const configData = $canvas.data('config');
            
            if (!configData) {
                console.warn(`Chart configuration missing for: ${chartId}`);
                return;
            }
            
            try {
                const existingChart = Chart.getChart(element);
                if (existingChart) {
                    existingChart.destroy();
                }
                
                // Check if instance and its method exist
                let config = configData;
                if (instance && typeof instance.validateAndParseJSON === 'function') {
                    config = instance.validateAndParseJSON(configData);
                } else {
                    // Fallback parsing
                    try {
                        config = JSON.parse(configData);
                    } catch (e) {
                        config = null;
                    }
                }
                
                if (!config) {
                    console.error('Invalid chart configuration for:', chartId);
                    return;
                }
                
                new Chart(element, config);
                if (instance && instance.components) {
                    instance.components.set(`chart_${chartId}`, element);
                }
            } catch (error) {
                console.error('Chart initialization error for', chartId, ':', error);
            }
        });
    };

    window.UltraGuardComponents.initializeLazyLoadComponents = function(instance) {
        if (window.UltraGuardComponents.initializeHeavyCharts) {
            window.UltraGuardComponents.initializeHeavyCharts(instance);
        }
    };

    window.UltraGuardComponents.initializeHeavyCharts = function(instance) {
        $('.ultraguard-chart-lazy').each((index, element) => {
            const $chart = $(element);
            if (window.UltraGuardComponents.isInViewport($chart[0])) {
                window.UltraGuardComponents.initializeCharts(instance, $chart);
            }
        });
    };

    window.UltraGuardComponents.isInViewport = function(element) {
        if (!element) return false;
        
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    };

    // ==================== Data Table Component ====================
    window.UltraGuardComponents.initializeDataTables = function(instance, container = document) {
        const $container = $(container);
        $container.find('.ultraguard-data-table').each((index, element) => {
            const $table = $(element);
            const tableId = $table.attr('id');

            // Sortable column headers
            $table.find('.ultraguard-sortable').on('click', (e) => {
                window.UltraGuardComponents.handleTableSort(e, $table);
            });

            // Live search: filter rows as user types in the adjacent search input
            const $wrapper = $table.closest('.ultraguard-table-wrapper');
            const $searchInput = $wrapper.find('.ultraguard-search-input');
            if ($searchInput.length) {
                window.UltraGuardComponents.bindLiveSearch($searchInput, $table);
            }

            if (instance && instance.components) {
                instance.components.set(`table_${tableId}`, element);
            }
        });
    };

    // Live search: filters visible rows on keyup — no form submit needed for client-side data
    window.UltraGuardComponents.bindLiveSearch = function($input, $table) {
        let debounceTimer = null;
        $input.on('input keyup', function() {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(function() {
                const query = $input.val().trim().toLowerCase();
                const $rows = $table.find('tbody tr');
                let visibleCount = 0;

                $rows.each(function() {
                    const rowText = $(this).text().toLowerCase();
                    const isMatch = !query || rowText.includes(query);
                    $(this).toggle(isMatch);
                    if (isMatch) visibleCount++;
                });

                // Show/hide empty-state row
                const $empty = $table.find('.ultraguard-table-empty').closest('tr');
                if ($empty.length) {
                    $empty.toggle(visibleCount === 0 && query.length > 0);
                }
            }, 200);
        });

        // Clear button also clears the live filter
        const $wrapper = $input.closest('.ultraguard-table-wrapper, .ultraguard-table-search').parent();
        $wrapper.on('click', '.ultraguard-search-clear', function(e) {
            // If we have client-side data (rows in tbody), prevent navigation and just clear
            if ($table.find('tbody tr:not(.ultraguard-empty-row)').length > 0) {
                e.preventDefault();
                $input.val('').trigger('input');
            }
        });
    };

    window.UltraGuardComponents.handleTableSort = function(e, $table) {
        const $header = $(e.currentTarget);
        if (!$header || !$header.length) return;
        
        const columnIndex = $header.index();
        const isAscending = !$header.hasClass('ultraguard-sort-asc');
        
        $table.find('.ultraguard-sortable').removeClass('ultraguard-sort-asc ultraguard-sort-desc');
        $header.addClass(isAscending ? 'ultraguard-sort-asc' : 'ultraguard-sort-desc');
        
        const $rows = $table.find('tbody tr').get();
        
        $rows.sort((a, b) => {
            const aValue = $(a).find('td').eq(columnIndex).text().trim();
            const bValue = $(b).find('td').eq(columnIndex).text().trim();
            
            let comparison = 0;
            if (aValue > bValue) {
                comparison = 1;
            } else if (aValue < bValue) {
                comparison = -1;
            }
            
            return isAscending ? comparison : -comparison;
        });
        
        const $tbody = $table.find('tbody');
        $.each($rows, (index, row) => {
            $tbody.append(row);
        });
    };

    // ==================== Progress Bar Component ====================
    window.UltraGuardComponents.initializeProgressBars = function(container = document) {
        const $container = $(container);
        $container.find('.ultraguard-security-suitegress-bar').each((index, element) => {
            const $bar = $(element);
            const percentage = parseFloat($bar.data('percentage')) || 
                              parseFloat($bar.css('width')) || 
                              parseFloat($bar.attr('style')?.match(/width:\s*([\d.]+)%/)?.[1]) || 0;

            $bar.css('width', `${percentage}%`);
            
            const $value = $bar.closest('.ultraguard-security-suitegress-container').find('.ultraguard-security-suitegress-value');
            if ($value.length && !$value.text().trim()) {
                $value.text(`${percentage}%`);
            }
        });
    };

    // ==================== Code Editor Component ====================
    window.UltraGuardComponents.initializeCodeEditors = function() {
        if (typeof wp === 'undefined' || !wp.codeEditor || !$.fn || !$.fn.codeEditor) {
            return;
        }
        
        $('.ultraguard-code-editor').each((index, element) => {
            const $editor = $(element);
            if (!$editor.data('code-editor-initialized')) {
                try {
                    const language = $editor.data('language') || 'html';
                    const theme = $editor.data('theme') || 'default';
                    
                    const editorInstance = wp.codeEditor.initialize(element, {
                        codemirror: {
                            mode: language,
                            theme: theme,
                            lineNumbers: true,
                            indentUnit: 2,
                            tabSize: 2,
                            indentWithTabs: false
                        }
                    });
                    if (editorInstance) {
                        $editor.data('code-editor-instance', editorInstance);
                    }
                    $editor.data('code-editor-initialized', true);
                } catch (error) {
                    console.warn('Code editor initialization error:', error);
                }
            }
        });
    };

    $(document).on('ultraguard:field:updated', '.ultraguard-code-editor', function(event, fieldName, value) {
        const $editor = $(this);
        const editorInstance = $editor.data('code-editor-instance');
        const nextValue = value !== null && value !== undefined ? String(value) : '';

        if (editorInstance && editorInstance.codemirror && typeof editorInstance.codemirror.setValue === 'function') {
            if (editorInstance.codemirror.getValue() !== nextValue) {
                editorInstance.codemirror.setValue(nextValue);
            }
        }

        if ($editor.val() !== nextValue) {
            $editor.val(nextValue);
        }
    });

    // ==================== Widget Component ====================
    window.UltraGuardComponents.initializeWidgets = function(instance) {
        if (!instance) return;
        
        $('.ultraguard-widget').each((index, element) => {
            const $widget = $(element);
            const refreshInterval = $widget.data('refresh-interval');
            
            if (refreshInterval && refreshInterval > 0) {
                window.UltraGuardComponents.setupWidgetAutoRefresh(instance, $widget, refreshInterval);
            }
        });
    };

    window.UltraGuardComponents.setupWidgetAutoRefresh = function(instance, $widget, interval) {
        if (!instance || !$widget || !$widget.length) return;
        
        setInterval(() => {
            if (instance.refreshWidget && typeof instance.refreshWidget === 'function') {
                instance.refreshWidget($widget);
            }
        }, interval * 1000);
    };

    window.UltraGuardComponents.handleWidgetRefresh = function(e, instance) {
        e.preventDefault();
        
        const $button = $(e.currentTarget);
        if (!$button || !$button.length || !instance) return;
        
        const $widget = $button.closest('.ultraguard-widget');
        
        if (instance.refreshWidget && typeof instance.refreshWidget === 'function') {
            instance.refreshWidget($widget);
        }
    };

    // ==================== Toast/Message Component ====================
    window.UltraGuardComponents.showMessage = function(instance, message, type = 'info', duration = 5000) {
        if (!message) return;
        
        const messageId = 'ug-message-' + Date.now();
        const messageHtml = `
            <div id="${messageId}" class="ultraguard-toast-message ultraguard-toast-${type}">
                <div class="ultraguard-toast-icon-wrapper">
                    <span class="ultraguard-toast-icon dashicons ${window.UltraGuardComponents.getToastIcon(type)}"></span>
                </div>
                <div class="ultraguard-toast-content">
                    <div class="ultraguard-toast-title">${window.UltraGuardComponents.getToastTitle(type)}</div>
                    <div class="ultraguard-toast-text">${instance.escapeHtml ? instance.escapeHtml(message) : message}</div>
                </div>
                <button type="button" class="ultraguard-toast-close" aria-label="Dismiss">
                    <span class="dashicons dashicons-no"></span>
                </button>
            </div>
        `;

        let $toastContainer = $('.ultraguard-toast-container');
        if (!$toastContainer.length) {
            $toastContainer = $('<div class="ultraguard-toast-container"></div>');
            $('body').append($toastContainer);
        }

        $toastContainer.append(messageHtml);
        const $toast = $(`#${messageId}`);

        setTimeout(() => {
            $toast.addClass('ultraguard-toast-show');
        }, 10);

        if (duration > 0) {
            setTimeout(() => {
                window.UltraGuardComponents.dismissToast($toast);
            }, duration);
        }

        $toast.find('.ultraguard-toast-close').on('click', () => {
            window.UltraGuardComponents.dismissToast($toast);
        });

        return messageId;
    };

    window.UltraGuardComponents.dismissToast = function($toast) {
        if (!$toast || !$toast.length) return;
        
        $toast.removeClass('ultraguard-toast-show');
        setTimeout(() => {
            $toast.remove();
        }, 300);
    };

    window.UltraGuardComponents.getToastIcon = function(type) {
        const icons = {
            'success': 'dashicons-yes-alt',
            'error': 'dashicons-dismiss',
            'warning': 'dashicons-warning',
            'info': 'dashicons-info'
        };
        return icons[type] || icons.info;
    };

    window.UltraGuardComponents.getToastTitle = function(type) {
        const titles = {
            'success': 'Success',
            'error': 'Error',
            'warning': 'Warning',
            'info': 'Information'
        };
        return titles[type] || titles.info;
    };

    window.UltraGuardComponents.handleDismissClick = function(e) {
        e.preventDefault();
        
        const $button = $(e.currentTarget);
        if (!$button || !$button.length) return;
        
        const $message = $button.closest('.ultraguard-message, .ultraguard-alert');
        
        $message.fadeOut(300, function() {
            $(this).remove();
        });
    };

    // ==================== Bulk Actions ====================
    window.UltraGuardComponents.handleBulkActionApply = function(e, instance) {
        e.preventDefault();
        
        const $button = $(e.currentTarget);
        if (!$button || !$button.length || !instance) return;
        
        const $container = $button.closest('.ultraguard-bulk-actions');
        const $select = $container.find('.ultraguard-bulk-action-select');
        const action = $select.val();
        const bulkKey = `bulk_${action}`;

        if (!action) {
            if (instance.showMessage) {
                instance.showMessage('Please select a bulk action', 'warning');
            }
            return;
        }
        
        const selectedItems = window.UltraGuardComponents.getSelectedItems();
        if (selectedItems.length === 0) {
            if (instance.showMessage) {
                instance.showMessage('Please select items to perform bulk action', 'warning');
            }
            return;
        }
        
        if (!confirm('Are you sure you want to perform this bulk action?')) {
            return;
        }

        if (instance.isInQueue && instance.isInQueue(bulkKey)) {
            return;
        }

        if (instance.addToQueue) instance.addToQueue(bulkKey);
        if (instance.showLoading) instance.showLoading($button);
        
        const elementNonce = $container.data('nonce') || $button.data('nonce');
        const nonce = elementNonce || instance.ajaxParams.nonce;
        
        if (!instance.ajaxManager) {
            console.error('AJAX Manager not available');
            if (instance.showMessage) {
                instance.showMessage('AJAX Manager not available', 'error');
            }
            if (instance.hideLoading) instance.hideLoading($button);
            if (instance.removeFromQueue) instance.removeFromQueue(bulkKey);
            return;
        }
        
        instance.ajaxManager.post(instance.ajaxParams.ajaxurl, {
            action: 'ultraguard_bulk_action',
            bulk_action: action,
            items: selectedItems,
            nonce: nonce
        })
        .then(response => {
            if (instance.responseHandler && instance.responseHandler.handle) {
                instance.responseHandler.handle(response, {
                    sourceElement: $button,
                    sourceType: 'bulk-action'
                });
            }
        })
        .catch(error => {
            console.error('Bulk action failed:', error);
            if (instance.showMessage) {
                instance.showMessage(error.message || 'Bulk action failed', 'error');
            }
        })
        .finally(() => {
            if (instance.hideLoading) instance.hideLoading($button);
            if (instance.removeFromQueue) instance.removeFromQueue(bulkKey);
        });
    };

    window.UltraGuardComponents.getSelectedItems = function() {
        const selectedItems = [];
        $('.ultraguard-row-selector:checked').each((index, element) => {
            selectedItems.push($(element).val());
        });
        return selectedItems;
    };

    // ==================== Dynamic Content Loading ====================
    window.UltraGuardComponents.handleDynamicLoad = function(e, instance) {
        e.preventDefault();
        
        const $trigger = $(e.currentTarget);
        if (!$trigger || !$trigger.length || !instance) return;
        
        const target = $trigger.data('dynamic-load');
        const source = $trigger.data('source');
        const loadKey = `load_${source}`;
        
        const $target = $(target);
        if (!$target.length) {
            console.error('Dynamic load target not found:', target);
            return;
        }

        if (instance.isInQueue && instance.isInQueue(loadKey)) {
            return;
        }

        if (instance.addToQueue) instance.addToQueue(loadKey);
        if (instance.showLoading) instance.showLoading($target);
        
        const elementNonce = $trigger.data('nonce');
        const nonce = elementNonce || instance.ajaxParams.nonce;
        
        if (!instance.ajaxManager) {
            console.error('AJAX Manager not available');
            if (instance.showMessage) {
                instance.showMessage('AJAX Manager not available', 'error');
            }
            if (instance.hideLoading) instance.hideLoading($target);
            if (instance.removeFromQueue) instance.removeFromQueue(loadKey);
            return;
        }
        
        instance.ajaxManager.get(instance.ajaxParams.ajaxurl, {
            action: 'ultraguard_load_data',
            source: source,
            context: $trigger.data('context') || {},
            nonce: nonce
        })
        .then(response => {
            if (instance.responseHandler && instance.responseHandler.handle) {
                instance.responseHandler.handle(response, {
                    sourceElement: $target,
                    sourceType: 'dynamic-load'
                });
            }
        })
        .catch(error => {
            console.error('Dynamic content load failed:', error);
            if (instance.showMessage) {
                instance.showMessage('Failed to load dynamic content: ' + error.message, 'error');
            }
        })
        .finally(() => {
            if (instance.hideLoading) instance.hideLoading($target);
            if (instance.removeFromQueue) instance.removeFromQueue(loadKey);
        });
    };

    // ==================== Real-time Updates ====================
    window.UltraGuardComponents.handleRealtimeUpdate = function(e, data, instance) {
        if (!data) return;
        
        if (data.component && data.html) {
            const $component = $(data.component);
            if ($component.length) {
                $component.html(data.html);
                if (window.UltraGuardComponents.initializeCharts) {
                    window.UltraGuardComponents.initializeCharts(instance, $component);
                }
                if (window.UltraGuardComponents.initializeAccordions) {
                    window.UltraGuardComponents.initializeAccordions();
                }
            }
        }
        
        if (data.stats) {
            window.UltraGuardComponents.updateStats(data.stats);
        }
    };

    window.UltraGuardComponents.updateStats = function(stats) {
        if (!stats) return;
        
        Object.keys(stats).forEach(statId => {
            const $stat = $(`#${statId}`);
            if ($stat.length) {
                const newValue = stats[statId];
                const oldValue = $stat.data('current-value');
                
                $stat.text(newValue);
                $stat.data('current-value', newValue);
                
                if (oldValue !== undefined && oldValue !== newValue) {
                    $stat.addClass('ultraguard-stat-updated');
                    setTimeout(() => {
                        $stat.removeClass('ultraguard-stat-updated');
                    }, 1000);
                }
            }
        });
    };

    // Log successful initialization

})(jQuery);
