let flagBox = document.querySelector('.js-do-flag')
if (flagBox) {
    flagBox.querySelectorAll('select option').forEach(item => {
        if (item.selected) {
            let selectedFlag = item.getAttribute('data-flag');
            flagBox.querySelector(`.flag img.${selectedFlag}`).classList.remove('d-none')
        }
        item.addEventListener('click', function () {
            flagBox.querySelectorAll('.flag img').forEach(delActive => {
                delActive.classList.add('d-none')
            })
            if (item.selected) {
                let selectedFlag = item.getAttribute('data-flag');
                console.log(selectedFlag);
                
                flagBox.querySelector(`.flag img.${selectedFlag}`).classList.remove('d-none')
            }
        })
    })
}

// Form submission functionality
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('.marketing-register-box form');
    
    if (form) {
        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // Get form data
            const formData = {
                full_name: form.querySelector("input[name=\"full_name\"]").value.trim(),
                company_name: form.querySelector("input[name=\"company_name\"]").value.trim(),
                work_email: form.querySelector("input[name=\"work_email\"]").value.trim(),
                phone_number: form.querySelector("input[name=\"phone_number\"]").value.trim()
            };
            
            // Validate required fields
            const errors = [];
            if (!formData.full_name) errors.push('Full Name is required');
            if (!formData.company_name) errors.push('Company Name is required');
            if (!formData.work_email) errors.push('Work Email is required');
            if (!formData.phone_number) errors.push('Phone Number is required');
            
            // Email validation
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (formData.work_email && !emailRegex.test(formData.work_email)) {
                errors.push('Please enter a valid email address');
            }
            
            if (errors.length > 0) {
                showMessage(errors.join(', '), 'error');
                return;
            }
            
            // Show loading state
            const submitBtn = form.querySelector('input[type="submit"]');
            const originalValue = submitBtn.value;
            submitBtn.value = 'Submitting...';
            submitBtn.disabled = true;
            
            try {
                const response = await fetch('/api/v1/inquiries', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'accept': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    // Success
                    showMessage('Thank you! Your inquiry has been submitted successfully.', 'success');
                    form.reset();
                } else {
                    // Handle API errors
                    if (response.status === 400) {
                        showMessage('Bad request - Please check your input data.', 'error');
                    } else if (response.status === 422) {
                        const message = result.error?.message || 'Validation error - Please check your data format.';
                        showMessage(message, 'error');
                    } else if (response.status === 409 || (result.error && result.error.code === 'DUPLICATE_INQUIRY')) {
                        showMessage('You already have a pending inquiry with this email address. Please wait for it to be processed before submitting a new one.', 'error');
                    } else if (response.status === 500) {
                        showMessage('Internal server error - Please try again later.', 'error');
                    } else {
                        showMessage(result.message || 'An error occurred. Please try again.', 'error');
                    }
                }
            } catch (error) {
                console.error('Network error:', error);
                showMessage('Network error - Please check your connection and try again.', 'error');
            } finally {
                // Reset button state
                submitBtn.value = originalValue;
                submitBtn.disabled = false;
            }
        });
    }
});

// Function to show messages to user
function showMessage(message, type) {
    // Remove existing message if any
    const existingMessage = document.querySelector('.form-message');
    if (existingMessage) {
        existingMessage.remove();
    }
    
    // Create new message element
    const messageDiv = document.createElement('div');
    messageDiv.className = `form-message ${type}`;
    messageDiv.textContent = message;
    
    // Add styles
    messageDiv.style.cssText = `
        padding: 12px 16px;
        margin: 10px 0;
        border-radius: 4px;
        font-weight: 500;
        text-align: center;
        ${type === 'success' 
            ? 'background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;' 
            : 'background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;'
        }
    `;
    
    // Insert message above the form
    const form = document.querySelector('.marketing-register-box form');
    if (form) {
        form.parentNode.insertBefore(messageDiv, form);
        
        // Auto-remove success messages after 5 seconds
        if (type === 'success') {
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.remove();
                }
            }, 5000);
        }
    }
}
