/**
 * Frontend JavaScript for SPAI Contact Form
 */

(function($) {
    'use strict';
    
    // Phone input instances - needs to be in outer scope
    var phoneInputInstances = {};
    window.phoneInputInstances = phoneInputInstances; // Make it accessible globally for debugging

    $(document).ready(function() {
        // Initialize phone inputs
        initializePhoneInputs();
        
        // Initialize multichoice fields
        initializeMultichoiceFields();
        
        // Initialize marketing data auto-population
        initializeMarketingDataFields();
        
        // Track user interactions to detect real users vs bots
        $('.spai-form').on('input change click', 'input, select, textarea', function() {
            $(this).closest('.spai-form').data('lastInteraction', Date.now());
        });
        
        // Handle form submission
        $('.spai-form').on('submit', function(e) {
            e.preventDefault();
            
            var $form = $(this);
            var $button = $form.find('.spai-submit-button');
            var $message = $form.find('.spai-message-bottom');
            
            // Clear previous messages
            $message.removeClass('success error').empty().hide();
            
            // Validate form
            if (!validateForm($form)) {
                return false;
            }
            
            // Function to submit the form
            var submitForm = function(recaptchaToken) {
                console.log('Starting form submission...');
                
                // First, update phone fields to E164 format BEFORE creating FormData
                $form.find('input[type="tel"]').each(function() {
                    var $field = $(this);
                    var fieldId = $field.attr('id');
                    var phoneInstance = phoneInputInstances[fieldId];
                    
                    console.log('Processing phone field:', fieldId);
                    console.log('Current value:', $field.val());
                    console.log('Phone instance exists:', !!phoneInstance);
                    
                    if (phoneInstance && typeof phoneInstance.getNumber === 'function') {
                        var e164Number = phoneInstance.getNumber();
                        console.log('E164 number:', e164Number);
                        
                        if (e164Number) {
                            // Update the actual input value to E164 format
                            $field.val(e164Number);
                            console.log('Updated field value to:', $field.val());
                        }
                    }
                });
                
                // Prepare form data manually to handle multiple files correctly
                var formData = new FormData();
                
                // Add all form fields except file inputs
                var formDataOriginal = new FormData($form[0]);
                for (var pair of formDataOriginal.entries()) {
                    if (!(pair[1] instanceof File)) {
                        formData.append(pair[0], pair[1]);
                    }
                }
                formData.append('action', 'spai_submit_form');
                
                // Manually add files from our managed storage
                $form.find('.spai-file-upload').each(function() {
                    var $upload = $(this);
                    var $input = $upload.find('input[type="file"]');
                    var fieldName = $input.attr('name');
                    var selectedFiles = $upload.data('selectedFiles') || [];
                    
                    console.log('Processing file field:', fieldName, 'with', selectedFiles.length, 'files');
                    
                    if (selectedFiles.length > 0) {
                        // Add files with array notation for multiple files
                        var baseFieldName = fieldName.replace('[]', '');
                        selectedFiles.forEach(function(file, index) {
                            formData.append(baseFieldName + '[]', file);
                            console.log('Added file to FormData:', baseFieldName + '[]', '->', file.name);
                        });
                    }
                });
                
                // Debug: Check final FormData contents
                console.log('Final FormData file entries:');
                for (var pair of formData.entries()) {
                    if (pair[1] instanceof File) {
                        console.log('FormData file:', pair[0], '->', pair[1].name);
                    }
                }
                
                // Debug: Log FormData contents
                console.log('FormData contents:');
                for (var pair of formData.entries()) {
                    if (pair[0].includes('phone')) {
                        console.log(pair[0] + ': ' + pair[1]);
                    }
                }
                
                // Ensure honeypot stays empty (security: only clear if it was autofilled)
                var $honeypot = $form.find('input[name="spai_hp_firstname"]');
                if ($honeypot.length && $honeypot.val()) {
                    // Only clear if user hasn't interacted with form for 2+ seconds
                    // This prevents bots from benefiting but helps with autofill
                    var lastInteraction = $form.data('lastInteraction') || 0;
                    var timeSinceInteraction = Date.now() - lastInteraction;
                    
                    if (timeSinceInteraction > 2000) {
                        $honeypot.val('');
                        formData.delete('spai_hp_firstname');
                    }
                }
                
                // Add reCAPTCHA token if available
                if (recaptchaToken) {
                    formData.append('recaptcha_token', recaptchaToken);
                }
                
                // Disable button and show spinner
                $button.prop('disabled', true)
                       .html(spai_form.strings.submitting + '<span class="spai-spinner"></span>');
                
                // Submit form
                $.ajax({
                    url: spai_form.ajax_url,
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            // Track form submission
                            trackFormSubmission($form);
                            
                            // Show success message
                            $message.removeClass('error')
                                .addClass('success')
                                .html(response.data.message || spai_form.strings.success)
                                .show();
                            
                            // Clear form
                            $form[0].reset();
                            $('.spai-file-list').empty();
                            
                            // Redirect if URL provided
                            if (response.data && response.data.redirect) {
                                setTimeout(function() {
                                    window.location.href = response.data.redirect;
                                }, 2000);
                            }
                        } else {
                            // Show error message
                            $message.removeClass('success')
                                .addClass('error')
                                .html(response.data || spai_form.strings.error)
                                .show();
                        }
                    },
                    error: function() {
                        // Show error message
                        $message.removeClass('success')
                            .addClass('error')
                            .html(spai_form.strings.error)
                            .show();
                    },
                    complete: function() {
                        $button.prop('disabled', false)
                               .text($button.data('text') || 'Submit');
                    }
                });
            };
            
            // Check if reCAPTCHA v3 is enabled
            if (spai_form.settings.enable_recaptcha && spai_form.settings.recaptcha_site_key && typeof grecaptcha !== 'undefined') {
                // Execute reCAPTCHA v3
                grecaptcha.ready(function() {
                    grecaptcha.execute(spai_form.settings.recaptcha_site_key, {action: 'submit'}).then(function(token) {
                        submitForm(token);
                    }).catch(function(error) {
                        console.error('reCAPTCHA error:', error);
                        $message.removeClass('success')
                            .addClass('error')
                            .html(spai_form.strings.recaptcha_error || 'reCAPTCHA verification failed')
                            .show();
                        $button.prop('disabled', false)
                               .text($button.data('text') || 'Submit');
                    });
                });
            } else {
                // Submit without reCAPTCHA
                submitForm();
            }
        });

        // File upload handling
        $('.spai-file-upload').each(function() {
            var $upload = $(this);
            var $input = $upload.find('input[type="file"]');
            var $list = $upload.find('.spai-file-list');
            
            // Use the effective limits (already calculated on server considering PHP limits)
            var maxSize = spai_form.settings.max_file_size * 1024 * 1024;
            var maxAttachments = spai_form.settings.max_attachments || 2;
            var allowedTypes = spai_form.settings.allowed_file_types;
            
            // Store reference to upload element for file counting and file storage
            $upload.data('fileCount', 0);
            $upload.data('selectedFiles', []);
            
            // Handle file selection
            $input.on('change', function(e) {
                console.log('File input changed. Files selected:', e.target.files.length);
                for (let i = 0; i < e.target.files.length; i++) {
                    console.log('File ' + i + ':', e.target.files[i].name);
                }
                handleFiles(e.target.files);
            });
            
            // Handle drag and drop
            $upload.on('dragover', function(e) {
                e.preventDefault();
                $(this).addClass('dragover');
            });
            
            $upload.on('dragleave', function() {
                $(this).removeClass('dragover');
            });
            
            $upload.on('drop', function(e) {
                e.preventDefault();
                $(this).removeClass('dragover');
                handleFiles(e.originalEvent.dataTransfer.files);
            });
            
            function handleFiles(files) {
                var currentCount = $upload.data('fileCount') || 0;
                var selectedFiles = $upload.data('selectedFiles') || [];
                
                $.each(files, function(i, file) {
                    // Check max attachments
                    if (currentCount >= maxAttachments) {
                        alert(spai_form.strings.too_many_files + ' (Max: ' + maxAttachments + ')');
                        return false; // Stop processing more files
                    }
                    
                    // Check if file already exists
                    var exists = selectedFiles.some(function(existingFile) {
                        return existingFile.name === file.name && existingFile.size === file.size;
                    });
                    
                    if (exists) {
                        return; // Skip duplicate file
                    }
                    
                    // Validate file size against effective limit (considers PHP limits)
                    if (file.size > maxSize) {
                        var sizeMB = Math.round(file.size / (1024 * 1024) * 10) / 10;
                        var maxMB = Math.round(maxSize / (1024 * 1024) * 10) / 10;
                        alert(spai_form.strings.file_too_large + ' (' + file.name + ')\n' +
                              'File size: ' + sizeMB + 'MB, Maximum allowed: ' + maxMB + 'MB');
                        return;
                    }
                    
                    // Validate file type
                    var ext = file.name.split('.').pop().toLowerCase();
                    if (allowedTypes.indexOf(ext) === -1) {
                        alert(spai_form.strings.invalid_file_type + ' (' + file.name + ')');
                        return;
                    }
                    
                    // Add to selected files array
                    selectedFiles.push(file);
                    
                    // Add to visual list
                    var $item = $('<div class="spai-file-item">' +
                        '<span>' + file.name + '</span>' +
                        '<span class="spai-file-remove" data-file="' + file.name + '">×</span>' +
                    '</div>');
                    
                    $list.append($item);
                    currentCount++;
                });
                
                // Update stored data
                $upload.data('fileCount', currentCount);
                $upload.data('selectedFiles', selectedFiles);
                
                // Note: We don't update input.files anymore since we manage files manually
                console.log('Files stored in selectedFiles array:', selectedFiles.length);
            }
            
            // Function to update input element with selected files
            function updateInputFiles(input, files) {
                console.log('updateInputFiles called with', files.length, 'files');
                
                // Check DataTransfer support
                if (typeof DataTransfer === 'undefined') {
                    console.error('DataTransfer API not supported in this browser');
                    return;
                }
                
                try {
                    var dt = new DataTransfer();
                    files.forEach(function(file, index) {
                        console.log('Adding file', index, ':', file.name);
                        dt.items.add(file);
                    });
                    console.log('DataTransfer created with', dt.files.length, 'files');
                    input.files = dt.files;
                    console.log('Input.files updated. New length:', input.files.length);
                } catch (error) {
                    console.error('Error updating input files:', error);
                }
            }
        });
        
        // Remove file
        $(document).on('click', '.spai-file-remove', function() {
            var $item = $(this).closest('.spai-file-item');
            var $upload = $item.closest('.spai-file-upload');
            var $input = $upload.find('input[type="file"]');
            var fileName = $(this).data('file');
            
            // Remove from visual list
            $item.remove();
            
            // Remove from stored files array
            var selectedFiles = $upload.data('selectedFiles') || [];
            selectedFiles = selectedFiles.filter(function(file) {
                return file.name !== fileName;
            });
            
            // Update stored data
            var currentCount = selectedFiles.length;
            $upload.data('fileCount', currentCount);
            $upload.data('selectedFiles', selectedFiles);
            
            // Files are managed in selectedFiles array, no need to update input.files
        });
        
        // Phone input initialization
        function initializePhoneInputs() {
            $('.spai-form input[type="tel"]').each(function() {
                var $input = $(this);
                var fieldId = $input.attr('id');
                var phoneSettings = $input.data('phone-settings') || {};
                
                // Skip if already initialized
                if (phoneInputInstances[fieldId]) {
                    return;
                }
                
                // Default settings
                var settings = {
                    initialCountry: phoneSettings.initialCountry || 'us',
                    separateDialCode: phoneSettings.separateDialCode !== false,
                    nationalMode: phoneSettings.nationalMode !== false,
                    countrySearch: true, // Enable country search
                    required: $input.prop('required')
                };
                
                // Initialize phone input
                if (window.SPAIPhoneInput && window.intlTelInput) {
                    console.log('Initializing phone input for:', fieldId);
                    phoneInputInstances[fieldId] = SPAIPhoneInput.init('#' + fieldId, settings);
                    console.log('Phone instance created:', !!phoneInputInstances[fieldId]);
                } else {
                    console.log('SPAIPhoneInput or intlTelInput not available');
                }
            });
        }
        
        // Form validation
        function validateForm($form) {
            var isValid = true;
            
            // Clear previous errors
            $form.find('.spai-error').remove();
            
            // Check required fields
            $form.find('[required]').each(function() {
                var $field = $(this);
                
                // Skip file inputs - they're always voluntary
                if ($field.attr('type') === 'file') {
                    return; // continue to next field
                }
                
                var value = $field.val();
                
                if (!value || value.trim() === '') {
                    showError($field, 'This field is required');
                    isValid = false;
                }
            });
            
            // Validate email fields
            $form.find('input[type="email"]').each(function() {
                var $field = $(this);
                var value = $field.val();
                
                if (value && !isValidEmail(value)) {
                    showError($field, 'Please enter a valid email address');
                    isValid = false;
                }
            });
            
            // Validate phone fields
            $form.find('input[type="tel"]').each(function() {
                var $field = $(this);
                var fieldId = $field.attr('id');
                var phoneInstance = phoneInputInstances[fieldId];
                
                if (phoneInstance && !phoneInstance.isValid()) {
                    showError($field, 'Please enter a valid phone number');
                    isValid = false;
                }
            });
            
            return isValid;
        }
        
        function showError($field, message) {
            var $error = $('<div class="spai-error">' + message + '</div>');
            $field.closest('.spai-form-group').append($error);
        }
        
        function isValidEmail(email) {
            var regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return regex.test(email);
        }
        
        // Track form submission with Google Analytics and Google Ads
        function trackFormSubmission($form) {
            try {
                // Get form ID from the form element
                var formId = $form.find('input[name="spai_form_id"]').val();
                
                // Get tracking settings for this specific form
                var trackingData = window['spai_form_' + formId];
                
                if (!trackingData) {
                    console.log('No tracking data found for form ' + formId);
                    return;
                }
                
                // Check if gtag is available
                if (typeof gtag === 'function') {
                    // Google Analytics 4 event tracking
                    var ga4EventName = trackingData.ga4_event_name || 'form_submission';
                    gtag('event', ga4EventName, {
                        'event_category': 'Form',
                        'event_label': 'SPAI Form ' + formId,
                        'form_id': formId,
                        'value': 1
                    });
                    console.log('GA4 event tracked: ' + ga4EventName);
                    
                    // Google Ads conversion tracking
                    if (trackingData.google_ads_conversion_id && trackingData.google_ads_conversion_label) {
                        gtag('event', 'conversion', {
                            'send_to': trackingData.google_ads_conversion_id + '/' + trackingData.google_ads_conversion_label,
                            'value': 1.0,
                            'currency': 'USD'
                        });
                        console.log('Google Ads conversion tracked for form ' + formId);
                    }
                } else {
                    console.warn('Google Analytics gtag not found. Make sure Google tag is installed on your site.');
                }
            } catch (e) {
                console.error('Error tracking form conversion:', e);
            }
        }
        
        // Initialize multichoice fields
        function initializeMultichoiceFields() {
            $('.spai-multichoice-container').each(function() {
                var $container = $(this);
                var $inputArea = $container.find('.spai-multichoice-input-area');
                var $input = $container.find('.spai-multichoice-input');
                var $dropdown = $container.find('.spai-multichoice-dropdown');
                var $selected = $container.find('.spai-multichoice-selected-inline');
                var options = $container.data('options') || [];
                var fieldName = $container.data('field-name');
                
                // Show dropdown on input focus/click or input area click
                $input.on('focus click', function() {
                    showDropdown();
                });
                
                $inputArea.on('click', function(e) {
                    // Don't focus if clicking on a tag or remove button
                    if (!$(e.target).closest('.spai-multichoice-tag').length) {
                        $input.focus();
                    }
                });
                
                // Filter options based on input
                $input.on('input', function() {
                    filterOptions();
                });
                
                // Hide dropdown when clicking outside
                $(document).on('click', function(e) {
                    if (!$container.is(e.target) && $container.has(e.target).length === 0) {
                        hideDropdown();
                    }
                });
                
                // Handle option selection
                $dropdown.on('click', '.spai-multichoice-option', function() {
                    var value = $(this).data('value');
                    addSelectedOption(value);
                    $input.val('').focus();
                    filterOptions();
                });
                
                // Handle tag removal
                $selected.on('click', '.spai-multichoice-remove', function() {
                    $(this).closest('.spai-multichoice-tag').remove();
                });
                
                function showDropdown() {
                    $dropdown.show();
                    $container.addClass('dropdown-open');
                    filterOptions();
                }
                
                function hideDropdown() {
                    $dropdown.hide();
                    $container.removeClass('dropdown-open');
                }
                
                function filterOptions() {
                    var searchTerm = $input.val().toLowerCase();
                    var selectedValues = getSelectedValues();
                    
                    $dropdown.find('.spai-multichoice-option').each(function() {
                        var optionText = $(this).text().toLowerCase();
                        var optionValue = $(this).data('value');
                        var isSelected = selectedValues.indexOf(optionValue) !== -1;
                        var matchesSearch = optionText.indexOf(searchTerm) !== -1;
                        
                        if (!isSelected && matchesSearch) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                    });
                }
                
                function addSelectedOption(value) {
                    // Don't add if already selected
                    if (getSelectedValues().indexOf(value) !== -1) {
                        return;
                    }
                    
                    var $tag = $('<span class="spai-multichoice-tag">' +
                        '<span class="spai-multichoice-text">' + value + '</span>' +
                        '<span class="spai-multichoice-remove">×</span>' +
                        '<input type="hidden" name="' + fieldName + '[]" value="' + value + '">' +
                        '</span>');
                    
                    $selected.append($tag);
                }
                
                function getSelectedValues() {
                    var values = [];
                    $selected.find('input[type="hidden"]').each(function() {
                        values.push($(this).val());
                    });
                    return values;
                }
            });
        }
        
        // Initialize marketing data auto-population
        function initializeMarketingDataFields() {
            // Check if marketing data is available from the tracker
            if (typeof window.spaiMarketingData !== 'undefined' && window.spaiMarketingData.formatted) {
                // Find all marketing data fields and populate them
                $('input[name="spai_field_marketing_data"]').each(function() {
                    var $field = $(this);
                    var marketingData = window.spaiMarketingData.formatted;
                    
                    console.log('Auto-populating marketing data field:', marketingData);
                    $field.val(marketingData);
                });
            } else {
                // Marketing tracker might not have loaded yet, try again after a short delay
                setTimeout(function() {
                    if (typeof window.spaiMarketingData !== 'undefined' && window.spaiMarketingData.formatted) {
                        $('input[name="spai_field_marketing_data"]').each(function() {
                            var $field = $(this);
                            var marketingData = window.spaiMarketingData.formatted;
                            
                            console.log('Auto-populating marketing data field (delayed):', marketingData);
                            $field.val(marketingData);
                        });
                    }
                }, 500);
            }
        }
    });

})(jQuery);
