jQuery(document).ready(function($) {
    // Initialize original toggle states for Save Changes functionality
    var originalToggleStates = {};
    
    // Notification function
    function showNotification(message, type) {
        var notification = $('<div class="formshield-notification formshield-notification-' + type + '">' + message + '</div>');
        $('body').append(notification);
        
        // Show notification
        setTimeout(function() {
            notification.addClass('show');
        }, 100);
        
        // Hide notification after 3 seconds
        setTimeout(function() {
            notification.removeClass('show');
            setTimeout(function() {
                notification.remove();
            }, 300);
        }, 3000);
    }
    
    // Store original toggle states when page loads
    $('.formshield-toggle').each(function() {
        var formId = $(this).data('form-id');
        originalToggleStates[formId] = $(this).is(':checked');
    });
    
    // Toggle change handler
    $('.formshield-toggle').on('change', function() {
        var $toggle = $(this);
        var formId = $toggle.data('form-id');
        var isEnabled = $toggle.is(':checked');
        
        // Update toggle status display
        var $status = $toggle.closest('tr').find('.toggle-status');
        if (isEnabled) {
            $status.removeClass('disabled').addClass('enabled').text('Enabled');
        } else {
            $status.removeClass('enabled').addClass('disabled').text('Disabled');
        }
        
        // Auto-save the change immediately
        autoSaveToggleChange(formId, isEnabled);
    });
    
    // Auto-save individual toggle change
    function autoSaveToggleChange(formId, isEnabled) {
        var changes = {};
        changes[formId] = isEnabled;
        
        // Send AJAX request
        $.post(ajaxConfig.url, {
            action: 'formshield_save_toggle_changes',
            changes: JSON.stringify(changes),
            nonce: ajaxConfig.saveToggleNonce || ajaxConfig.nonce
        })
        .done(function(response) {
            if (response.success) {
                // Update original state
                originalToggleStates[formId] = isEnabled;
                
                // Show success notification
                var message = isEnabled ? 'Form protection enabled and saved' : 'Form protection disabled and saved';
                showNotification(message, 'success');
            } else {
                // Revert toggle state on error
                var $toggle = $('.formshield-toggle[data-form-id="' + formId + '"]');
                $toggle.prop('checked', !isEnabled);
                
                // Update status display
                var $status = $toggle.closest('tr').find('.toggle-status');
                if (!isEnabled) {
                    $status.removeClass('enabled').addClass('disabled').text('Disabled');
                } else {
                    $status.removeClass('disabled').addClass('enabled').text('Enabled');
                }
                
                // Show error notification
                var errorMessage = 'Unknown error';
                if (response.data) {
                    if (typeof response.data === 'string') {
                        errorMessage = response.data;
                    } else if (response.data.message) {
                        errorMessage = response.data.message;
                    } else {
                        errorMessage = JSON.stringify(response.data);
                    }
                }
                showNotification('Failed to save: ' + errorMessage, 'error');
            }
        })
        .fail(function(xhr, status, error) {
            // Revert toggle state on network error
            var $toggle = $('.formshield-toggle[data-form-id="' + formId + '"]');
            $toggle.prop('checked', !isEnabled);
            
            // Update status display
            var $status = $toggle.closest('tr').find('.toggle-status');
            if (!isEnabled) {
                $status.removeClass('enabled').addClass('disabled').text('Disabled');
            } else {
                $status.removeClass('disabled').addClass('enabled').text('Enabled');
            }
            
            showNotification('Failed to save: Network error', 'error');
        });
    }
    
    // Auto-save functionality is now handled by autoSaveToggleChange function above
    
    // Rescan button click handler
    $('.rescan-forms-btn').on('click', function() {
        var $button = $(this);
        
        // Show loading state
        $button.prop('disabled', true).text('🔄 Rescanning...');
        
        // Make AJAX call to rescan all forms
        $.post(ajaxConfig.url, {
            action: 'formsh_rescan_forms',
            nonce: ajaxConfig.rescanNonce
        })
        .done(function(response) {
            if (response.success) {
                $button.text('✅ Rescan Complete!');
                showNotification('Forms rescanned successfully!', 'success');
                
                // Reload page after 2 seconds to show updated forms
                setTimeout(function() {
                    location.reload();
                }, 2000);
            } else {
                $button.text('❌ Rescan Failed');
                showNotification('Failed to rescan forms: ' + (response.data || 'Unknown error'), 'error');
                
                // Reset button after 3 seconds
                setTimeout(function() {
                    $button.prop('disabled', false).text('Rescan Forms');
                }, 3000);
            }
        })
        .fail(function() {
            $button.text('❌ Rescan Failed');
            showNotification('Failed to rescan forms: Network error', 'error');
            
            // Reset button after 3 seconds
            setTimeout(function() {
                $button.prop('disabled', false).text('Rescan Forms');
            }, 3000);
        });
    });
    
    // Statistics button click handler (using event delegation)
    $(document).on('click', '.formshield-stats-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        var $button = $(this);
        var formId = $button.data('form-id');
        
        // Show loading state
        $button.prop('disabled', true).html('<span style="color: #3498db; font-size: 14px;">⏳</span>');
        
        // Make AJAX call to get form statistics
        $.post(ajaxConfig.url, {
            action: 'formshield_get_form_stats',
            form_id: formId,
            nonce: ajaxConfig.nonce
        })
        .done(function(response) {
            if (response.success) {
                showFormStatisticsModal(formId, response.data);
            } else {
                showNotification('Failed to load statistics: ' + (response.data || 'Unknown error'), 'error');
            }
        })
        .fail(function() {
            showNotification('Failed to load statistics: Network error', 'error');
        })
        .always(function() {
            // Reset button
            $button.prop('disabled', false).html('<span style="color: #3498db; font-size: 14px;">📊</span>');
        });
    });
    
    // Show form statistics modal
    function showFormStatisticsModal(formId, stats) {
        var modalHtml = `
            <div id="formshield-stats-modal" class="formshield-modal">
                <div class="formshield-modal-content">
                    <div class="formshield-modal-header">
                        <h2>📊 Form Statistics</h2>
                        <button type="button" class="formshield-modal-close">&times;</button>
                    </div>
                    <div class="formshield-modal-body">
                        <div class="stats-grid">
                            <div class="stat-card">
                                <h3>🛡️ Protection</h3>
                                <div class="stat-value">${stats.blocked_attempts || 0}</div>
                                <div class="stat-label">Blocked Attempts</div>
                            </div>
                            <div class="stat-card">
                                <h3>📝 Submissions</h3>
                                <div class="stat-value">${stats.total_submissions || 0}</div>
                                <div class="stat-label">Total Submissions</div>
                            </div>
                            <div class="stat-card">
                                <h3>👤 Human</h3>
                                <div class="stat-value">${stats.human_submissions || 0}</div>
                                <div class="stat-label">Human Submissions</div>
                            </div>
                            <div class="stat-card">
                                <h3>⚠️ Suspicious</h3>
                                <div class="stat-value">${stats.suspicious_submissions || 0}</div>
                                <div class="stat-label">Suspicious Submissions</div>
                            </div>
                        </div>
                        <div class="stats-details">
                            <h3>📈 Activity Timeline</h3>
                            <div class="timeline">
                                ${stats.last_activity ? '<div class="timeline-item"><span class="time">' + stats.last_activity + '</span><span class="activity">Last Activity</span></div>' : ''}
                                ${stats.last_attack ? '<div class="timeline-item"><span class="time">' + stats.last_attack + '</span><span class="activity">Last Attack Blocked</span></div>' : ''}
                            </div>
                        </div>
                    </div>
                    <div class="formshield-modal-footer">
                        <button type="button" class="button button-secondary formshield-modal-close">Close</button>
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing modal if any
        $('#formshield-stats-modal').remove();
        
        // Add modal to page
        $('body').append(modalHtml);
        
        // Show modal
        $('#formshield-stats-modal').fadeIn(300);
        
        // Close modal handlers
        $('.formshield-modal-close').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $('#formshield-stats-modal').fadeOut(300, function() {
                $(this).remove();
            });
        });
        
        // Close on background click
        $('#formshield-stats-modal').on('click', function(e) {
            if (e.target === this) {
                $(this).fadeOut(300, function() {
                    $(this).remove();
                });
            }
        });
        
        // Close on ESC key
        $(document).on('keydown.formshield-modal', function(e) {
            if (e.keyCode === 27) { // ESC key
                $('#formshield-stats-modal').fadeOut(300, function() {
                    $(this).remove();
                });
                $(document).off('keydown.formshield-modal');
            }
        });
    }
});
