// FormShield Protection Script
jQuery(document).ready(function($) {
    // Debug mode
    const DEBUG = false;
    
    // Инициализация на защитата
    const FormShieldProtection = {
        stats: {
            mouseMovements: 0,
            keyboardEvents: 0,
            formStartTime: null,
            formInteractions: 0
        },
        
        init: function() {
            // Check if there are forms on the page before initializing
            if (this.hasFormsOnPage()) {
                this.setupEventListeners();
                this.injectHoneypots();
                this.setupFormValidation();
                
            } else {
            }
        },
        
        hasFormsOnPage: function() {
            // Check for various form types
            const forms = $('form').length;
            const commentForms = $('#commentform').length;
            const contactForms = $('[class*="contact-form"], [class*="contactform"]').length;
            const diviForms = $('[class*="et_pb_contact_form"]').length;
            
            return forms > 0 || commentForms > 0 || contactForms > 0 || diviForms > 0;
        },
        
        isNearForm: function(element) {
            // Check if mouse is within 200px of any form
            const $element = $(element);
            const forms = $('form');
            
            for (let i = 0; i < forms.length; i++) {
                const $form = $(forms[i]);
                const formRect = $form[0].getBoundingClientRect();
                const mouseX = event.clientX;
                const mouseY = event.clientY;
                
                // Check if mouse is within 200px of form boundaries
                if (mouseX >= formRect.left - 200 && 
                    mouseX <= formRect.right + 200 && 
                    mouseY >= formRect.top - 200 && 
                    mouseY <= formRect.bottom + 200) {
                    return true;
                }
            }
            
            return false;
        },
        
        setupEventListeners: function() {
            // Mouse movement - only track when near forms
            $(document).on('mousemove', (e) => {
                if (this.isNearForm(e.target)) {
                    this.stats.mouseMovements++;
                    if (DEBUG && this.stats.mouseMovements % 10 === 0) {
                    }
                }
            });
            
            // Keyboard events - only track when focused on forms
            $(document).on('keydown', (e) => {
                if ($(e.target).closest('form').length > 0) {
                    this.stats.keyboardEvents++;
                    if (DEBUG && this.stats.keyboardEvents % 5 === 0) {
                    }
                }
            });
            
            // Form field interactions
            $('form input, form textarea').on('focus', (e) => {
                if (!this.stats.formStartTime) {
                    this.stats.formStartTime = Date.now();
                }
                this.stats.formInteractions++;
            });
        },
        
        isWooCommerceForm: function(form) {
            // Check if form is WooCommerce related
            const $form = $(form);
            
            // WooCommerce cart form
            if ($form.hasClass('cart') || $form.hasClass('woocommerce-cart-form') || 
                $form.closest('.woocommerce').length > 0 || 
                $form.closest('.product').length > 0) {
                return true;
            }
            
            // WooCommerce checkout form
            if ($form.hasClass('checkout') || $form.hasClass('woocommerce-checkout') ||
                $form.attr('name') === 'checkout' || $form.attr('id') === 'checkout') {
                return true;
            }
            
            // WooCommerce add to cart form
            if ($form.find('input[name="add-to-cart"]').length > 0 ||
                $form.find('button[name="add-to-cart"]').length > 0 ||
                $form.find('[name*="add-to-cart"]').length > 0) {
                return true;
            }
            
            // WooCommerce variations form
            if ($form.hasClass('variations_form') || $form.find('.variations').length > 0) {
                return true;
            }
            
            // WooCommerce login/register forms
            if ($form.hasClass('woocommerce-form') || 
                $form.hasClass('woocommerce-form-login') ||
                $form.hasClass('woocommerce-form-register')) {
                return true;
            }
            
            return false;
        },
        
        injectHoneypots: function() {
            $('form').each((i, form) => {
                // Skip WooCommerce forms - we don't have integration yet
                if (this.isWooCommerceForm(form)) {
                    return; // Skip this form
                }
                
                const honeypotId = 'fs_hp_' + Math.random().toString(36).substr(2, 9);
                const honeypot = $('<input>', {
                    type: 'text',
                    name: honeypotId,
                    id: honeypotId,
                    autocomplete: 'off'
                }).css({
                    position: 'absolute',
                    left: '-9999px',
                    opacity: 0,
                    height: 0,
                    width: 0
                });
                
                $(form).append(honeypot);
            });
        },
        
        setupFormValidation: function() {
            $('form').on('submit', (e) => {
                const form = e.target;
                
                // Skip WooCommerce forms - we don't have integration yet
                if (this.isWooCommerceForm(form)) {
                    return true; // Allow submission
                }
                
                const validationResult = this.validateSubmission(form);
                
                if (DEBUG) {
                }
                
                if (!validationResult.isValid) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Показваме грешка
                    this.showError(form, validationResult.failures);
                    
                    // Логваме опита
                    this.logAttempt(form, validationResult);
                    
                    return false;
                }
            });
        },
        
        validateSubmission: function(form) {
            const validationResult = {
                isValid: true,
                failures: [],
                stats: { ...this.stats }
            };
            
            // Проверка за време
            const timeTaken = Date.now() - (this.stats.formStartTime || Date.now());
            if (timeTaken < 3000) { // По-малко от 3 секунди
                validationResult.isValid = false;
                validationResult.failures.push('submission_too_fast');
            }
            
            // Проверка за движения на мишката
            if (this.stats.mouseMovements < 5) {
                validationResult.isValid = false;
                validationResult.failures.push('insufficient_mouse_movement');
            }
            
            // Проверка за клавиатурни събития
            if (this.stats.keyboardEvents < 3) {
                validationResult.isValid = false;
                validationResult.failures.push('insufficient_keyboard_events');
            }
            
            // Проверка на honeypot
            const honeypot = $(form).find('input[name^="fs_hp_"]');
            if (honeypot.length && honeypot.val()) {
                validationResult.isValid = false;
                validationResult.failures.push('honeypot_filled');
            }
            
            return validationResult;
        },
        
        showError: function(form, failures) {
            // Създаваме съобщение за грешка
            const errorDiv = $('<div>', {
                class: 'formshield-error',
                text: 'Sorry, we could not process your submission. Please try again.'
            }).css({
                color: '#dc3545',
                padding: '10px',
                marginBottom: '10px',
                border: '1px solid #dc3545',
                borderRadius: '4px',
                backgroundColor: '#fff'
            });
            
            // Добавяме го към формата
            $(form).prepend(errorDiv);
            
            // Скролваме до грешката
            $('html, body').animate({
                scrollTop: errorDiv.offset().top - 100
            }, 500);
            
            // Премахваме след 5 секунди
            setTimeout(() => errorDiv.fadeOut('slow', function() {
                $(this).remove();
            }), 5000);
        },
        
        logAttempt: function(form, validationResult) {
            const formData = {
                formId: $(form).attr('id') || 'unknown_form',
                timestamp: new Date().toISOString(),
                validationResult: validationResult,
                userAgent: navigator.userAgent,
                screenResolution: `${window.screen.width}x${window.screen.height}`,
                timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
            };
            
            // Изпращаме към сървъра
            $.ajax({
                url: formshieldData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'formshield_log_validation',
                    nonce: formshieldData.nonce,
                    log_data: formData
                },
                success: function(response) {
                },
                error: function(xhr, status, error) {
                    if (DEBUG) console.error('FormShield: Logging failed:', error);
                }
            });
        }
    };
    
    // Стартираме защитата
    FormShieldProtection.init();
});
