/**
 * FormShield Divi Forms Behavioral Tracking & Spam Blocking
 * 
 * Tracks user behavior for spam detection
 * GDPR compliant - no fingerprinting, only form-specific tracking
 * 
 * Note: For Divi 5, we rely on server-side protection (intercept_divi_ajax)
 * instead of JavaScript interception, as Divi 5's form handling is incompatible
 * with client-side submit interception.
 */
(function($) {
    'use strict';
    
    const FormShieldDiviTracking = {
        formStartTime: {},
        mouseMoveCount: {},
        focusEventCount: {},
        isProcessing: {},
        isDivi5: false,
        
        init: function() {
            // Detect Divi 5 by checking for its specific elements or global vars
            this.isDivi5 = this.detectDivi5();
            
            console.log('[FormShield DEBUG] Divi version detected:', this.isDivi5 ? 'Divi 5+' : 'Divi 4 or earlier');
            
            this.trackDiviForms();
            
            // Only bind submit handler for Divi 4 and earlier
            // Divi 5 uses server-side protection via intercept_divi_ajax
            if (!this.isDivi5) {
                this.bindSubmitHandler();
            } else {
                console.log('[FormShield DEBUG] Divi 5 detected - using server-side protection only');
            }
        },
        
        detectDivi5: function() {
            // Divi 5 uses a different structure and has specific markers
            // Check for Divi 5 specific elements or global variables
            
            // Method 1: Check for Divi 5 specific CSS class or element
            if ($('.et-db, .et-l, [data-et-multi-view]').length > 0) {
                return true;
            }
            
            // Method 2: Check for Divi 5's React-based forms
            if ($('.et_pb_contact_form[data-et-multi-view-load-tablet-hidden]').length > 0) {
                return true;
            }
            
            // Method 3: Check for DiviArea or other Divi 5 globals
            if (typeof window.DiviArea !== 'undefined' || typeof window.ETBuilderBackend !== 'undefined') {
                return true;
            }
            
            // Method 4: Check Divi version from et_builder_version if available
            if (typeof et_builder_version !== 'undefined') {
                const version = parseFloat(et_builder_version);
                if (version >= 5.0) {
                    return true;
                }
            }
            
            // Method 5: Check for Divi 5 form structure (most reliable)
            // Divi 5 forms have a different AJAX handling mechanism
            if ($('.et_pb_module.et_pb_contact_form_0').length > 0) {
                // Check if form uses new Divi 5 structure
                const $form = $('.et_pb_contact_form').first();
                if ($form.find('[data-type="et_pb_contact_form"]').length > 0) {
                    return true;
                }
            }
            
            // Default: assume Divi 5 if we can't reliably detect version
            // This is safer as server-side protection always works
            // But check for classic Divi 4 markers first
            if ($('.et_pb_contact_form .et_pb_contact_form_0').length > 0 || 
                $('input[name="et_pb_contactform_submit"]').length > 0) {
                return false; // Classic Divi 4 form
            }
            
            // If unsure, assume Divi 5 to be safe
            return true;
        },
        
        trackDiviForms: function() {
            // Track all Divi contact forms
            $(document).on('focus', '.et_pb_contact_form input, .et_pb_contact_form textarea', function() {
                const form = $(this).closest('.et_pb_contact_form');
                const formId = FormShieldDiviTracking.getFormId(form);
                
                // Start tracking when user first interacts
                if (!FormShieldDiviTracking.formStartTime[formId]) {
                    FormShieldDiviTracking.formStartTime[formId] = Date.now();
                }
                
                // Increment focus events
                if (!FormShieldDiviTracking.focusEventCount[formId]) {
                    FormShieldDiviTracking.focusEventCount[formId] = 0;
                }
                FormShieldDiviTracking.focusEventCount[formId]++;
            });
            
            // Track mouse movements within form
            $(document).on('mousemove', '.et_pb_contact_form', function(e) {
                const form = $(this).closest('.et_pb_contact_form');
                const formId = FormShieldDiviTracking.getFormId(form);
                
                if (!FormShieldDiviTracking.mouseMoveCount[formId]) {
                    FormShieldDiviTracking.mouseMoveCount[formId] = 0;
                }
                FormShieldDiviTracking.mouseMoveCount[formId]++;
            });
        },
            
        bindSubmitHandler: function() {
            const selector = '.et_pb_contact_form form, form.et_pb_contact_form';
            
            // Remove previous handler to avoid duplicates
            $(document).off('submit.formshield', selector);
            
            // Intercept form submission BEFORE Divi processes it
            $(document).on('submit.formshield', selector, function(e) {
                const $form = $(this).hasClass('et_pb_contact_form') ? $(this) : $(this).closest('.et_pb_contact_form');
                const formId = FormShieldDiviTracking.getFormId($form);
                
                console.log('[FormShield DEBUG] Submit event caught for form:', formId);
                
                // Prevent double processing
                if (FormShieldDiviTracking.isProcessing[formId]) {
                    console.log('[FormShield DEBUG] Already processing, preventing');
                    e.preventDefault();
                    return false;
                }
                
                // Check if this form was already validated
                if ($form.data('formshield-validated') === true) {
                    // Already validated, allow submission
                    console.log('[FormShield DEBUG] Form already validated, allowing submission');
                    $form.data('formshield-validated', false);
                    return true; // Allow the event to continue
                }
                
                // Stop the form submission
                e.preventDefault();
                e.stopPropagation();
                
                // Mark as processing
                FormShieldDiviTracking.isProcessing[formId] = true;
                
                // Show loading state
                const $submitBtn = $form.find('input[type="submit"], button[type="submit"], .et_pb_contact_submit');
                const originalText = $submitBtn.val() || $submitBtn.text();
                $submitBtn.prop('disabled', true);
                if ($submitBtn.is('input')) {
                    $submitBtn.val('Проверка...');
                } else {
                    $submitBtn.text('Проверка...');
                }
                
                // Collect form data
                const formData = {
                    post_id: FormShieldDiviTracking.getPostId($form),
                    form_id: formId,
                    message: FormShieldDiviTracking.getMessage($form),
                    email: FormShieldDiviTracking.getEmail($form),
                    name: FormShieldDiviTracking.getName($form),
                    behavioral_data: {
                        form_fill_time: FormShieldDiviTracking.formStartTime[formId] 
                            ? Math.floor((Date.now() - FormShieldDiviTracking.formStartTime[formId]) / 1000)
                            : 0,
                        mouse_moves: FormShieldDiviTracking.mouseMoveCount[formId] || 0,
                        focus_events: FormShieldDiviTracking.focusEventCount[formId] || 0
                    }
                };
                
                // Check with our spam detection endpoint
                FormShieldDiviTracking.checkSubmission(formData, $form, $submitBtn, originalText);
                
                return false;
            });
        },
        
        getFormId: function($form) {
            // Try to get form ID from data attributes or generate unique ID
            let formId = $form.attr('id');
            
            if (!formId) {
                // Try to get from data attributes
                formId = $form.attr('data-form-id') || $form.attr('data-et-pb-contact-form-id');
            }
            
            if (!formId) {
                // Generate unique ID based on form position and content
                const formIndex = $('.et_pb_contact_form').index($form);
                const pageId = $('body').attr('data-page-id') || window.location.pathname;
                formId = 'divi_form_' + formIndex + '_' + pageId.replace(/[^a-zA-Z0-9]/g, '_');
            }
            
            return formId;
        },
        
        getPostId: function($form) {
            // Try to get post ID from body data attribute or formshieldData
            let postId = $('body').attr('data-page-id');
            if (!postId && typeof formshieldData !== 'undefined' && formshieldData.postId) {
                postId = formshieldData.postId;
            }
            return postId || 0;
        },
        
        getMessage: function($form) {
            // Try to find message/comment field
            let message = '';
            $form.find('textarea[name*="message"], textarea[name*="comment"], textarea[name*="msg"], textarea').each(function() {
                const val = $(this).val();
                if (val && val.length > message.length) {
                    message = val;
                }
            });
            return message;
        },
        
        getEmail: function($form) {
            // Try to find email field
            let email = '';
            $form.find('input[type="email"], input[name*="email"]').each(function() {
                email = $(this).val();
                return false; // Get first match
            });
            return email;
        },
        
        getName: function($form) {
            // Try to find name field
            let name = '';
            $form.find('input[name*="name"], input[name*="first"], input[name*="fname"]').each(function() {
                name = $(this).val();
                return false; // Get first match
            });
            return name;
        },
        
        checkSubmission: function(formData, $form, $submitBtn, originalText) {
            const formId = formData.form_id;
            
            // DEBUG: Log submission attempt
            console.log('[FormShield DEBUG] checkSubmission called', {
                message: formData.message.substring(0, 50),
                email: formData.email,
                name: formData.name,
                behavioral_data: formData.behavioral_data
            });
            
            // Send request to check spam
            if (typeof formshieldData === 'undefined' || !formshieldData.ajaxurl) {
                // FormShield not initialized - allow submission
                console.log('[FormShield DEBUG] FormShield not initialized, allowing submission');
                FormShieldDiviTracking.allowSubmission($form, $submitBtn, originalText, formId);
                return;
            }
            
            $.ajax({
                url: formshieldData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'formshield_check_divi_submission',
                    nonce: formshieldData.nonce,
                    post_id: formData.post_id,
                    form_id: formData.form_id,
                    message: formData.message,
                    email: formData.email,
                    name: formData.name,
                    behavioral_data: JSON.stringify(formData.behavioral_data)
                },
                timeout: 10000, // 10 second timeout
                success: function(response) {
                    console.log('[FormShield DEBUG] AJAX response:', response);
                    if (response.success) {
                        // Submission allowed - proceed with form
                        console.log('[FormShield DEBUG] Submission allowed, score:', response.data ? response.data.score : 'N/A');
                        FormShieldDiviTracking.allowSubmission($form, $submitBtn, originalText, formId);
                    } else {
                        // Submission BLOCKED - show error
                        console.log('[FormShield DEBUG] Submission BLOCKED, score:', response.data ? response.data.score : 'N/A', 'reason:', response.data ? response.data.reason : 'N/A');
                        FormShieldDiviTracking.blockSubmission($form, $submitBtn, originalText, formId, response.data);
                    }
                },
                error: function(xhr, status, error) {
                    // On error, allow submission (fail-open for UX)
                    console.log('[FormShield DEBUG] AJAX error, allowing submission:', error, xhr.responseText);
                    FormShieldDiviTracking.allowSubmission($form, $submitBtn, originalText, formId);
                }
            });
        },
        
        allowSubmission: function($form, $submitBtn, originalText, formId) {
            console.log('[FormShield DEBUG] allowSubmission called for form:', formId);
            
            // Reset button
            $submitBtn.prop('disabled', false);
            if ($submitBtn.is('input')) {
                $submitBtn.val(originalText);
            } else {
                $submitBtn.text(originalText);
            }
            
            // Mark form as validated
            $form.data('formshield-validated', true);
            
            // Reset processing flag
            FormShieldDiviTracking.isProcessing[formId] = false;
            
            // Find the actual form element
            const $actualForm = $form.is('form') ? $form : $form.find('form').first();
            
            if (!$actualForm.length) {
                console.log('[FormShield DEBUG] ERROR: Could not find form element!');
                return;
            }
            
            // Temporarily remove our handler to avoid recursion
            const selector = '.et_pb_contact_form form, form.et_pb_contact_form';
            $(document).off('submit.formshield', selector);
            
            // Create a new submit event and dispatch it natively
            setTimeout(function() {
                try {
                    // Get the native form element
                    const formElement = $actualForm[0];
                    
                    // Create a native submit event
                    const submitEvent = new Event('submit', {
                        bubbles: true,
                        cancelable: true
                    });
                    
                    // Dispatch the event natively (this will trigger Divi's handler)
                    const submitted = formElement.dispatchEvent(submitEvent);
                    
                    console.log('[FormShield DEBUG] Native submit event dispatched, result:', submitted);
                    
                    // If event was not prevented, manually submit
                    if (submitted && !submitEvent.defaultPrevented) {
                        formElement.submit();
                    } else {
                        // If prevented, try clicking the submit button
                        const $submitButton = $form.find('input[type="submit"], button[type="submit"], .et_pb_contact_submit').first();
                        if ($submitButton.length) {
                            console.log('[FormShield DEBUG] Trying to click submit button');
                            $submitButton[0].click();
                        }
                    }
                } catch (e) {
                    console.log('[FormShield DEBUG] Error submitting form:', e);
                    // Fallback: try native submit
                    const formElement = $actualForm[0];
                    if (formElement && formElement.submit) {
                        formElement.submit();
                    }
                }
                
                // Re-bind handler for subsequent submissions
                setTimeout(function() {
                    FormShieldDiviTracking.bindSubmitHandler();
                }, 100);
            }, 50);
        },
        
        blockSubmission: function($form, $submitBtn, originalText, formId, errorData) {
            // Reset button
            $submitBtn.prop('disabled', false);
            if ($submitBtn.is('input')) {
                $submitBtn.val(originalText);
            } else {
                $submitBtn.text(originalText);
            }
            
            // Reset processing flag
            FormShieldDiviTracking.isProcessing[formId] = false;
            
            // Show error message
            const errorMessage = errorData && errorData.message 
                ? errorData.message 
                : 'Съобщението не може да бъде изпратено. Моля, премахнете линковете и опитайте отново.';
            
            // Remove existing error messages
            $form.find('.formshield-error-message').remove();
            
            // Add error message before submit button
            const $errorDiv = $('<div class="formshield-error-message" style="' +
                'background: #fee2e2; ' +
                'border: 1px solid #ef4444; ' +
                'color: #b91c1c; ' +
                'padding: 12px 16px; ' +
                'border-radius: 6px; ' +
                'margin: 15px 0; ' +
                'font-size: 14px; ' +
                'text-align: center;' +
                '">' +
                '<strong>⚠️ ' + errorMessage + '</strong>' +
                '</div>');
            
            $submitBtn.closest('.et_pb_contact_form, .et_contact_bottom_container').before($errorDiv);
            
            // Scroll to error
            $('html, body').animate({
                scrollTop: $errorDiv.offset().top - 100
            }, 300);
            
            // Auto-remove after 10 seconds
            setTimeout(function() {
                $errorDiv.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 10000);
        }
    };
    
    // Initialize when DOM is ready
    $(document).ready(function() {
        FormShieldDiviTracking.init();
    });
    
})(jQuery);
