
    (function () {

        // ================== SETTINGS ==================
        var ALLOWED_EXT = ['pdf', 'dwg', 'step', 'stl', 'iges'];
        var MAX_FILE_MB = 10;

        var DANGEROUS = [
            /<script/i,       /<\/script/i,     /onerror/i,
            /onload/i,        /javascript:/i,   /'\s*OR\s*1=1/i,
            /DROP\s+TABLE/i,  /UNION\s+SELECT/i, /--/,
            /;\s*--/,         /xp_cmdshell/i
        ];

        // For names, company, general text — letters, numbers, spaces, . - , ( )
        var SPECIAL_CHARS_TEXT = /[^a-zA-Z0-9\s.\-,()]/;

        // For phone fields — digits, spaces, + - ( )
        var SPECIAL_CHARS_TEL = /[^0-9\s+\-()]/;

        // For textarea — more lenient, allow @ # : / . etc for addresses/descriptions
        var SPECIAL_CHARS_TEXTAREA = /[^a-zA-Z0-9\s@._+\-,()#:\/]/;

        // ✅ Valid email format
        var EMAIL_REGEX = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;

        // ✅ Allowed email domains — add your own business domains here
        var ALLOWED_EMAIL_DOMAINS = [];
        // =============================================

        var _secured = {};

        // ================== HELPERS ==================

        function _err(input) {
            var e = input.parentNode.querySelector('.hs-custom-error');
            if (!e) {
                e = document.createElement('div');
                e.className     = 'hs-custom-error';
                e.style.cssText = 'color:#d32f2f;font-size:13px;margin-top:6px;display:none';
                input.parentNode.appendChild(e);
            }
            return e;
        }

        function _show(e, msg) {
            e.textContent   = msg;
            e.style.display = 'block';
        }

        function _hide(e) {
            e.style.display = 'none';
        }

        function _bad(val) {
            return DANGEROUS.some(function(p) { return p.test(val); });
        }

        function _hasSpecialChars(val, type) {
            if (type === 'tel')      return SPECIAL_CHARS_TEL.test(val);
            if (type === 'textarea') return SPECIAL_CHARS_TEXTAREA.test(val);
            return SPECIAL_CHARS_TEXT.test(val);
        }

        function _cleanSpecialChars(val, type) {
            if (type === 'tel')      return val.replace(/[^0-9\s+\-()]/g, '');
            if (type === 'textarea') return val.replace(/[^a-zA-Z0-9\s@._+\-,()#:\/]/g, '');
            return val.replace(/[^a-zA-Z0-9\s.\-,()]/g, '');
        }

        // ✅ Check email format
        function _validEmailFormat(val) {
            return EMAIL_REGEX.test(val);
        }

        // ✅ Check email domain is in allowed list
        function _validEmailDomain(val) {
            if (!ALLOWED_EMAIL_DOMAINS.length) return true;
            var parts = val.split('@');
            if (parts.length !== 2) return false;
            var domain = parts[1].toLowerCase();
            return ALLOWED_EMAIL_DOMAINS.indexOf(domain) !== -1;
        }

        // ================== SECURE ONE FORM ==================

        function secureForm(form) {

            // ── 1. File upload protection ──────────────────────────
            var fileInputs = form.querySelectorAll('input[type="file"]');

            fileInputs.forEach(function(input) {
                var err = _err(input);

                input.setAttribute('accept', ALLOWED_EXT.map(function(e) { return '.' + e; }).join(','));
                input.dataset.valid = 'true';

                input.addEventListener('change', function() {
                    var file = this.files[0];
                    if (!file) { _hide(err); return; }

                    var ext = file.name.split('.').pop().toLowerCase();
                    var mb  = (file.size / (1024 * 1024)).toFixed(2);

                    _hide(err);
                    input.dataset.valid = 'true';

                    if (!ALLOWED_EXT.includes(ext)) {
                        _show(err, 'Invalid file type. Allowed: ' + ALLOWED_EXT.join(', '));
                        this.value = '';
                        input.dataset.valid = 'false';
                        return;
                    }

                    if (parseFloat(mb) > MAX_FILE_MB) {
                        _show(err, 'File too large (' + mb + ' MB). Max: ' + MAX_FILE_MB + ' MB');
                        this.value = '';
                        input.dataset.valid = 'false';
                        return;
                    }

                    input.dataset.valid = 'true';
                });

                input.addEventListener('click', function() { _hide(err); });
            });

            // ✅ Block form submit if invalid file was attempted
            form.addEventListener('submit', function(e) {
                fileInputs.forEach(function(input) {
                    if (input.dataset.valid === 'false') {
                        e.preventDefault();
                        e.stopPropagation();
                        var errorDiv = input.parentNode.querySelector('.hs-custom-error');
                        if (errorDiv) {
                            _show(errorDiv, 'Please upload a valid file before submitting.');
                        }
                    }
                });
            }, true);

            // ── 2. Text / email / tel / textarea protection ────────
            form.querySelectorAll(
                'input[type="text"], input[type="email"], textarea, input[type="tel"]'
            ).forEach(function(input) {
                var err  = _err(input);
                var type = input.tagName.toLowerCase() === 'textarea'
                    ? 'textarea'
                    : (input.getAttribute('type') || 'text');

                // ✅ EMAIL FIELD — special handling
                if (type === 'email') {

                    input.addEventListener('input', function() {
                        var val = this.value;
                        if (_bad(val)) {
                            _show(err, 'Invalid input. Scripts are not allowed.');
                            this.value = val.replace(/[<>'";\\/]/g, '');
                        } else {
                            _hide(err);
                        }
                    });

                    input.addEventListener('blur', function() {
                        var val = this.value.trim();
                        if (!val) return;

                        if (_bad(val)) {
                            _show(err, 'Invalid input detected.');
                            this.value = '';
                            return;
                        }
                        if (!_validEmailFormat(val)) {
                            _show(err, 'Please enter a valid email address (e.g. name@domain.com).');
                            return;
                        }
                        if (!_validEmailDomain(val)) {
                            _show(err, 'Email domain not allowed. Please use a valid email provider.');
                            return;
                        }
                        _hide(err);
                    });

                    return;
                }

                // ✅ ALL OTHER FIELDS (text / tel / textarea)
                input.addEventListener('input', function() {
                    var val = this.value;

                    if (_bad(val)) {
                        _show(err, 'Invalid input. Scripts are not allowed.');
                        this.value = _cleanSpecialChars(val.replace(/[<>'";\\/]/g, ''), type);
                        return;
                    }

                    if (_hasSpecialChars(val, type)) {
                        _show(err, 'Special characters are not allowed in this field.');
                        this.value = _cleanSpecialChars(val, type);
                        return;
                    }

                    _hide(err);
                });

                input.addEventListener('blur', function() {
                    var val = this.value;
                    if (_bad(val) || _hasSpecialChars(val, type)) {
                        _show(err, 'Invalid input detected. Please remove special characters.');
                        this.value = _cleanSpecialChars(val, type);
                    }
                });
            });
        }

        // ================== LISTEN FOR HUBSPOT READY ==================

        window.addEventListener('message', function(event) {
            if (!event.data || typeof event.data !== 'object') return;

            if (
                event.data.type      === 'hsFormCallback' &&
                event.data.eventName === 'onFormReady'
            ) {
                var formId = event.data.id;
                if (!formId) return;

                if (_secured[formId]) return;

                var form = document.querySelector('#hsForm_' + formId);
                if (!form) return;

                secureForm(form);
                _secured[formId] = true;
            }
        });

    })();
    