window.FormShieldProtection = {
    mouseMovements: 0,
    keyboardEvents: 0,
    formStartTime: 0,
    honeypotFields: {},
    
    init: function() {
        this.addEventListeners();
        this.injectHoneypots();
    },
    
    addEventListeners: function() {
        document.addEventListener('mousemove', this.handleMouseMove.bind(this));
        document.addEventListener('keydown', this.handleKeyboard.bind(this));
        
        // Отслеживаем фокус на формах
        document.addEventListener('focusin', function(e) {
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
                if (!this.formStartTime) {
                    this.formStartTime = Date.now();
                }
            }
        }.bind(this));
    },
    
    handleMouseMove: function() {
        this.mouseMovements++;
    },
    
    handleKeyboard: function() {
        this.keyboardEvents++;
    },
    
    injectHoneypots: function() {
        // Добавяме скрити полета във всички форми
        document.querySelectorAll('form').forEach(function(form) {
            const honeypot = document.createElement('input');
            const fieldName = 'fs_hp_' + Math.random().toString(36).substr(2, 9);
            
            honeypot.type = 'text';
            honeypot.name = fieldName;
            honeypot.style.opacity = '0';
            honeypot.style.position = 'absolute';
            honeypot.style.height = '0';
            honeypot.style.width = '0';
            honeypot.style.zIndex = '-1';
            honeypot.setAttribute('tabindex', '-1');
            honeypot.setAttribute('autocomplete', 'off');
            
            form.appendChild(honeypot);
            this.honeypotFields[form.id || form.getAttribute('data-form-id')] = fieldName;
        }.bind(this));
    },
    
    validateSubmission: function(form) {
        const validationData = {
            mouseMovements: this.mouseMovements,
            keyboardEvents: this.keyboardEvents,
            timeTaken: this.formStartTime ? (Date.now() - this.formStartTime) : 0,
            honeypotValue: '',
            formId: form.id || form.getAttribute('data-form-id'),
            validationFailures: []
        };
        
        // Проверка за минимално време
        if (validationData.timeTaken < 3000) {
            validationData.validationFailures.push('too_fast');
        }
        
        // Проверка за движения на мишката
        if (this.mouseMovements < 5) {
            validationData.validationFailures.push('no_mouse_movement');
        }
        
        // Проверка за клавиатурни събития
        if (this.keyboardEvents < 3) {
            validationData.validationFailures.push('no_keyboard_events');
        }
        
        // Проверка на honeypot
        const honeypotField = form.querySelector('[name="' + this.honeypotFields[validationData.formId] + '"]');
        if (honeypotField && honeypotField.value) {
            validationData.validationFailures.push('honeypot_filled');
            validationData.honeypotValue = honeypotField.value;
        }
        
        // Записваме резултата
        this.logValidationResult(validationData);
        
        return validationData.validationFailures.length === 0;
    },
    
    logValidationResult: function(validationData) {
        // Изпращаме данните към сървъра за логване
        jQuery.post(ajaxurl, {
            action: 'formshield_log_validation',
            nonce: formshieldData.nonce,
            validation_data: validationData
        });
    }
};

// Инициализираме защитата
jQuery(document).ready(function() {
    FormShieldProtection.init();
});
