/**
 * Stablezact Admin JavaScript
 */

(function($) {
    'use strict';

    // Global admin object
    window.StablezactAdmin = {
        
        /**
         * Initialize admin functionality
         */
        init: function() {
            this.bindEvents();
            this.initComponents();
        },

        /**
         * Bind event listeners
         */
        bindEvents: function() {
            // Dashboard refresh
            $(document).on('click', '#refresh-dashboard', this.refreshDashboard);
            
            // Transaction actions
            $(document).on('click', '.view-transaction', this.viewTransaction);
            $(document).on('click', '.stablezact-modal-close', this.closeModal);
            $(document).on('click', '.coinley-modal', this.closeModalOnOverlay);
            
            // Copy functionality
            $(document).on('click', '.copy-address', this.copyToClipboard);
            $(document).on('click', '.copy-webhook', this.copyToClipboard);
            
            // Settings forms
            $(document).on('submit', '#stablezact-api-form', this.handleApiForm);
            $(document).on('submit', '#stablezact-payment-settings', this.handlePaymentSettings);
            $(document).on('submit', '#stablezact-wallet-form', this.handleWalletForm);
            
            // Connection test
            $(document).on('click', '#test-connection', this.testConnection);
            
            // Webhook regeneration
            $(document).on('click', '#regenerate-webhook-secret', this.regenerateWebhookSecret);
            
            // Network settings
            $(document).on('click', '#save-network-settings', this.saveNetworkSettings);
            $(document).on('change', '.network-toggle', this.toggleNetwork);
            
            // Transaction filters
            $(document).on('click', '#apply-filters', this.applyTransactionFilters);
            $(document).on('click', '#clear-filters', this.clearTransactionFilters);
            $(document).on('click', '#refresh-transactions', this.refreshTransactions);
            
            // Bulk actions
            $(document).on('click', '#select-all-transactions', this.toggleSelectAll);
            $(document).on('click', '#apply-bulk-action', this.applyBulkAction);
            
            // Export functionality
            $(document).on('click', '#export-transactions', this.exportTransactions);
            
            // Clear wallet addresses
            $(document).on('click', '#clear-addresses', this.clearWalletAddresses);
            
            // Validate wallet addresses
            $(document).on('click', '#validate-addresses', this.validateWalletAddresses);
        },

        /**
         * Initialize components
         */
        initComponents: function() {
            // Initialize tooltips if available
            if (typeof $.fn.tooltip === 'function') {
                $('[title]').tooltip();
            }
            
            // Initialize date pickers
            if (typeof $.fn.datepicker === 'function') {
                $('#date-from, #date-to').datepicker({
                    dateFormat: 'yy-mm-dd',
                    maxDate: new Date()
                });
            }
            
            // Auto-refresh dashboard every 5 minutes if on dashboard page
            if ($('.stablezact-admin .stablezact-stats-grid').length) {
                setInterval(this.backgroundRefresh, 300000); // 5 minutes
            }

            // Check API credentials every 15 minutes
            setInterval(this.checkApiCredentials, 900000); // 15 minutes
        },

        /**
         * Check API credentials periodically
         */
        checkApiCredentials: function() {
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_check_credentials',
                nonce: stablezact_admin.nonce
            })
            .done(function(response) {
                if (!response.success) {
                    // Show warning if credentials are invalid
                    StablezactAdmin.showCredentialWarning();
                }
            });
        },

        /**
         * Show credential warning
         */
        showCredentialWarning: function() {
            const $notice = $('<div class="notice notice-warning is-dismissible">' +
                '<p><strong>' + stablezact_admin.strings.credential_warning + '</strong></p>' +
                '<p>' + stablezact_admin.strings.credential_warning_desc + '</p>' +
                '<button type="button" class="button" id="refresh-credentials">' +
                stablezact_admin.strings.refresh_credentials + '</button>' +
                '</div>');
            
            // Remove existing credential warnings
            $('.credential-warning').remove();
            
            // Add new warning
            $notice.addClass('credential-warning')
                   .insertAfter('.wp-header-end');
            
            // Handle refresh button click
            $notice.find('#refresh-credentials').on('click', function(e) {
                e.preventDefault();
                StablezactAdmin.refreshCredentials();
            });
        },

        /**
         * Refresh API credentials
         */
        refreshCredentials: function() {
            const $button = $('#refresh-credentials');
            const originalText = $button.text();
            
            $button.prop('disabled', true)
                   .text(stablezact_admin.strings.refreshing);
            
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_refresh_credentials',
                nonce: stablezact_admin.nonce
            })
            .done(function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    StablezactAdmin.showNotice('error', response.data || stablezact_admin.strings.refresh_failed);
                }
            })
            .fail(function() {
                StablezactAdmin.showNotice('error', stablezact_admin.strings.refresh_failed);
            })
            .always(function() {
                $button.prop('disabled', false).text(originalText);
            });
        },

        /**
         * Refresh dashboard data
         */
        refreshDashboard: function() {
            const $button = $(this);
            const originalText = $button.html();
            
            $button.prop('disabled', true)
                   .html('<span class="spinner is-active"></span> ' + stablezact_admin.strings.loading);
            
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_fetch_dashboard_data',
                nonce: stablezact_admin.nonce
            })
            .done(function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    StablezactAdmin.showNotice('error', stablezact_admin.strings.error);
                }
            })
            .fail(function(xhr, status, error) {
                let errorMessage = stablezact_admin.strings.error || 'An error occurred';
                if (xhr.status === 403) {
                    errorMessage = 'Permission denied. Please check your user permissions.';
                } else if (xhr.status === 500) {
                    errorMessage = 'Server error. Please try again later.';
                } else if (xhr.status === 0) {
                    errorMessage = 'Network error. Please check your connection.';
                }
                StablezactAdmin.showNotice('error', errorMessage);
            })
            .always(function() {
                $button.prop('disabled', false).html(originalText);
            });
        },

        /**
         * Background refresh for dashboard
         */
        backgroundRefresh: function() {
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_fetch_dashboard_data',
                nonce: stablezact_admin.nonce
            })
            .done(function(response) {
                if (response.success && response.data.stats) {
                    StablezactAdmin.updateDashboardStats(response.data.stats);
                }
            });
        },

        /**
         * Update dashboard stats without full reload
         */
        updateDashboardStats: function(stats) {
            $('.stat-card').each(function(index) {
                const $card = $(this);
                const $content = $card.find('.stat-content h3');
                
                switch(index) {
                    case 0:
                        $content.text(StablezactAdmin.formatNumber(stats.totalPayments || 0));
                        break;
                    case 1:
                        $content.text(StablezactAdmin.formatNumber(stats.completedPayments || 0));
                        break;
                    case 2:
                        $content.text(StablezactAdmin.formatNumber(stats.pendingPayments || 0));
                        break;
                    case 3:
                        $content.text('$' + StablezactAdmin.formatNumber(stats.totalVolume || 0, 2));
                        break;
                }
            });
        },

        /**
         * View transaction details
         */
        viewTransaction: function(e) {
            e.preventDefault();
            const paymentId = $(this).data('payment-id');
            StablezactAdmin.showTransactionModal(paymentId);
        },

        /**
         * Show transaction details modal
         */
        showTransactionModal: function(paymentId) {
            const $modal = $('#transaction-modal');
            const $modalBody = $modal.find('.stablezact-modal-body');
            
            $modalBody.html('<div class="loading"><div class="spinner is-active"></div> ' + 
                           stablezact_admin.strings.loading + '</div>');
            $modal.show();
            
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_get_transaction_details',
                nonce: stablezact_admin.nonce,
                payment_id: paymentId
            })
            .done(function(response) {
                if (response.success) {
                    $modalBody.html(StablezactAdmin.buildTransactionDetailsHTML(response.data));
                } else {
                    $modalBody.html('<div class="error">' + (response.data || stablezact_admin.strings.error) + '</div>');
                }
            })
            .fail(function() {
                $modalBody.html('<div class="error">' + stablezact_admin.strings.error + '</div>');
            });
        },

        /**
         * Build transaction details HTML
         */
        buildTransactionDetailsHTML: function(transaction) {
            let html = '<div class="transaction-details">';
            
            // Payment Information
            html += '<div class="detail-section">';
            html += '<h4>Payment Information</h4>';
            html += '<div class="detail-grid">';
            html += StablezactAdmin.buildDetailRow('Payment ID', '<code>' + transaction.id + '</code>');
            html += StablezactAdmin.buildDetailRow('Amount', '<strong>$' + parseFloat(transaction.amount).toFixed(2) + '</strong>');
            html += StablezactAdmin.buildDetailRow('Total Amount', '<strong>$' + parseFloat(transaction.totalAmount || transaction.amount).toFixed(2) + '</strong>');
            html += StablezactAdmin.buildDetailRow('Fee Amount', '$' + parseFloat(transaction.feeAmount || 0).toFixed(2));
            html += StablezactAdmin.buildDetailRow('Currency', '<span class="currency-badge">' + transaction.currency + '</span>');
            html += StablezactAdmin.buildDetailRow('Network', transaction.network);
            html += StablezactAdmin.buildDetailRow('Status', '<span class="status-badge status-' + transaction.status + '">' + transaction.status + '</span>');
            html += '</div></div>';
            
            // Blockchain Information
            if (transaction.transactionHash) {
                html += '<div class="detail-section">';
                html += '<h4>Blockchain Information</h4>';
                html += '<div class="detail-grid">';
                html += StablezactAdmin.buildDetailRow('Transaction Hash', '<code>' + transaction.transactionHash + '</code>');
                html += StablezactAdmin.buildDetailRow('Confirmations', transaction.confirmations || 'N/A');
                html += '</div></div>';
            }
            
            // Timeline
            html += '<div class="detail-section">';
            html += '<h4>Timeline</h4>';
            html += '<div class="detail-grid">';
            html += StablezactAdmin.buildDetailRow('Created', new Date(transaction.createdAt).toLocaleString());
            if (transaction.processedAt) {
                html += StablezactAdmin.buildDetailRow('Processed', new Date(transaction.processedAt).toLocaleString());
            }
            if (transaction.expiresAt) {
                html += StablezactAdmin.buildDetailRow('Expires', new Date(transaction.expiresAt).toLocaleString());
            }
            html += '</div></div>';
            
            html += '</div>';
            return html;
        },

        /**
         * Build detail row HTML
         */
        buildDetailRow: function(label, value) {
            return '<div class="detail-row"><label>' + label + ':</label><span>' + value + '</span></div>';
        },

        /**
         * Close modal
         */
        closeModal: function(e) {
            e.preventDefault();
            $(this).closest('.coinley-modal').hide();
        },

        /**
         * Close modal on overlay click
         */
        closeModalOnOverlay: function(e) {
            if (e.target === this) {
                $(this).hide();
            }
        },

        /**
         * Copy to clipboard
         */
        copyToClipboard: function(e) {
            e.preventDefault();
            const $button = $(this);
            const text = $button.data('address') || $button.data('url');
            
            if (navigator.clipboard) {
                navigator.clipboard.writeText(text).then(function() {
                    const originalContent = $button.html();
                    $button.html('<span class="dashicons dashicons-yes"></span>');
                    setTimeout(function() {
                        $button.html(originalContent);
                    }, 2000);
                });
            }
        },

        /**
         * Handle API form submission
         */
        handleApiForm: function(e) {
            const $form = $(this);
            const $button = $form.find('button[type="submit"]');
            
            $button.prop('disabled', true)
                   .html('<span class="spinner is-active"></span> Connecting...');
        },

        /**
         * Handle payment settings form
         */
        handlePaymentSettings: function(e) {
            e.preventDefault();
            
            const $form = $(this);
            const $button = $form.find('button[type="submit"]');
            const formData = $form.serialize();
            
            $button.prop('disabled', true)
                   .html('<span class="spinner is-active"></span> Saving...');
            
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_save_payment_settings',
                nonce: stablezact_admin.nonce,
                settings: formData
            })
            .done(function(response) {
                if (response.success) {
                    StablezactAdmin.showNotice('success', 'Settings saved successfully!');
                } else {
                    StablezactAdmin.showNotice('error', response.data || 'Failed to save settings');
                }
            })
            .fail(function(xhr, status, error) {
                let errorMessage = stablezact_admin.strings.error || 'An error occurred';
                if (xhr.status === 403) {
                    errorMessage = 'Permission denied. Please check your user permissions.';
                } else if (xhr.status === 500) {
                    errorMessage = 'Server error. Please try again later.';
                } else if (xhr.status === 0) {
                    errorMessage = 'Network error. Please check your connection.';
                }
                StablezactAdmin.showNotice('error', errorMessage);
            })
            .always(function() {
                $button.prop('disabled', false)
                       .html('<span class="dashicons dashicons-saved"></span> Save Payment Settings');
            });
        },

        /**
         * Handle wallet form submission
         */
        handleWalletForm: function(e) {
            e.preventDefault();
            const $form = $(this);
            const $submitButton = $form.find('#save-wallet-addresses');
            const originalText = $submitButton.html();
            
            // Disable submit button and show loading state
            $submitButton.prop('disabled', true)
                        .html('<span class="spinner is-active"></span> ' + stablezact_admin.strings.saving);
            
            // Get form data and filter out empty wallet addresses
            const formData = $form.serializeArray();
            const wallets = [];
            let currentWallet = {};
            let currentIndex = -1;
            
            formData.forEach(function(item) {
                const match = item.name.match(/wallets\[(\d+)\]\[(\w+)\]/);
                if (match) {
                    const index = parseInt(match[1]);
                    const field = match[2];
                    
                    if (index !== currentIndex) {
                        if (currentIndex !== -1 && currentWallet.walletAddress) {
                            wallets.push(currentWallet);
                        }
                        currentWallet = {};
                        currentIndex = index;
                    }
                    
                    if (field === 'supportedTokens') {
                        if (!currentWallet.supportedTokens) {
                            currentWallet.supportedTokens = [];
                        }
                        currentWallet.supportedTokens.push(item.value);
                    } else {
                        currentWallet[field] = item.value;
                    }
                }
            });
            
            // Add the last wallet if it has an address
            if (currentWallet.walletAddress) {
                wallets.push(currentWallet);
            }
            
            // Filter out wallets with empty addresses
            const validWallets = wallets.filter(wallet => wallet.walletAddress.trim() !== '');
            
            // Make the API request
            $.ajax({
                url: stablezact_admin.ajax_url,
                method: 'POST',
                data: {
                    action: 'stablezact_update_wallets',
                    nonce: stablezact_admin.nonce,
                    wallets: validWallets
                }
            })
            .done(function(response) {
                if (response.success) {
                    StablezactAdmin.showNotice('success', stablezact_admin.strings.wallets_updated);
                } else {
                    StablezactAdmin.showNotice('error', response.data || stablezact_admin.strings.error);
                }
            })
            .fail(function(xhr, status, error) {
                let errorMessage = stablezact_admin.strings.error || 'An error occurred';
                if (xhr.status === 403) {
                    errorMessage = 'Permission denied. Please check your user permissions.';
                } else if (xhr.status === 500) {
                    errorMessage = 'Server error. Please try again later.';
                } else if (xhr.status === 0) {
                    errorMessage = 'Network error. Please check your connection.';
                }
                StablezactAdmin.showNotice('error', errorMessage);
            })
            .always(function() {
                $submitButton.prop('disabled', false).html(originalText);
            });
        },

        /**
         * Test API connection
         */
        testConnection: function(e) {
            e.preventDefault();
            
            const $button = $(this);
            $button.prop('disabled', true)
                   .html('<span class="spinner is-active"></span> Testing...');
            
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_test_connection',
                nonce: stablezact_admin.nonce
            })
            .done(function(response) {
                if (response.success) {
                    StablezactAdmin.showNotice('success', 'API connection successful!');
                } else {
                    StablezactAdmin.showNotice('error', 'API connection failed: ' + (response.data || 'Unknown error'));
                }
            })
            .fail(function() {
                StablezactAdmin.showNotice('error', 'Connection test failed');
            })
            .always(function() {
                $button.prop('disabled', false)
                       .html('<span class="dashicons dashicons-admin-tools"></span> Test Connection');
            });
        },

        /**
         * Apply transaction filters
         */
        applyTransactionFilters: function(e) {
            e.preventDefault();
            
            if (typeof window.loadTransactions === 'function') {
                window.currentPage = 1;
                window.currentFilters = {
                    status: $('#status-filter').val(),
                    currency: $('#currency-filter').val(),
                    network: $('#network-filter').val(),
                    start_date: $('#date-from').val(),
                    end_date: $('#date-to').val()
                };
                window.loadTransactions();
            }
        },

        /**
         * Clear transaction filters
         */
        clearTransactionFilters: function(e) {
            e.preventDefault();
            
            $('#status-filter, #currency-filter, #network-filter').val('');
            $('#date-from, #date-to').val('');
            
            if (typeof window.loadTransactions === 'function') {
                window.currentPage = 1;
                window.currentFilters = {};
                window.loadTransactions();
            }
        },

        /**
         * Refresh transactions
         */
        refreshTransactions: function(e) {
            e.preventDefault();
            
            if (typeof window.loadTransactions === 'function') {
                window.loadTransactions();
            }
        },

        /**
         * Toggle select all transactions
         */
        toggleSelectAll: function() {
            const isChecked = $(this).prop('checked');
            $('#transactions-tbody input[type="checkbox"]').prop('checked', isChecked);
        },

        /**
         * Apply bulk action
         */
        applyBulkAction: function(e) {
            e.preventDefault();
            
            const action = $('#bulk-action').val();
            const selectedIds = [];
            
            $('#transactions-tbody input[type="checkbox"]:checked').each(function() {
                selectedIds.push($(this).val());
            });
            
            if (!action) {
                StablezactAdmin.showNotice('error', 'Please select an action');
                return;
            }
            
            if (selectedIds.length === 0) {
                StablezactAdmin.showNotice('error', 'Please select transactions');
                return;
            }
            
            if (action === 'export') {
                StablezactAdmin.exportSelectedTransactions(selectedIds);
            }
        },

        /**
         * Export transactions
         */
        exportTransactions: function(e) {
            e.preventDefault();
            StablezactAdmin.showNotice('info', 'Export functionality coming soon');
        },

        /**
         * Export selected transactions
         */
        exportSelectedTransactions: function(transactionIds) {
            StablezactAdmin.showNotice('info', 'Exporting ' + transactionIds.length + ' transactions...');
        },

        /**
         * Toggle network
         */
        toggleNetwork: function() {
            const $toggle = $(this);
            const $card = $toggle.closest('.network-card');
            const $status = $card.find('.network-status');
            
            if ($toggle.prop('checked')) {
                $status.text('Enabled').removeClass('disabled').addClass('enabled');
            } else {
                $status.text('Disabled').removeClass('enabled').addClass('disabled');
            }
        },

        /**
         * Save network settings
         */
        saveNetworkSettings: function(e) {
            e.preventDefault();
            
            const networkSettings = {};
            $('.network-toggle').each(function() {
                networkSettings[$(this).data('network')] = $(this).prop('checked');
            });
            
            const $button = $(this);
            $button.prop('disabled', true)
                   .html('<span class="spinner is-active"></span> Saving...');
            
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_save_network_settings',
                nonce: stablezact_admin.nonce,
                networks: networkSettings
            })
            .done(function(response) {
                if (response.success) {
                    StablezactAdmin.showNotice('success', 'Network settings saved successfully!');
                } else {
                    StablezactAdmin.showNotice('error', response.data || 'Failed to save network settings');
                }
            })
            .fail(function(xhr, status, error) {
                let errorMessage = stablezact_admin.strings.error || 'An error occurred';
                if (xhr.status === 403) {
                    errorMessage = 'Permission denied. Please check your user permissions.';
                } else if (xhr.status === 500) {
                    errorMessage = 'Server error. Please try again later.';
                } else if (xhr.status === 0) {
                    errorMessage = 'Network error. Please check your connection.';
                }
                StablezactAdmin.showNotice('error', errorMessage);
            })
            .always(function() {
                $button.prop('disabled', false)
                       .html('<span class="dashicons dashicons-saved"></span> Save Network Settings');
            });
        },

        /**
         * Regenerate webhook secret
         */
        regenerateWebhookSecret: function(e) {
            e.preventDefault();
            
            if (!confirm('Are you sure you want to regenerate the webhook secret? You will need to update it in your Stablezact dashboard.')) {
                return;
            }
            
            const $button = $(this);
            $button.prop('disabled', true)
                   .html('<span class="spinner is-active"></span> Generating...');
            
            $.post(stablezact_admin.ajax_url, {
                action: 'stablezact_regenerate_webhook_secret',
                nonce: stablezact_admin.nonce
            })
            .done(function(response) {
                if (response.success) {
                    $('.webhook-secret').text(response.data.secret);
                    StablezactAdmin.showNotice('success', 'Webhook secret regenerated successfully!');
                } else {
                    StablezactAdmin.showNotice('error', 'Failed to regenerate webhook secret');
                }
            })
            .fail(function(xhr, status, error) {
                let errorMessage = stablezact_admin.strings.error || 'An error occurred';
                if (xhr.status === 403) {
                    errorMessage = 'Permission denied. Please check your user permissions.';
                } else if (xhr.status === 500) {
                    errorMessage = 'Server error. Please try again later.';
                } else if (xhr.status === 0) {
                    errorMessage = 'Network error. Please check your connection.';
                }
                StablezactAdmin.showNotice('error', errorMessage);
            })
            .always(function() {
                $button.prop('disabled', false)
                       .html('<span class="dashicons dashicons-update"></span> Regenerate');
            });
        },

        /**
         * Clear all wallet addresses
         */
        clearWalletAddresses: function(e) {
            e.preventDefault();
            const $form = $('#stablezact-wallet-form');
            
            // Clear all wallet address inputs
            $form.find('input[type="text"]').val('');
            
            // Uncheck all token checkboxes
            $form.find('input[type="checkbox"]').prop('checked', false);
            
            // Update validation status
            StablezactAdmin.updateValidationStatus();
        },

        /**
         * Validate wallet addresses
         */
        validateWalletAddresses: function(e) {
            e.preventDefault();
            const $form = $('#stablezact-wallet-form');
            const $button = $(this);
            const originalText = $button.html();
            
            $button.prop('disabled', true)
                   .html('<span class="spinner is-active"></span> ' + stablezact_admin.strings.validating);
            
            // Show validation status container
            $('#wallet-validation').removeClass('hidden');
            
            // Validate each wallet address
            $form.find('.wallet-input').each(function() {
                const $input = $(this);
                const network = $input.data('network');
                const address = $input.val().trim();
                const $status = $('.validation-item[data-network="' + network + '"] .validation-result');
                
                if (!address) {
                    $status.text('EMPTY').removeClass('valid invalid').addClass('empty');
                    $input.removeClass('valid invalid');
                    return;
                }
                
                // Validate address format using the input pattern
                const pattern = new RegExp($input.attr('pattern'));
                const isValid = pattern.test(address);
                
                $status.text(isValid ? 'VALID' : 'INVALID')
                       .removeClass('valid invalid empty')
                       .addClass(isValid ? 'valid' : 'invalid');
                
                $input.removeClass('valid invalid')
                      .addClass(isValid ? 'valid' : 'invalid');
            });
            
            $button.prop('disabled', false).html(originalText);
        },

        /**
         * Update validation status
         */
        updateValidationStatus: function() {
            const $validation = $('#wallet-validation');
            if (!$validation.hasClass('hidden')) {
                $('#validate-addresses').trigger('click');
            }
        },

        /**
         * Show admin notice with improved error handling
         */
        showNotice: function(type, message) {
            // Sanitize message to prevent XSS
            const safeMessage = $('<div>').text(message).html();
            const $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + safeMessage + '</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button></div>');
            
            // Remove any existing notices of the same type
            $('.notice.notice-' + type).remove();
            
            $('.wrap').prepend($notice);
            
            // Make notice dismissible
            $notice.on('click', '.notice-dismiss', function() {
                $notice.fadeOut(function() {
                    $(this).remove();
                });
            });
            
            // Auto-dismiss after 5 seconds (except errors)
            if (type !== 'error') {
                setTimeout(function() {
                    $notice.fadeOut(function() {
                        $(this).remove();
                    });
                }, 5000);
            }
        },

        /**
         * Format number with commas
         */
        formatNumber: function(num, decimals = 0) {
            return parseFloat(num).toLocaleString(undefined, {
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals
            });
        },

        /**
         * Utility: Debounce function
         */
        debounce: function(func, delay) {
            let timeoutId;
            return function(...args) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => func.apply(this, args), delay);
            };
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        StablezactAdmin.init();
        
        // Auto-populate conversion rate field if we're on the gateway settings page
        if (typeof stablezact_admin !== 'undefined' && stablezact_admin.current_conversion_rate) {
            setTimeout(function() {
                // WooCommerce generates field IDs with prefix: woocommerce_[gateway_id]_[field_name]
                var conversionRateField = jQuery('#woocommerce_stablezact_conversion_rate_display');
                if (conversionRateField.length === 0) {
                    // Fallback selectors
                    conversionRateField = jQuery('[id*="conversion_rate_display"]');
                }
                if (conversionRateField.length === 0) {
                    conversionRateField = jQuery('#stablezact_conversion_rate_display');
                }
                
                
                if (conversionRateField.length) {
                    conversionRateField.val(stablezact_admin.current_conversion_rate);
                    // Set color based on content
                    if (stablezact_admin.current_conversion_rate.includes('No conversion needed')) {
                        conversionRateField.css('color', '#28a745'); // Green for USD
                    } else if (stablezact_admin.current_conversion_rate.includes('→')) {
                        conversionRateField.css('color', '#007cba'); // Blue for successful conversion
                    } else if (stablezact_admin.current_conversion_rate.includes('Unable to fetch')) {
                        conversionRateField.css('color', '#dc3545'); // Red for error
                    } else {
                        conversionRateField.css('color', '#6c757d'); // Gray for other states
                    }
                } else {
                }
            }, 500); // Increased delay to ensure WooCommerce form is fully rendered
        }
    });

})(jQuery);

/**
 * Global functions for gateway settings
 */

// Test currency conversion function
function stablezact_test_conversion() {
    jQuery('#stablezact_test_conversion_results').remove();
    
    var $button = jQuery('[id$="test_conversion"]');
    var originalText = $button.val();
    $button.val('Testing...').prop('disabled', true);
    
    // Show testing status in the conversion rate display field
    var conversionRateField = jQuery('#woocommerce_stablezact_conversion_rate_display');
    if (conversionRateField.length === 0) {
        conversionRateField = jQuery('[id*="conversion_rate_display"]');
    }
    if (conversionRateField.length === 0) {
        conversionRateField = jQuery('#stablezact_conversion_rate_display');
    }
    
    
    if (conversionRateField.length) {
        conversionRateField.val('Testing conversion rate...');
        conversionRateField.css('color', '#6c757d'); // Gray color for testing
    }
    
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'stablezact_test_conversion',
            nonce: jQuery('#woocommerce_stablezact_settings_nonce').val() || stablezact_admin.nonce || ''
        },
        success: function(response) {
            if (response.success) {
                var detailsHTML = '<div style="margin-top: 10px; font-size: 14px; color: #666;">';
                if (response.data.conversion_info) {
                    detailsHTML += '<strong>Conversion Test:</strong> ' + response.data.conversion_info + '<br>';
                }
                if (response.data.response_time) {
                    detailsHTML += '<strong>Response Time:</strong> ' + response.data.response_time + '<br>';
                }
                if (response.data.api_source) {
                    detailsHTML += '<strong>API Source:</strong> ' + response.data.api_source + '<br>';
                }
                if (response.data.cache_status) {
                    detailsHTML += '<strong>Cache Status:</strong> ' + response.data.cache_status;
                }
                detailsHTML += '</div>';
                
                // Update the read-only conversion rate display field
                var conversionRateField = jQuery('#woocommerce_stablezact_conversion_rate_display');
                if (conversionRateField.length === 0) {
                    conversionRateField = jQuery('[id*="conversion_rate_display"]');
                }
                if (conversionRateField.length === 0) {
                    conversionRateField = jQuery('#stablezact_conversion_rate_display');
                }
                if (conversionRateField.length && response.data.conversion_info) {
                    conversionRateField.val(response.data.conversion_info);
                    conversionRateField.css('color', '#28a745'); // Green color for success
                }
                
                // Use enhanced notification system if available
                if (typeof showNotification === 'function') {
                    showNotification('success', 'Currency Converter Test Successful', response.data.message + detailsHTML);
                } else {
                    // Fallback to old method
                    var resultHTML = '<div id="stablezact_test_conversion_results" class="notice notice-success inline" style="margin-top: 10px; padding: 10px;"><p><strong>Success:</strong> ' + 
                                   response.data.message + detailsHTML + '</p></div>';
                    $button.closest('tr').after('<tr><td colspan="2">' + resultHTML + '</td></tr>');
                }
            } else {
                var errorMessage = response.data || 'Unknown error occurred';
                
                // Update the read-only conversion rate display field with error
                var conversionRateField = jQuery('#woocommerce_stablezact_conversion_rate_display');
                if (conversionRateField.length === 0) {
                    conversionRateField = jQuery('[id*="conversion_rate_display"]');
                }
                if (conversionRateField.length === 0) {
                    conversionRateField = jQuery('#stablezact_conversion_rate_display');
                }
                if (conversionRateField.length) {
                    conversionRateField.val('Error: ' + errorMessage);
                    conversionRateField.css('color', '#dc3545'); // Red color for error
                }
                
                // Use enhanced notification system if available
                if (typeof showNotification === 'function') {
                    showNotification('error', 'Currency Converter Test Failed', errorMessage);
                } else {
                    // Fallback to old method
                    var resultHTML = '<div id="stablezact_test_conversion_results" class="notice notice-error inline" style="margin-top: 10px; padding: 10px;"><p><strong>Error:</strong> ' + 
                                   errorMessage + '</p></div>';
                    $button.closest('tr').after('<tr><td colspan="2">' + resultHTML + '</td></tr>');
                }
            }
            $button.val(originalText).prop('disabled', false);
        },
        error: function(xhr, status, error) {
            var errorMessage = 'Connection failed. Please check your internet connection and try again.';
            
            // Update the read-only conversion rate display field with connection error
            var conversionRateField = jQuery('#woocommerce_stablezact_conversion_rate_display');
            if (conversionRateField.length === 0) {
                conversionRateField = jQuery('[id*="conversion_rate_display"]');
            }
            if (conversionRateField.length === 0) {
                conversionRateField = jQuery('#stablezact_conversion_rate_display');
            }
            if (conversionRateField.length) {
                conversionRateField.val('Connection Error: ' + errorMessage);
                conversionRateField.css('color', '#dc3545'); // Red color for error
            }
            
            // Use enhanced notification system if available
            if (typeof showNotification === 'function') {
                showNotification('error', 'Currency Converter Connection Failed', errorMessage);
            } else {
                // Fallback to old method
                var resultHTML = '<div id="stablezact_test_conversion_results" class="notice notice-error inline" style="margin-top: 10px; padding: 10px;"><p><strong>Error:</strong> ' + 
                               errorMessage + '</p></div>';
                $button.closest('tr').after('<tr><td colspan="2">' + resultHTML + '</td></tr>');
            }
            $button.val(originalText).prop('disabled', false);
        }
    });
} 

// Add clear credentials function
function clearCredentials() {
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'stablezact_clear_credentials',
            nonce: stablezact_admin.nonce
        },
        success: function(response) {
            if (response.success) {
                // Use enhanced notification system if available
                if (typeof showNotification === 'function') {
                    showNotification('success', 'Credentials Cleared', response.data);
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    alert(response.data);
                    window.location.reload();
                }
            } else {
                // Use enhanced notification system if available
                if (typeof showNotification === 'function') {
                    showNotification('error', 'Failed to Clear Credentials', response.data || 'An error occurred while clearing credentials');
                } else {
                    alert('Failed to clear credentials: ' + response.data);
                }
            }
        },
        error: function() {
            // Use enhanced notification system if available
            if (typeof showNotification === 'function') {
                showNotification('error', 'Connection Error', 'Failed to clear credentials. Please check your connection and try again.');
            } else {
                alert('Failed to clear credentials. Please try again.');
            }
        }
    });
}

// Update wallet form handling
jQuery(document).ready(function($) {
    // ... existing code ...

    // Handle wallet form submission
    $('#stablezact-wallet-form').on('submit', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var submitButton = form.find('button[type="submit"]');
        var statusDiv = $('#wallet-sync-status');
        
        // Disable submit button and show loading state
        submitButton.prop('disabled', true);
        statusDiv.html('<div class="notice notice-info"><p>Updating wallet addresses...</p></div>');
        
        // Collect wallet addresses
        var wallets = {};
        form.find('.wallet-address-input').each(function() {
            var network = $(this).data('network');
            var address = $(this).val().trim();
            if (address) {
                wallets[network] = address;
            }
        });
        
        // Send AJAX request
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'stablezact_update_wallet_addresses',
                nonce: stablezact_admin.nonce,
                wallets: wallets
            },
            success: function(response) {
                if (response.success) {
                    statusDiv.html('<div class="notice notice-success"><p>' + response.data + '</p></div>');
                } else {
                    var errorMsg = response.data;
                    if (errorMsg.includes('Invalid or expired API credentials')) {
                        statusDiv.html('<div class="notice notice-error"><p>' + errorMsg + '</p><button type="button" class="button" onclick="clearCredentials()">Clear Credentials & Login Again</button></div>');
                    } else {
                        statusDiv.html('<div class="notice notice-error"><p>' + errorMsg + '</p></div>');
                    }
                }
            },
            error: function() {
                statusDiv.html('<div class="notice notice-error"><p>Failed to update wallet addresses. Please try again.</p></div>');
            },
            complete: function() {
                submitButton.prop('disabled', false);
            }
        });
    });
}); 