/**
 * VMO AI Builder - Advanced Form Generation & Management
 * Automatically generates forms with validation, styling, and submission handling
 */

(function($) {
    'use strict';

    const VMO_SMS_CONSENT_DEFAULTS = {
        privacyUrl: '/privacy-policy.html',
        termsUrl: '/terms-of-service.html',
        supportText: 'Reply STOP to opt out and HELP for help.',
        ratesText: 'Message frequency varies. Message and data rates may apply.',
        purchaseText: 'Consent is not a condition of purchase.'
    };

    // === FORM GENERATION SYSTEM ===
    
    /**
     * Generate a form based on requirements
     */
    window.vmoGenerateForm = function(formType, options = {}) {
        console.log('VMO: Generating form:', formType, options);
        
        try {
            const formConfig = getFormConfig(formType, options);
            const formHTML = buildFormHTML(formConfig);
            const formCSS = buildFormCSS(formConfig);
            
            // Insert form into the page
            if (options.targetElement) {
                $(options.targetElement).html(formHTML);
            } else {
                // Insert at current selection or end of content
                insertFormIntoContent(formHTML);
            }
            
            // Apply custom CSS
            if (!$('#vmo-form-styles').length) {
                $('head').append(`<style id="vmo-form-styles">${formCSS}</style>`);
            }
            
            // Initialize form functionality
            initializeFormHandlers();
            ensurePhoneConsentCompliance(document);
            
            console.log('VMO: Form generated successfully');
            return formHTML;
            
        } catch (error) {
            console.error('VMO: Error generating form:', error);
            return null;
        }
    };
    
    /**
     * Form configuration templates
     */
    function getFormConfig(formType, options) {
        const configs = {
            contact: {
                title: 'Contact Us',
                description: 'Get in touch with us',
                fields: [
                    { type: 'text', name: 'name', label: 'Full Name', required: true, placeholder: 'Enter your full name' },
                    { type: 'email', name: 'email', label: 'Email Address', required: true, placeholder: 'your@email.com' },
                    { type: 'tel', name: 'phone', label: 'Phone Number', required: false, placeholder: '(555) 123-4567' },
                    { type: 'select', name: 'subject', label: 'Subject', required: true, options: ['General Inquiry', 'Support', 'Sales', 'Partnership'] },
                    { type: 'textarea', name: 'message', label: 'Message', required: true, placeholder: 'Tell us how we can help you...', rows: 5 }
                ],
                submitText: 'Send Message',
                style: 'modern',
                notification: true
            },
            
            newsletter: {
                title: 'Subscribe to Our Newsletter',
                description: 'Stay updated with our latest news and offers',
                fields: [
                    { type: 'email', name: 'email', label: 'Email Address', required: true, placeholder: 'Enter your email' },
                    { type: 'text', name: 'name', label: 'First Name', required: false, placeholder: 'Your first name' },
                    { type: 'checkbox', name: 'terms', label: 'I agree to receive marketing emails', required: true }
                ],
                submitText: 'Subscribe Now',
                style: 'compact',
                notification: true
            },
            
            booking: {
                title: 'Book an Appointment',
                description: 'Schedule a meeting with our team',
                fields: [
                    { type: 'text', name: 'name', label: 'Full Name', required: true, placeholder: 'Enter your name' },
                    { type: 'email', name: 'email', label: 'Email Address', required: true, placeholder: 'your@email.com' },
                    { type: 'tel', name: 'phone', label: 'Phone Number', required: true, placeholder: '(555) 123-4567' },
                    { type: 'date', name: 'date', label: 'Preferred Date', required: true },
                    { type: 'time', name: 'time', label: 'Preferred Time', required: true },
                    { type: 'select', name: 'service', label: 'Service Type', required: true, options: ['Consultation', 'Demo', 'Support', 'Training'] },
                    { type: 'textarea', name: 'notes', label: 'Additional Notes', required: false, placeholder: 'Any specific requirements...', rows: 3 }
                ],
                submitText: 'Book Appointment',
                style: 'professional',
                notification: true
            },
            
            survey: {
                title: 'Customer Feedback Survey',
                description: 'Help us improve our services',
                fields: [
                    { type: 'text', name: 'name', label: 'Name (Optional)', required: false, placeholder: 'Your name' },
                    { type: 'radio', name: 'satisfaction', label: 'Overall Satisfaction', required: true, options: ['Very Satisfied', 'Satisfied', 'Neutral', 'Dissatisfied', 'Very Dissatisfied'] },
                    { type: 'checkbox-group', name: 'features', label: 'Which features do you use most?', required: false, options: ['AI Generation', 'Media Library', 'Templates', 'SEO Tools', 'Form Builder'] },
                    { type: 'range', name: 'recommend', label: 'How likely are you to recommend us? (1-10)', required: true, min: 1, max: 10, value: 5 },
                    { type: 'textarea', name: 'feedback', label: 'Additional Feedback', required: false, placeholder: 'Share your thoughts...', rows: 4 }
                ],
                submitText: 'Submit Feedback',
                style: 'friendly',
                notification: true
            },
            
            quote: {
                title: 'Request a Quote',
                description: 'Get a custom quote for your project',
                fields: [
                    { type: 'text', name: 'company', label: 'Company Name', required: true, placeholder: 'Your company' },
                    { type: 'text', name: 'name', label: 'Contact Name', required: true, placeholder: 'Your full name' },
                    { type: 'email', name: 'email', label: 'Email Address', required: true, placeholder: 'business@email.com' },
                    { type: 'tel', name: 'phone', label: 'Phone Number', required: true, placeholder: '(555) 123-4567' },
                    { type: 'select', name: 'project_type', label: 'Project Type', required: true, options: ['Website Design', 'E-commerce', 'Mobile App', 'Branding', 'SEO Services'] },
                    { type: 'select', name: 'budget', label: 'Budget Range', required: true, options: ['Under $5,000', '$5,000 - $15,000', '$15,000 - $50,000', '$50,000+', 'To be discussed'] },
                    { type: 'date', name: 'timeline', label: 'Desired Completion Date', required: false },
                    { type: 'textarea', name: 'requirements', label: 'Project Requirements', required: true, placeholder: 'Describe your project in detail...', rows: 6 }
                ],
                submitText: 'Request Quote',
                style: 'corporate',
                notification: true
            }
        };
        
        // Merge with custom options
        return { ...configs[formType], ...options };
    }

    function getPhoneFieldConfig(config) {
        if (!config || !Array.isArray(config.fields)) {
            return null;
        }

        return config.fields.find(field => {
            const fieldName = (field.name || '').toLowerCase();
            return field.type === 'tel' || fieldName.includes('phone') || fieldName.includes('mobile');
        }) || null;
    }

    function resolveSmsConsentConfig(form = null) {
        const rootDocument = form && form.ownerDocument ? form.ownerDocument : document;
        const links = rootDocument ? Array.from(rootDocument.querySelectorAll('a[href]')) : [];
        const privacyLink = links.find(link => /privacy/i.test((link.textContent || '').trim()) || /privacy-policy/i.test(link.getAttribute('href') || ''));
        const termsLink = links.find(link => /terms/i.test((link.textContent || '').trim()) || /terms-of-service/i.test(link.getAttribute('href') || ''));

        return {
            privacyUrl: privacyLink ? privacyLink.href : VMO_SMS_CONSENT_DEFAULTS.privacyUrl,
            termsUrl: termsLink ? termsLink.href : VMO_SMS_CONSENT_DEFAULTS.termsUrl,
            supportText: VMO_SMS_CONSENT_DEFAULTS.supportText,
            ratesText: VMO_SMS_CONSENT_DEFAULTS.ratesText,
            purchaseText: VMO_SMS_CONSENT_DEFAULTS.purchaseText
        };
    }

    function buildPhoneConsentField(config, options = {}) {
        const phoneField = getPhoneFieldConfig(config);
        if (!phoneField) {
            return '';
        }

        const consent = { ...VMO_SMS_CONSENT_DEFAULTS, ...(options.smsConsent || {}) };
        const phoneRequired = !!phoneField.required;
        const consentLabel = phoneRequired
            ? 'I agree to receive recurring SMS/MMS messages at the number provided regarding my request, appointments, account updates, support, and occasional promotional messages where permitted.'
            : 'If I provide a mobile number, I agree to receive recurring SMS/MMS messages at the number provided regarding my request, appointments, account updates, support, and occasional promotional messages where permitted.';

        return `
            <div class="vmo-form-field field-sms-consent" data-vmo-phone-consent-block="1">
                <label class="checkbox-label vmo-consent-checkbox-label">
                    <input type="checkbox" name="sms_consent" value="1" data-vmo-phone-consent="1" data-vmo-phone-required="${phoneRequired ? '1' : '0'}" ${phoneRequired ? 'required' : ''}>
                    <span class="checkbox-custom"></span>
                    <span class="vmo-consent-copy">${consentLabel}</span>
                </label>
                <p class="vmo-phone-consent-disclosure">
                    <span>${consent.ratesText}</span>
                    <span>${consent.supportText}</span>
                    <span>${consent.purchaseText}</span>
                    <span>View <a href="${consent.privacyUrl}" data-vmo-privacy-link="1">Privacy Policy</a> and <a href="${consent.termsUrl}" data-vmo-terms-link="1">Terms of Service</a>.</span>
                </p>
            </div>
        `;
    }
    
    /**
     * Build form HTML
     */
    function buildFormHTML(config) {
        const formId = 'vmo-form-' + Date.now();
        const styleClass = `vmo-form-${config.style}`;
        const phoneField = getPhoneFieldConfig(config);
        
        let html = `
            <div class="vmo-form-container ${styleClass}" id="${formId}">
                <form class="vmo-form" data-form-type="${config.title}" ${phoneField ? 'data-vmo-phone-consent="1"' : ''}>
                    <div class="vmo-form-header">
                        <h3 class="vmo-form-title">${config.title}</h3>
                        ${config.description ? `<p class="vmo-form-description">${config.description}</p>` : ''}
                    </div>
                    
                    <div class="vmo-form-fields">
        `;
        
        // Generate fields
        config.fields.forEach(field => {
            html += generateFieldHTML(field);
        });

        html += buildPhoneConsentField(config);
        
        // Add submit button and footer
        html += `
                    </div>
                    
                    <div class="vmo-form-footer">
                        <button type="submit" class="vmo-form-submit">
                            <span class="submit-text">${config.submitText}</span>
                            <span class="submit-loader" style="display:none;">
                                <svg width="20" height="20" viewBox="0 0 24 24">
                                    <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-dasharray="32" stroke-dashoffset="32">
                                        <animate attributeName="stroke-dasharray" dur="2s" values="0 32;16 16;0 32;0 32" repeatCount="indefinite"/>
                                        <animate attributeName="stroke-dashoffset" dur="2s" values="0;-16;-32;-32" repeatCount="indefinite"/>
                                    </circle>
                                </svg>
                            </span>
                        </button>
                        
                        ${config.notification ? `
                        <div class="vmo-form-notification" style="display:none;">
                            <div class="notification-success">✅ Thank you! Your message has been sent successfully.</div>
                            <div class="notification-error">❌ Sorry, there was an error sending your message. Please try again.</div>
                        </div>
                        ` : ''}
                    </div>
                </form>
            </div>
        `;
        
        return html;
    }
    
    /**
     * Generate individual field HTML
     */
    function generateFieldHTML(field) {
        const fieldId = 'field-' + field.name + '-' + Date.now();
        const required = field.required ? 'required' : '';
        const requiredMark = field.required ? ' <span class="required">*</span>' : '';
        
        let fieldHTML = `<div class="vmo-form-field field-${field.type}">`;
        
        // Field label
        if (field.label) {
            fieldHTML += `<label for="${fieldId}" class="field-label">${field.label}${requiredMark}</label>`;
        }
        
        // Field input based on type
        switch (field.type) {
            case 'text':
            case 'email':
            case 'tel':
            case 'date':
            case 'time':
                fieldHTML += `<input type="${field.type}" id="${fieldId}" name="${field.name}" placeholder="${field.placeholder || ''}" ${required} class="field-input">`;
                break;
                
            case 'textarea':
                fieldHTML += `<textarea id="${fieldId}" name="${field.name}" placeholder="${field.placeholder || ''}" rows="${field.rows || 3}" ${required} class="field-input"></textarea>`;
                break;
                
            case 'select':
                fieldHTML += `<select id="${fieldId}" name="${field.name}" ${required} class="field-input">`;
                fieldHTML += `<option value="">Select ${field.label}</option>`;
                field.options.forEach(option => {
                    fieldHTML += `<option value="${option}">${option}</option>`;
                });
                fieldHTML += `</select>`;
                break;
                
            case 'radio':
                fieldHTML += `<div class="radio-group">`;
                field.options.forEach((option, index) => {
                    const radioId = `${fieldId}-${index}`;
                    fieldHTML += `
                        <label class="radio-label">
                            <input type="radio" id="${radioId}" name="${field.name}" value="${option}" ${required}>
                            <span class="radio-custom"></span>
                            ${option}
                        </label>
                    `;
                });
                fieldHTML += `</div>`;
                break;
                
            case 'checkbox':
                fieldHTML += `
                    <label class="checkbox-label">
                        <input type="checkbox" id="${fieldId}" name="${field.name}" value="1" ${required}>
                        <span class="checkbox-custom"></span>
                        ${field.label}
                    </label>
                `;
                break;
                
            case 'checkbox-group':
                fieldHTML += `<div class="checkbox-group">`;
                field.options.forEach((option, index) => {
                    const checkboxId = `${fieldId}-${index}`;
                    fieldHTML += `
                        <label class="checkbox-label">
                            <input type="checkbox" id="${checkboxId}" name="${field.name}[]" value="${option}">
                            <span class="checkbox-custom"></span>
                            ${option}
                        </label>
                    `;
                });
                fieldHTML += `</div>`;
                break;
                
            case 'range':
                fieldHTML += `
                    <div class="range-container">
                        <input type="range" id="${fieldId}" name="${field.name}" min="${field.min || 1}" max="${field.max || 10}" value="${field.value || 5}" ${required} class="field-input range-input">
                        <div class="range-value">
                            <span class="range-min">${field.min || 1}</span>
                            <span class="range-current">${field.value || 5}</span>
                            <span class="range-max">${field.max || 10}</span>
                        </div>
                    </div>
                `;
                break;
        }
        
        fieldHTML += `</div>`;
        return fieldHTML;
    }
    
    /**
     * Build form CSS styles
     */
    function buildFormCSS(config) {
        return `
            .vmo-form-container {
                max-width: 600px;
                margin: 2rem auto;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                line-height: 1.6;
            }
            
            .vmo-form {
                background: white;
                border-radius: 12px;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                overflow: hidden;
            }
            
            .vmo-form-header {
                padding: 2rem 2rem 1rem;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                text-align: center;
            }
            
            .vmo-form-title {
                margin: 0 0 0.5rem;
                font-size: 1.8rem;
                font-weight: 600;
            }
            
            .vmo-form-description {
                margin: 0;
                opacity: 0.9;
                font-size: 1rem;
            }
            
            .vmo-form-fields {
                padding: 2rem;
            }
            
            .vmo-form-field {
                margin-bottom: 1.5rem;
            }
            
            .field-label {
                display: block;
                margin-bottom: 0.5rem;
                font-weight: 500;
                color: #374151;
            }
            
            .required {
                color: #ef4444;
            }
            
            .field-input {
                width: 100%;
                padding: 0.75rem;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 1rem;
                transition: all 0.3s ease;
                box-sizing: border-box;
            }
            
            .field-input:focus {
                outline: none;
                border-color: #667eea;
                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }
            
            .field-input:invalid {
                border-color: #ef4444;
            }
            
            /* Radio and Checkbox Styles */
            .radio-group, .checkbox-group {
                display: flex;
                flex-direction: column;
                gap: 0.75rem;
            }
            
            .radio-label, .checkbox-label {
                display: flex;
                align-items: center;
                cursor: pointer;
                font-weight: normal;
                margin-bottom: 0;
            }
            
            .radio-custom, .checkbox-custom {
                width: 20px;
                height: 20px;
                border: 2px solid #e5e7eb;
                margin-right: 0.75rem;
                position: relative;
                transition: all 0.3s ease;
            }
            
            .radio-custom {
                border-radius: 50%;
            }
            
            .checkbox-custom {
                border-radius: 4px;
            }
            
            input[type="radio"]:checked + .radio-custom::after {
                content: '';
                width: 8px;
                height: 8px;
                background: #667eea;
                border-radius: 50%;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
            
            input[type="checkbox"]:checked + .checkbox-custom::after {
                content: '✓';
                color: white;
                font-size: 14px;
                font-weight: bold;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
            
            input[type="radio"]:checked + .radio-custom,
            input[type="checkbox"]:checked + .checkbox-custom {
                background: #667eea;
                border-color: #667eea;
            }
            
            input[type="radio"], input[type="checkbox"] {
                display: none;
            }
            
            /* Range Slider */
            .range-container {
                padding: 0.5rem 0;
            }
            
            .range-input {
                width: 100%;
                height: 8px;
                border-radius: 4px;
                background: #e5e7eb;
                outline: none;
                -webkit-appearance: none;
            }
            
            .range-input::-webkit-slider-thumb {
                appearance: none;
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background: #667eea;
                cursor: pointer;
            }
            
            .range-value {
                display: flex;
                justify-content: space-between;
                margin-top: 0.5rem;
                font-size: 0.875rem;
                color: #6b7280;
            }
            
            .range-current {
                font-weight: 600;
                color: #667eea;
            }
            
            /* Submit Button */
            .vmo-form-footer {
                padding: 0 2rem 2rem;
            }
            
            .vmo-form-submit {
                width: 100%;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                padding: 1rem 2rem;
                border-radius: 8px;
                font-size: 1rem;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 0.5rem;
            }
            
            .vmo-form-submit:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
            }
            
            .vmo-form-submit:disabled {
                opacity: 0.7;
                cursor: not-allowed;
                transform: none;
            }
            
            /* Notifications */
            .vmo-form-notification {
                margin-top: 1rem;
                padding: 1rem;
                border-radius: 8px;
                text-align: center;
            }
            
            .notification-success {
                background: #dcfce7;
                color: #166534;
                border: 1px solid #bbf7d0;
            }
            
            .notification-error {
                background: #fef2f2;
                color: #991b1b;
                border: 1px solid #fecaca;
                display: none;
            }

            .field-sms-consent {
                padding: 1rem;
                border: 1px solid #e5e7eb;
                border-radius: 10px;
                background: #f8fafc;
            }

            .vmo-consent-checkbox-label {
                align-items: flex-start;
                gap: 0.75rem;
            }

            .vmo-consent-checkbox-label .checkbox-custom {
                flex: 0 0 20px;
                margin-right: 0;
                margin-top: 0.15rem;
            }

            .vmo-consent-copy {
                color: #1f2937;
                font-size: 0.95rem;
                line-height: 1.6;
            }

            .vmo-phone-consent-disclosure {
                margin: 0.75rem 0 0;
                color: #4b5563;
                font-size: 0.85rem;
                line-height: 1.7;
            }

            .vmo-phone-consent-disclosure span {
                display: inline;
                margin-right: 0.35rem;
            }

            .vmo-phone-consent-disclosure a {
                color: #4338ca;
                text-decoration: underline;
            }

            .field-input.error,
            .field-sms-consent.error {
                border-color: #ef4444;
                box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.08);
            }
            
            /* Responsive Design */
            @media (max-width: 768px) {
                .vmo-form-container {
                    margin: 1rem;
                }
                
                .vmo-form-header,
                .vmo-form-fields,
                .vmo-form-footer {
                    padding-left: 1rem;
                    padding-right: 1rem;
                }
                
                .radio-group, .checkbox-group {
                    gap: 0.5rem;
                }
            }
            
            /* Style Variations */
            .vmo-form-compact .vmo-form {
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            
            .vmo-form-compact .vmo-form-header {
                padding: 1.5rem 2rem 1rem;
            }
            
            .vmo-form-professional .vmo-form-header {
                background: linear-gradient(135deg, #1f2937 0%, #374151 100%);
            }
            
            .vmo-form-friendly .vmo-form-header {
                background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            }
            
            .vmo-form-corporate .vmo-form-header {
                background: linear-gradient(135deg, #1e40af 0%, #1d4ed8 100%);
            }
        `;
    }
    
    /**
     * Insert form into content
     */
    function insertFormIntoContent(formHTML) {
        const iframe = document.getElementById('vmo-preview-iframe');
        if (iframe && iframe.contentDocument) {
            const doc = iframe.contentDocument;
            const body = doc.body;
            
            // Try to insert at a good location
            let insertTarget = body.querySelector('.content, main, .main, #content, #main');
            if (!insertTarget) {
                insertTarget = body;
            }
            
            // Create a section for the form
            const formSection = doc.createElement('section');
            formSection.className = 'vmo-generated-form-section';
            formSection.style.cssText = 'padding: 4rem 2rem; background: #f9fafb;';
            formSection.innerHTML = formHTML;
            
            insertTarget.appendChild(formSection);
            ensurePhoneConsentCompliance(doc);
            
            console.log('VMO: Form inserted into content');
        }
    }
    
    /**
     * Initialize form handlers
     */
    function isPhoneLikeInput(input) {
        if (!(input instanceof HTMLInputElement)) {
            return false;
        }

        if (String(input.type || '').toLowerCase() === 'tel') {
            return true;
        }

        const lookup = `${input.name || ''} ${input.id || ''}`.toLowerCase();
        return lookup.includes('phone') || lookup.includes('mobile');
    }

    function initializeFormHandlers() {
        $(document).off('submit', '.vmo-form, form[data-vmo-form]').on('submit', '.vmo-form, form[data-vmo-form]', handleFormSubmit);
        $(document).off('input', '.range-input').on('input', '.range-input', handleRangeInput);
        $(document).off('change', '.field-input').on('change', '.field-input', handleFieldValidation);
        $(document)
            .off('.vmoPhoneConsent')
            .on('input.vmoPhoneConsent change.vmoPhoneConsent', 'input', function() {
                if (isPhoneLikeInput(this)) {
                    syncPhoneConsentState.call(this);
                }
            });
        $(document).off('change', '[data-vmo-phone-consent="1"]').on('change', '[data-vmo-phone-consent="1"]', handleFieldValidation);

        if (!window.vmoPhoneConsentSubmitHandlerBound) {
            document.addEventListener('submit', handlePhoneConsentSubmit, true);
            window.vmoPhoneConsentSubmitHandlerBound = true;
        }
    }

    function getPhoneInputs(form) {
        return form.find('input').filter(function() {
            if (!isPhoneLikeInput(this)) {
                return false;
            }
            return this.type !== 'hidden';
        });
    }

    function formHasPhoneValue(form) {
        return getPhoneInputs(form).toArray().some(input => String($(input).val() || '').trim() !== '');
    }

    function syncPhoneConsentState() {
        const form = $(this).closest('form');
        const consentField = form.find('[data-vmo-phone-consent="1"]').first();
        if (!consentField.length) {
            return;
        }

        const shouldRequireConsent = formHasPhoneValue(form);
        const phoneRequired = consentField.data('vmo-phone-required') === 1 || consentField.data('vmo-phone-required') === '1';
        consentField.prop('required', phoneRequired || shouldRequireConsent);

        if (!shouldRequireConsent && !phoneRequired) {
            consentField[0].setCustomValidity('');
            consentField.closest('.field-sms-consent').removeClass('error');
        }
    }

    function validatePhoneConsent(form) {
        const consentField = form.find('[data-vmo-phone-consent="1"]').first();
        if (!consentField.length) {
            return true;
        }

        const phoneRequired = consentField.data('vmo-phone-required') === 1 || consentField.data('vmo-phone-required') === '1';
        const phoneProvided = formHasPhoneValue(form);
        const mustConsent = phoneRequired || phoneProvided;
        const consentWrapper = consentField.closest('.field-sms-consent');

        if (mustConsent && !consentField.is(':checked')) {
            consentField[0].setCustomValidity('Please agree to the SMS terms before submitting a phone number.');
            consentWrapper.addClass('error');
            consentField[0].reportValidity();
            return false;
        }

        consentField[0].setCustomValidity('');
        consentWrapper.removeClass('error');
        return true;
    }

    function handlePhoneConsentSubmit(event) {
        const formEl = event.target;
        if (!(formEl instanceof HTMLFormElement)) {
            return;
        }

        const rootDocument = formEl.ownerDocument;
        if (rootDocument && rootDocument.body && rootDocument.body.classList.contains('wp-admin')) {
            return;
        }

        const form = $(formEl);
        if (!getPhoneInputs(form).length) {
            return;
        }

        if (!validatePhoneConsent(form)) {
            event.preventDefault();
            event.stopPropagation();
        }
    }

    function getFormSecurityValue(form, keys) {
        for (const key of keys) {
            const dataValue = form.data(key);
            if (dataValue !== undefined && dataValue !== null && String(dataValue) !== '') {
                return dataValue;
            }

            const attrValue = form.attr('data-' + String(key).replace(/[A-Z]/g, match => '-' + match.toLowerCase()).replace(/_/g, '-'));
            if (attrValue !== undefined && attrValue !== null && String(attrValue) !== '') {
                return attrValue;
            }

            const hiddenValue = form.find('[name="' + key + '"]').first().val();
            if (hiddenValue !== undefined && hiddenValue !== null && String(hiddenValue) !== '') {
                return hiddenValue;
            }

            if (typeof vmo_form_config !== 'undefined' && vmo_form_config && vmo_form_config[key]) {
                return vmo_form_config[key];
            }
        }
        return '';
    }

    function ensurePhoneConsentCompliance(rootDocument = document) {
        if (!rootDocument || !rootDocument.body || rootDocument.body.classList.contains('wp-admin')) {
            return;
        }

        const forms = rootDocument.querySelectorAll('form');
        forms.forEach(formEl => {
            const form = $(formEl);
            const phoneInputs = getPhoneInputs(form);
            if (!phoneInputs.length) {
                return;
            }

            form.attr('data-vmo-phone-consent', '1');

            const phoneRequired = phoneInputs.toArray().some(input => input.required);
            let consentField = form.find('[data-vmo-phone-consent="1"]').first();

            if (!consentField.length) {
                const consentConfig = resolveSmsConsentConfig(formEl);
                const consentHTML = buildPhoneConsentField({
                    fields: [{ type: 'tel', name: phoneInputs.first().attr('name') || 'phone', required: phoneRequired }]
                }, { smsConsent: consentConfig });

                const submitGroup = form.find('button[type="submit"], input[type="submit"], .vmo-form-submit').last().closest('.vmo-form-footer, .form-actions, p, div');
                if (submitGroup.length) {
                    submitGroup.before(consentHTML);
                } else {
                    form.append(consentHTML);
                }

                consentField = form.find('[data-vmo-phone-consent="1"]').first();
            }

            const consentConfig = resolveSmsConsentConfig(formEl);
            form.find('[data-vmo-privacy-link="1"]').attr('href', consentConfig.privacyUrl);
            form.find('[data-vmo-terms-link="1"]').attr('href', consentConfig.termsUrl);
            consentField.attr('data-vmo-phone-required', phoneRequired ? '1' : '0');
            consentField.prop('required', phoneRequired || formHasPhoneValue(form));
            syncPhoneConsentState.call(phoneInputs.first());
        });
    }
    
    /**
     * Handle form submission
     */
    function handleFormSubmit(e) {
        e.preventDefault();
        
        const form = $(this);
        const submitBtn = form.find('.vmo-form-submit, button[type="submit"], input[type="submit"]').first();
        const submitText = submitBtn.find('.submit-text');
        const submitLoader = submitBtn.find('.submit-loader');
        const notification = form.find('.vmo-form-notification');
        
        // Validate form
        if (!validateForm(form)) {
            return false;
        }
        
        // Show loading state
        submitBtn.prop('disabled', true);
        submitText.hide();
        submitLoader.show();
        
        // Collect form data
        const formData = collectFormData(form);
        const formType = form.data('form-type') || form.attr('data-form-type') || form.data('vmo-form') || form.attr('data-vmo-form') || 'contact';
        
        console.log('VMO: Form submitted:', formType, formData);

        // Resolve the AJAX URL — published sites embed it as a data attribute or global
        const ajaxUrl = form.data('ajax-url')
            || (typeof vmo_ajax !== 'undefined' && vmo_ajax.ajaxurl)
            || (typeof vmo_form_config !== 'undefined' && vmo_form_config.ajaxurl)
            || '/wp-admin/admin-ajax.php';

        const siteOwner = form.data('site-owner')
            || (typeof vmo_form_config !== 'undefined' && vmo_form_config.site_owner)
            || 0;

        const formId = getFormSecurityValue(form, ['form_id', 'formId', 'vmo_form'])
            || form.attr('id')
            || formType;
        const nonce = (typeof vmo_ajax !== 'undefined' && vmo_ajax.nonce)
            || (typeof vmoAjax !== 'undefined' && vmoAjax.nonce)
            || getFormSecurityValue(form, ['security', 'nonce'])
            || '';
        const requestData = {
            action: 'vmo_submit_form',
            form_type: formType,
            form_id: formId,
            site_owner: siteOwner,
            form_data: JSON.stringify(formData)
        };

        if (nonce) {
            requestData.security = nonce;
            requestData.nonce = nonce;
        }

        ['form_contract', 'form_token', 'vmo_form_token', 'form_signature', 'form_timestamp'].forEach(key => {
            const value = getFormSecurityValue(form, [key]);
            if (value !== '') {
                requestData[key] = value;
            }
        });

        // Submit to backend
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: requestData,
            timeout: 15000,
            success: function(response) {
                submitBtn.prop('disabled', false);
                submitText.show();
                submitLoader.hide();

                if (response && response.success) {
                    // Show success notification
                    if (notification.length) {
                        notification.show();
                        notification.find('.notification-success').show();
                        notification.find('.notification-error').hide();
                        form[0].reset();
                        setTimeout(() => { notification.fadeOut(); }, 5000);
                    }
                } else {
                    // Show error notification
                    if (notification.length) {
                        notification.show();
                        notification.find('.notification-error').show().text(
                            (response && response.data && response.data.message) || 'Something went wrong. Please try again.'
                        );
                        notification.find('.notification-success').hide();
                        setTimeout(() => { notification.fadeOut(); }, 5000);
                    }
                }

                // Track submission
                if (window.vmoTrackEvent) {
                    window.vmoTrackEvent('form_submit', {
                        form_type: formType,
                        fields_count: Object.keys(formData).length,
                        success: !!(response && response.success)
                    });
                }
            },
            error: function() {
                submitBtn.prop('disabled', false);
                submitText.show();
                submitLoader.hide();

                if (notification.length) {
                    notification.show();
                    notification.find('.notification-error').show().text('Network error. Please check your connection and try again.');
                    notification.find('.notification-success').hide();
                    setTimeout(() => { notification.fadeOut(); }, 5000);
                }
            }
        });
        
        return false;
    }
    
    /**
     * Validate form
     */
    function validateForm(form) {
        let isValid = true;
        
        form.find('[required]').each(function() {
            const field = $(this);
            const type = (field.attr('type') || '').toLowerCase();
            const value = String(field.val() || '').trim();

            if (type === 'checkbox') {
                if (!field.is(':checked')) {
                    field.closest('.field-sms-consent, .vmo-form-field').addClass('error');
                    isValid = false;
                } else {
                    field.closest('.field-sms-consent, .vmo-form-field').removeClass('error');
                }
                return;
            }

            if (type === 'radio') {
                const group = form.find(`[name="${field.attr('name')}"]`);
                if (!group.is(':checked')) {
                    field.closest('.vmo-form-field').addClass('error');
                    isValid = false;
                } else {
                    field.closest('.vmo-form-field').removeClass('error');
                }
                return;
            }
            
            if (!value) {
                field.addClass('error');
                isValid = false;
            } else {
                field.removeClass('error');
            }
            
            // Email validation
            if (field.attr('type') === 'email' && value) {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(value)) {
                    field.addClass('error');
                    isValid = false;
                }
            }
        });

        if (!validatePhoneConsent(form)) {
            isValid = false;
        }
        
        return isValid;
    }
    
    /**
     * Collect form data
     */
    function collectFormData(form) {
        const data = {};
        
        form.find('[name]').each(function() {
            const field = $(this);
            const name = field.attr('name');
            const type = field.attr('type');
            
            if (type === 'checkbox') {
                if (name.includes('[]')) {
                    // Checkbox group
                    const baseName = name.replace('[]', '');
                    if (!data[baseName]) data[baseName] = [];
                    if (field.is(':checked')) {
                        data[baseName].push(field.val());
                    }
                } else {
                    // Single checkbox
                    data[name] = field.is(':checked');
                }
            } else if (type === 'radio') {
                if (field.is(':checked')) {
                    data[name] = field.val();
                }
            } else {
                data[name] = field.val();
            }
        });
        
        return data;
    }
    
    /**
     * Handle range input changes
     */
    function handleRangeInput() {
        const range = $(this);
        const container = range.closest('.range-container');
        const current = container.find('.range-current');
        
        current.text(range.val());
    }
    
    /**
     * Handle field validation
     */
    function handleFieldValidation() {
        const field = $(this);
        field.removeClass('error');
        field.closest('.field-sms-consent, .vmo-form-field').removeClass('error');

        if (field.is('[data-vmo-phone-consent="1"]')) {
            field[0].setCustomValidity('');
        }
    }
    
    /**
     * Quick form insertion buttons
     */
    window.vmoShowFormMenu = function() {
        const formTypes = [
            { type: 'contact', icon: '📧', title: 'Contact Form', desc: 'Get in touch form with validation' },
            { type: 'newsletter', icon: '📰', title: 'Newsletter Signup', desc: 'Email subscription form' },
            { type: 'booking', icon: '📅', title: 'Booking Form', desc: 'Appointment scheduling form' },
            { type: 'survey', icon: '📊', title: 'Survey Form', desc: 'Customer feedback survey' },
            { type: 'quote', icon: '💰', title: 'Quote Request', desc: 'Get custom pricing quote' }
        ];
        
        let menuHTML = `
            <div id="vmo-form-menu" style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:white;border-radius:12px;box-shadow:0 20px 40px rgba(0,0,0,0.3);z-index:10000;max-width:500px;width:90%;">
                <div style="padding:2rem;border-bottom:1px solid #eee;">
                    <h3 style="margin:0;color:#333;">Insert Form</h3>
                    <p style="margin:0.5rem 0 0;color:#666;">Choose a form type to add to your page</p>
                    <button onclick="$('#vmo-form-menu').remove()" style="position:absolute;top:1rem;right:1rem;background:none;border:none;font-size:1.5rem;cursor:pointer;">×</button>
                </div>
                <div style="padding:1rem;">
        `;
        
        formTypes.forEach(form => {
            menuHTML += `
                <div onclick="$('#vmo-form-menu').remove(); vmoGenerateForm('${form.type}')" style="display:flex;align-items:center;padding:1rem;border-radius:8px;cursor:pointer;transition:background 0.2s;margin-bottom:0.5rem;" onmouseover="this.style.background='#f8f9fa'" onmouseout="this.style.background='transparent'">
                    <div style="font-size:2rem;margin-right:1rem;">${form.icon}</div>
                    <div>
                        <div style="font-weight:600;color:#333;">${form.title}</div>
                        <div style="font-size:0.875rem;color:#666;">${form.desc}</div>
                    </div>
                </div>
            `;
        });
        
        menuHTML += `
                </div>
            </div>
        `;
        
        $('body').append(menuHTML);
    };

    $(function() {
        initializeFormHandlers();
        ensurePhoneConsentCompliance(document);
    });

})(jQuery);
