/**
 * FormShield Divi Forms Behavioral Tracking & Spam Blocking
 * 
 * Tracks user behavior and BLOCKS spam submissions
 * GDPR compliant - no fingerprinting, only form-specific tracking
 */
(function($) {
    'use strict';
    
    const FormShieldDiviTracking = {
        formStartTime: {},
        mouseMoveCount: {},
        focusEventCount: {},
        isProcessing: {},
        
        init: function() {
            this.trackDiviForms();
            this.addFormInterceptor();
        },
        
        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]++;
            });
        },
            
        addFormInterceptor: function() {
            // Intercept form submission BEFORE Divi processes it
            $(document).on('submit', '.et_pb_contact_form form, form.et_pb_contact_form', function(e) {
                const $form = $(this).hasClass('et_pb_contact_form') ? $(this) : $(this).closest('.et_pb_contact_form');
                const formId = FormShieldDiviTracking.getFormId($form);
                
                // Prevent double processing
                if (FormShieldDiviTracking.isProcessing[formId]) {
                    e.preventDefault();
                    return false;
                }
                
                // Check if this form was already validated
                if ($form.data('formshield-validated') === true) {
                    // Already validated, allow submission
                    $form.data('formshield-validated', false);
                    return true;
                }
                
                // Stop the form submission
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();
                
                // 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;
            
            // Send request to check spam
            if (typeof formshieldData === 'undefined' || !formshieldData.ajaxurl) {
                // FormShield not initialized - allow 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) {
                    if (response.success) {
                        // Submission allowed - proceed with form
                        FormShieldDiviTracking.allowSubmission($form, $submitBtn, originalText, formId);
                    } else {
                        // Submission BLOCKED - show error
                        FormShieldDiviTracking.blockSubmission($form, $submitBtn, originalText, formId, response.data);
                    }
                },
                error: function(xhr, status, error) {
                    // On error, allow submission (fail-open for UX)
                    console.log('FormShield check failed, allowing submission:', error);
                    FormShieldDiviTracking.allowSubmission($form, $submitBtn, originalText, formId);
                }
            });
        },
        
        allowSubmission: function($form, $submitBtn, originalText, 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;
            
            // Trigger the actual form submission
            // Use native submit to bypass our handler
            const formElement = $form.find('form').length ? $form.find('form')[0] : $form[0];
            if (formElement && formElement.submit) {
                // Create and dispatch a native submit event
                setTimeout(function() {
                    // Try to find the original submit button and click it
                    const submitButton = $form.find('input[type="submit"], button[type="submit"], .et_pb_contact_submit')[0];
                    if (submitButton) {
                        // Temporarily remove our handler
                        $form.off('submit.formshield');
                        submitButton.click();
                    } else {
                        formElement.submit();
                    }
                }, 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);
