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

(function($) {
    'use strict';

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

    // Make sure global namespace exists
    window.UltraGuardPro = window.UltraGuardPro || {};
    window.UltraGuardComponents = window.UltraGuardComponents || {};
    window.UltraGuardManagers = window.UltraGuardManagers || {};
    window.UltraGuardModals = window.UltraGuardModals || {};

    // Main UltraGuard Pro Class
    window.UltraGuardPro = class UltraGuardPro {
        constructor() {
            this.ajaxManager = null;
            this.realtimeManager = null;
            this.validationEngine = null;
            this.responseHandler = null;
            this.cache = new Map();
            this.initialized = false;
            this.components = new Map();
            this.ajaxQueue = new Map();
            this.documentReady = false;
            this.windowLoaded = false;
            this.sidebar = null;
            
            // Safely get localized variables with proper fallbacks
            this.ajaxParams = this.getAjaxParams();
            
            this.init();
        }

        getAjaxParams() {
            // Try multiple possible locations for ajax parameters
            if (window.ultraguardPro && window.ultraguardPro.ajaxurl) {
                return window.ultraguardPro;
            }
            
            if (window.ultraguard_ajax && window.ultraguard_ajax.ajaxurl) {
                return window.ultraguard_ajax;
            }
            
            // Default fallback
            return {
                ajaxurl: window.ajaxurl || '/wp-admin/admin-ajax.php',
                nonce: (window.ultraguardAdmin && window.ultraguardAdmin.nonce) || ''
            };
        }

        init() {
            if (this.initialized) return;
            // Set flag immediately to prevent duplicate initialization
            // even if init() is called before DOMContentLoaded fires
            this.initialized = true;
            
            const self = this;
            
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    self.bindEvents();
                    self.initComponents();
                });
            } else {
                // DOM is already ready — defer one tick to allow all scripts to parse
                setTimeout(function() {
                    self.bindEvents();
                    self.initComponents();
                }, 0);
            }
        }

        bindEvents() {
            // Document ready
            if (document.readyState === 'complete' || document.readyState === 'interactive') {
                this.documentReady = true;
                this.onDocumentReady();
            } else {
                $(document).ready(() => {
                    this.documentReady = true;
                    this.onDocumentReady();
                });
            }

            // Window load
            if (document.readyState === 'complete') {
                this.windowLoaded = true;
                this.onWindowLoad();
            } else {
                $(window).on('load', () => {
                    this.windowLoaded = true;
                    this.onWindowLoad();
                });
            }

            // AJAX form submission
            $(document).on('submit', '.ultraguard-form[data-ajax="true"]', (e) => {
                this.handleAjaxFormSubmit(e);
            });

            // Tab events
            $(document).on('click', '.ultraguard-tab-nav-link', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleTabClick) {
                    window.UltraGuardComponents.handleTabClick(this, e);
                }
            });

            // Accordion events
            $(document).on('click', '.ultraguard-accordion-header', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleAccordionClick) {
                    window.UltraGuardComponents.handleAccordionClick(e);
                }
            });

            // Toggle events
            $(document).on('change', '.ultraguard-toggle input', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleToggleChange) {
                    window.UltraGuardComponents.handleToggleChange(e);
                }
            });

            // Slider events
            $(document).on('input change', '.ultraguard-slider', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleSliderInput) {
                    window.UltraGuardComponents.handleSliderInput(e);
                }
            });

            // Icon selector events
            $(document).on('click', '.ultraguard-icon-item', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleIconSelect) {
                    window.UltraGuardComponents.handleIconSelect(e);
                }
            });

            // Upload events
            $(document).on('click', '.ultraguard-upload-button', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleUploadClick) {
                    window.UltraGuardComponents.handleUploadClick(e, this);
                }
            });

            $(document).on('click', '.ultraguard-remove-button', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleRemoveClick) {
                    window.UltraGuardComponents.handleRemoveClick(e);
                }
            });

            // Repeater events
            $(document).on('click', '.ultraguard-repeater-add', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleRepeaterAdd) {
                    window.UltraGuardComponents.handleRepeaterAdd(e, this);
                }
            });

            $(document).on('click', '.ultraguard-repeater-remove', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleRepeaterRemove) {
                    window.UltraGuardComponents.handleRepeaterRemove(e);
                }
            });

            // Dismissible messages
            $(document).on('click', '.ultraguard-message-dismiss, .ultraguard-alert-dismiss', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleDismissClick) {
                    window.UltraGuardComponents.handleDismissClick(e);
                }
            });

            // Real-time updates - wire into UltraGuardRealtime channel events
            $(document).on('ultraguard:realtime:update', (e, channel, data) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleRealtimeUpdate) {
                    window.UltraGuardComponents.handleRealtimeUpdate(e, { channel, data }, this);
                }
            });

            // Bulk actions
            $(document).on('click', '.ultraguard-bulk-action-apply', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleBulkActionApply) {
                    window.UltraGuardComponents.handleBulkActionApply(e, this);
                }
            });

            // Widget refresh
            $(document).on('click', '.ultraguard-widget-refresh', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleWidgetRefresh) {
                    window.UltraGuardComponents.handleWidgetRefresh(e, this);
                }
            });

            // AJAX actions
            $(document).on('click', '.ultraguard-ajax-action', (e) => {
                this.handleAjaxAction(e);
            });

            // Form validation
            $(document).on('blur', '.ultraguard-field[data-validation]', (e) => {
                this.handleFieldValidation(e);
            });

            // Chart initialization
            $(document).on('ultraguard:component:loaded', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.initializeCharts) {
                    window.UltraGuardComponents.initializeCharts(this);
                }
            });

            // Dynamic content loading
            $(document).on('click', '[data-dynamic-load]', (e) => {
                if (window.UltraGuardComponents && window.UltraGuardComponents.handleDynamicLoad) {
                    window.UltraGuardComponents.handleDynamicLoad(e, this);
                }
            });

            // Prevent duplicate AJAX requests
            $(document).on('ultraguard:ajax:start', (e, key) => {
                this.addToQueue(key);
            });

            $(document).on('ultraguard:ajax:complete', (e, key) => {
                this.removeFromQueue(key);
            });

            // File Details Modal
            $(document).on('click', '[data-modal-trigger="file-details-modal"]', (e) => {
                if (window.UltraGuardModals && window.UltraGuardModals.handleFileDetailsModalTrigger) {
                    window.UltraGuardModals.handleFileDetailsModalTrigger(e, this);
                }
            });

            // Modal close
            $(document).on('click', '[data-modal-close="file-details-modal"], .ultraguard-modal-overlay', (e) => {
                if (window.UltraGuardModals && window.UltraGuardModals.handleModalClose) {
                    window.UltraGuardModals.handleModalClose(e);
                }
            });

            // Load file content
            $(document).on('click', '#load-file-content-btn', (e) => {
                if (window.UltraGuardModals && window.UltraGuardModals.handleLoadFileContent) {
                    window.UltraGuardModals.handleLoadFileContent(e, this);
                }
            });

            // Quarantine file from modal
            $(document).on('click', '#quarantine-file-btn', (e) => {
                if (window.UltraGuardModals && window.UltraGuardModals.handleQuarantineFile) {
                    window.UltraGuardModals.handleQuarantineFile(e, this);
                }
            });

            // Escape key to close modal
            $(document).on('keydown', (e) => {
                if (e.key === 'Escape' && $('#file-details-modal').is(':visible')) {
                    if (window.UltraGuardModals && window.UltraGuardModals.handleModalClose) {
                        window.UltraGuardModals.handleModalClose(e);
                    }
                }
            });
        }

        onDocumentReady() {
            // Check if components exist before calling
            if (window.UltraGuardComponents) {
                if (window.UltraGuardComponents.initializeTabs) window.UltraGuardComponents.initializeTabs(this);
                if (window.UltraGuardComponents.initializeAccordions) window.UltraGuardComponents.initializeAccordions();
                if (window.UltraGuardComponents.initializeColorPickers) window.UltraGuardComponents.initializeColorPickers();
                if (window.UltraGuardComponents.initializeSliders) window.UltraGuardComponents.initializeSliders();
                if (window.UltraGuardComponents.initializeRepeaters) window.UltraGuardComponents.initializeRepeaters(this);
                if (window.UltraGuardComponents.initializeCharts) window.UltraGuardComponents.initializeCharts(this);
                if (window.UltraGuardComponents.initializeDataTables) window.UltraGuardComponents.initializeDataTables(this);
                if (window.UltraGuardComponents.initializeProgressBars) window.UltraGuardComponents.initializeProgressBars();
                if (window.UltraGuardComponents.initializeCodeEditors) window.UltraGuardComponents.initializeCodeEditors();
                if (window.UltraGuardComponents.initializeWidgets) window.UltraGuardComponents.initializeWidgets(this);
            }
            
            this.initializeSidebar();
            
            if (window.UltraGuardModals && window.UltraGuardModals.initializeModals) {
                window.UltraGuardModals.initializeModals(this);
            }

            $(document).trigger('ultraguard:component:loaded');
        }

        onWindowLoad() {
            if (window.UltraGuardComponents && window.UltraGuardComponents.initializeLazyLoadComponents) {
                window.UltraGuardComponents.initializeLazyLoadComponents(this);
            }
        }

        initializeSidebar() {
            if ($('.ultraguard-app-sidebar').length && !this.sidebar) {
                if (window.UltraGuardModals && window.UltraGuardModals.UltraGuardSidebar) {
                    this.sidebar = new window.UltraGuardModals.UltraGuardSidebar();
                } else {
                    // ultraguard-modals.js not yet parsed — retry once after window.load
                    // This handles script ordering edge cases on slower connections
                    const retryInit = () => {
                        if (!this.sidebar && window.UltraGuardModals && window.UltraGuardModals.UltraGuardSidebar) {
                            this.sidebar = new window.UltraGuardModals.UltraGuardSidebar();
                        }
                    };
                    if (document.readyState === 'complete') {
                        retryInit();
                    } else {
                        $(window).one('load', retryInit);
                    }
                }
            }
        }

        initComponents() {
            // Check if managers exist before initializing
            if (window.UltraGuardManagers) {
                if (window.UltraGuardManagers.UltraGuardAjaxManager) {
                    this.ajaxManager = new window.UltraGuardManagers.UltraGuardAjaxManager(this.ajaxParams);
                }
                
                if (window.UltraGuardManagers.UltraGuardRealtimeManager) {
                    this.realtimeManager = new window.UltraGuardManagers.UltraGuardRealtimeManager();
                }
                
                if (window.UltraGuardManagers.UltraGuardValidationEngine) {
                    this.validationEngine = new window.UltraGuardManagers.UltraGuardValidationEngine();
                }
                this.cache.set
                if (window.UltraGuardManagers.UltraGuardResponseHandler) {
                    this.responseHandler = new window.UltraGuardManagers.UltraGuardResponseHandler(this);
                }
            }
            
            // Log which components were initialized
        }

        addToQueue(key) {
            this.ajaxQueue.set(key, true);
        }

        removeFromQueue(key) {
            this.ajaxQueue.delete(key);
        }

        isInQueue(key) {
            return this.ajaxQueue.has(key);
        }

        showLoading($element) {
            if ($element && $element.length) {
                $element.addClass('ultraguard-loading');
            }
        }

        hideLoading($element) {
            if ($element && $element.length) {
                $element.removeClass('ultraguard-loading');
            }
        }

        registerComponent(type, id, element) {
            this.components.set(`${type}_${id}`, element);
        }

        getComponent(type, id) {
            return this.components.get(`${type}_${id}`);
        }

        getSidebar() {
            return this.sidebar;
        }

        refreshSidebar() {
            if (this.sidebar && typeof this.sidebar.refresh === 'function') {
                this.sidebar.refresh();
            }
        }

        getAjaxManager() {
            return this.ajaxManager;
        }

        getRealtimeManager() {
            return this.realtimeManager;
        }

        getValidationEngine() {
            return this.validationEngine;
        }

        getResponseHandler() {
            return this.responseHandler;
        }

        escapeHtml(text) {
            if (typeof text !== 'string') return text;
            
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, (m) => map[m]);
        }

        debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }

        showMessage(message, type = 'info', duration = 5000) {
            if (window.UltraGuardComponents && window.UltraGuardComponents.showMessage) {
                window.UltraGuardComponents.showMessage(this, message, type, duration);
            } else {
                // Fallback alert if component not available
                alert(message);
            }
        }

        refreshWidget($widget) {
            if (!$widget || !$widget.length) return;
            
            const widgetId = $widget.data('widget-id');
            const widgetType = $widget.data('widget-type');
            const refreshKey = `widget_${widgetId}`;

            if (this.isInQueue(refreshKey) || !this.ajaxManager) {
                return;
            }

            this.addToQueue(refreshKey);
            this.showLoading($widget);
            
            const elementNonce = $widget.data('nonce') || $widget.find('[data-nonce]').data('nonce');
            const nonce = elementNonce || this.ajaxParams.nonce;
            
            this.ajaxManager.post(this.ajaxParams.ajaxurl, {
                action: 'ultraguard_refresh_widget',
                widget_id: widgetId,
                widget_type: widgetType,
                nonce: nonce
            })
            .then(response => {
                if (this.responseHandler) {
                    this.responseHandler.handle(response, {
                        sourceElement: $widget,
                        sourceType: 'widget-refresh'
                    });
                }
            })
            .catch(error => {
                console.error('Widget refresh failed:', error);
                this.showMessage('Widget refresh failed: ' + error.message, 'error');
            })
            .finally(() => {
                this.hideLoading($widget);
                this.removeFromQueue(refreshKey);
            });
        }

        validateAndParseJSON(jsonString) {
            if (!jsonString || typeof jsonString !== 'string') {
                return jsonString;
            }

            jsonString = jsonString.trim();

            if (jsonString === '' || jsonString === 'null') {
                return null;
            }

            try {
                return JSON.parse(jsonString);
            } catch (error) {
                console.warn('Initial JSON parse failed, attempting cleanup:', error.message);

                try {
                    let cleaned = jsonString;

                    cleaned = cleaned
                        .replace(/&quot;/g, '"')
                        .replace(/&#039;/g, "'")
                        .replace(/&#39;/g, "'")
                        .replace(/&amp;/g, '&')
                        .replace(/&apos;/g, "'")
                        .replace(/[“”]/g, '"')
                        .replace(/[‘’]/g, "'")
                        .replace(/\\"/g, '"')
                        .replace(/,\s*([}\]])/g, '$1')
                        .replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, '$1"$2":');

                    if (cleaned.charCodeAt(0) === 0xFEFF) {
                        cleaned = cleaned.substring(1);
                    }

                    try {
                        return JSON.parse(cleaned);
                    } catch (secondError) {
                        console.warn('Cleaned JSON parse failed:', secondError.message);
                        return null;
                    }

                } catch (cleanupError) {
                    console.error('JSON cleanup failed:', cleanupError.message);
                    return null;
                }
            }
        }

        handleAjaxFormSubmit(e) {
            e.preventDefault();

            const $form = $(e.currentTarget);
            if (!$form || !$form.length) return;
            
            const formId = $form.attr('id') || 'form_' + Date.now();

            if (this.isInQueue(formId)) {
                return;
            }

            this.addToQueue(formId);
            this.showLoading($form);

            const formData = {};

            $form.find('input, select, textarea').each((index, element) => {
                const $element = $(element);
                const name = $element.attr('name');
                const type = $element.attr('type');
                const tagName = element.tagName.toLowerCase();

                if (!name) return;

                // Skip internal WP/UG nonce fields — handled explicitly below.
                // Skip the hidden action field — set explicitly below to guarantee
                // the correct value even if the loop processes it first.
                if (name === '_wpnonce' || name === '_ultraguard_nonce' ||
                    name === 'nonce'    || name === 'action') {
                    return;
                }

                if (type === 'checkbox') {
                    if (name.endsWith('[]')) {
                        const cleanName = name.replace('[]', '');
                        if (!formData[cleanName]) formData[cleanName] = [];
                        if ($element.is(':checked')) formData[cleanName].push($element.val());
                    } else {
                        formData[name] = $element.is(':checked') ? '1' : '0';
                    }
                } else if (type === 'radio') {
                    if ($element.is(':checked')) formData[name] = $element.val();
                } else if (tagName === 'select' && $element.prop('multiple')) {
                    formData[name] = $element.val() || [];
                } else {
                    const cleanName = name.endsWith('[]') ? name.replace('[]', '') : name;
                    formData[cleanName] = $element.val();
                }
            });

            // ── Action ────────────────────────────────────────────────────────
            // Priority: data-ajax-action attribute → data-action attribute →
            //           hidden input[name="action"] inside the form.
            // Never fall back to a generic consolidated handler.
            const action = $form.data('ajax-action') ||
                           $form.data('action')      ||
                           $form.find('input[name="action"]').val() ||
                           '';

            if (!action) {
                console.error('UltraGuard form: no AJAX action found on form', $form.attr('id'));
                this.hideLoading($form);
                this.removeFromQueue(formId);
                this.showMessage('Configuration error: missing AJAX action.', 'error');
                return;
            }
            formData.action = action;

            // ── Nonce ─────────────────────────────────────────────────────────
            // Read the single nonce field the PHP renderer emits (name="nonce").
            // Setting formData.nonce here prevents AjaxManager.request() from
            // overwriting it with the page-global 'ultraguard_admin_nonce' value,
            // which would be a different token from the one the form was rendered with.
            const formNonce = $form.find('input[name="nonce"]').val() || '';
            formData.nonce  = formNonce || this.ajaxParams.nonce;

            if (!this.ajaxManager) {
                console.error('AJAX Manager not initialized');
                this.hideLoading($form);
                this.removeFromQueue(formId);
                this.showMessage('System error: AJAX Manager not available', 'error');
                return;
            }

            this.ajaxManager.post(this.ajaxParams.ajaxurl, formData)
                .then(response => {
                    if (this.responseHandler) {
                        this.responseHandler.handle(response, {
                            sourceElement: $form,
                            sourceType: 'form-submit'
                        });
                    }
                    $form.trigger('ultraguard:form:success', [response]);
                })
                .catch(error => {
                    console.error('Form submission error:', error);
                    this.showMessage(error.message || 'Failed to save settings', 'error');
                    $form.trigger('ultraguard:form:error', [error]);
                })
                .finally(() => {
                    this.hideLoading($form);
                    this.removeFromQueue(formId);
                });
        }

        handleAjaxAction(e) {
            e.preventDefault();

            const $button = $(e.currentTarget);
            if (!$button || !$button.length) return;
            
            const ajaxAction = $button.data('ajax-action');
            const elementNonce = $button.data('nonce');
            const confirmMessage = $button.data('confirm');
            const ajaxMethod = $button.data('ajax-method') || 'POST';
            const ajaxDataRaw = $button.data('ajax-data');
            
            if (!ajaxAction) {
                console.error('AJAX action missing data-ajax-action attribute');
                return;
            }
            
            if (confirmMessage && !confirm(confirmMessage)) {
                return;
            }

            const actionKey = `action_${ajaxAction}_${Date.now()}`;

            if (this.isInQueue(actionKey) || !this.ajaxManager) {
                return;
            }

            this.addToQueue(actionKey);
            this.showLoading($button);

            // Start with explicit data-ajax-data payload (static, pre-encoded on the button).
            let ajaxData = {};
            if (ajaxDataRaw) {
                ajaxData = this.validateAndParseJSON(ajaxDataRaw) || {};
            }

            // ── Collect sibling form fields ────────────────────────────────────
            // Buttons inside a card footer (or any container) sit next to — but
            // NOT inside — the card body that holds the input fields.  The form
            // submit handler handles <form data-ajax="true"> forms; but cards
            // that use an ajax-action button in their footer never have an
            // enclosing <form>, so field values are never sent.
            //
            // Fix: walk up to the nearest scoping container (card, section,
            // modal, or generic ultraguard wrapper) and collect every named
            // input/select/textarea found inside it, skipping internal hidden
            // fields that the request already handles (action, nonce, _wpnonce).
            //
            // Explicit data-ajax-data values take priority over field values so
            // that buttons that hard-code certain keys are not overridden.
            // Scope resolution for field collection
            // ─────────────────────────────────────────────────────────────────
            // When a save/submit button lives in a modal FOOTER, its closest()
            // ancestors are:  button → button-group → modal-footer → modal → modal-overlay
            // .ultraguard-modal-body is a SIBLING of modal-footer, NOT an
            // ancestor, so it is never matched by closest() alone.
            //
            // Fix: include .ultraguard-modal-overlay in the selector.
            // The overlay wraps the entire modal (header + body + footer), so
            // closest() finds it when the button is anywhere inside the modal.
            // find('input,select,textarea') then collects all fields in both
            // body and footer — which is exactly what a modal form needs.
            //
            // Card/section buttons outside modals are unaffected: closest()
            // stops at the first match, so a button inside .ultraguard-card
            // resolves to the card (nearer ancestor), never the overlay.
            const $scope = $button.closest(
                '.ultraguard-card, .ultraguard-section, .ultraguard-mini-section, ' +
                '.ultraguard-modal-overlay, .ultraguard-modal-body, ' +
                '.ultraguard-module, [data-field-scope]'
            );

            if ($scope.length) {
                $scope.find('input, select, textarea').each((i, el) => {
                    const $el   = $(el);
                    const name  = $el.attr('name');
                    const type  = ($el.attr('type') || '').toLowerCase();
                    const tag   = el.tagName.toLowerCase();

                    if (!name) return;

                    // Skip fields that are already set explicitly or are internal.
                    if (name === 'action' || name === 'nonce' || name === '_wpnonce' || name === '_ultraguard_nonce') return;
                    if (name in ajaxData) return; // explicit data-ajax-data wins

                    if (type === 'checkbox') {
                        // Only include if not already set from data-ajax-data.
                        if (!(name in ajaxData)) {
                            if (name.endsWith('[]')) {
                                const clean = name.slice(0, -2);
                                if (!ajaxData[clean]) ajaxData[clean] = [];
                                if ($el.is(':checked')) ajaxData[clean].push($el.val());
                            } else {
                                ajaxData[name] = $el.is(':checked') ? '1' : '0';
                            }
                        }
                    } else if (type === 'radio') {
                        if ($el.is(':checked') && !(name in ajaxData)) {
                            ajaxData[name] = $el.val();
                        }
                    } else if (tag === 'select' && $el.prop('multiple')) {
                        if (!(name in ajaxData)) {
                            ajaxData[name] = $el.val() || [];
                        }
                    } else {
                        const cleanName = name.endsWith('[]') ? name.slice(0, -2) : name;
                        if (!(cleanName in ajaxData)) {
                            ajaxData[cleanName] = $el.val();
                        }
                    }
                });
            }
            // ──────────────────────────────────────────────────────────────────

            const requestData = {
                action: ajaxAction,
                nonce: elementNonce || this.ajaxParams.nonce,
                ...ajaxData
            };

            const requestPromise = ajaxMethod.toUpperCase() === 'GET' 
                ? this.ajaxManager.get(this.ajaxParams.ajaxurl, requestData)
                : this.ajaxManager.post(this.ajaxParams.ajaxurl, requestData);

            requestPromise
            .then(response => {
                if (this.responseHandler) {
                    this.responseHandler.handle(response, {
                        sourceElement: $button,
                        sourceType: 'ajax-action'
                    });
                }
            })
            .catch(error => {
                console.error('AJAX action failed:', error);
                if (error.code === 'access_denied') {
                    this.showMessage('Access denied. Please check your permissions or refresh the page.', 'error');
                } else if (error.code === 'nonce_failure' || error.code === 'security_failed') {
                    this.showMessage('Security token expired. Please refresh the page and try again.', 'error');
                } else {
                    this.showMessage(error.message || 'Action failed', 'error');
                }
                $button.trigger('ultraguard:ajax:action:error', [error]);
                
                const errorHandler = $button.data('error-handler');
                if (errorHandler && typeof window[errorHandler] === 'function') {
                    window[errorHandler](error, $button);
                }
            })
            .finally(() => {
                this.hideLoading($button);
                this.removeFromQueue(actionKey);
            });
        }

        handleFieldValidation(e) {
            const $field = $(e.currentTarget);
            if (!$field || !$field.length) return;
            
            const validationRules = $field.data('validation');
            
            if (!validationRules || !this.validationEngine) {
                return;
            }
            
            const validationResult = this.validationEngine.validateField($field, validationRules);
            
            if (!validationResult.isValid) {
                this.validationEngine.showFieldError($field, validationResult.message);
            } else {
                this.validationEngine.clearFieldError($field);
            }
        }
    }

})(jQuery);

// ==================== AUTO-INITIALIZATION ====================
// This is what makes everything work automatically!

(function() {
    'use strict';

    // Function to initialize UltraGuard
    function initUltraGuard() {
        if (typeof jQuery === 'undefined') {
            console.error('UltraGuard Core: jQuery not loaded yet. Retrying in 100ms...');
            setTimeout(initUltraGuard, 100);
            return;
        }

        jQuery(function($) {
            // Check if already initialized
            if (!window.UltraGuardProInstance) {
                // Create new instance
                window.UltraGuardProInstance = new window.UltraGuardPro();
                
            }
        });
    }

    // Start initialization
    initUltraGuard();

    // jQuery plugin for easy access (optional but useful)
    if (typeof jQuery !== 'undefined') {
        jQuery.fn.ultraGuard = function(method, ...args) {
            const ug = window.UltraGuardProInstance;
            
            if (ug && typeof method === 'string' && ug[method]) {
                return ug[method](this, ...args);
            }
            
            return ug;
        };
    }

    // Legacy support - maintains backward compatibility
    if (typeof jQuery !== 'undefined') {
        jQuery(function() {
            if (typeof window.ultraguard_ajax === 'undefined' && window.UltraGuardProInstance) {
                window.ultraguard_ajax = {
                    ajaxurl: window.UltraGuardProInstance.ajaxParams.ajaxurl,
                    nonce: window.UltraGuardProInstance.ajaxParams.nonce
                };
            }
        });
    }

})();

// Global fallback for $ if needed
if (typeof jQuery !== 'undefined' && typeof window.$ === 'undefined') {
    window.$ = jQuery;
}