/**
 * LeadMachine Connector - Frontend JavaScript
 * Version: 2.4.0
 *
 * Handles form submissions for both contact and newsletter forms
 * Includes analytics tracking and browser data collection
 */

(function($) {
    'use strict';

    /**
     * Collect browser and tracking data for lead enrichment
     */
    function collectAnalyticsData() {
        var data = {
            // Timestamp
            submitted_at: new Date().toISOString(),
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            timezone_offset: new Date().getTimezoneOffset(),

            // Page/Source info
            page_url: window.location.href,
            page_title: document.title,
            referrer: document.referrer,

            // UTM parameters
            utm_source: getUrlParam('utm_source'),
            utm_medium: getUrlParam('utm_medium'),
            utm_campaign: getUrlParam('utm_campaign'),
            utm_term: getUrlParam('utm_term'),
            utm_content: getUrlParam('utm_content'),

            // Ad platform click IDs
            gclid: getUrlParam('gclid'),       // Google Ads
            gbraid: getUrlParam('gbraid'),     // Google Ads (iOS)
            wbraid: getUrlParam('wbraid'),     // Google Ads (web-to-app)
            fbclid: getUrlParam('fbclid'),     // Facebook/Meta Ads
            msclkid: getUrlParam('msclkid'),   // Microsoft/Bing Ads
            li_fat_id: getUrlParam('li_fat_id'), // LinkedIn Ads
            ttclid: getUrlParam('ttclid'),     // TikTok Ads
            twclid: getUrlParam('twclid'),     // Twitter/X Ads

            // Browser/Device info
            user_agent: navigator.userAgent,
            language: navigator.language,
            languages: navigator.languages ? navigator.languages.join(',') : navigator.language,
            platform: navigator.platform,
            screen_width: screen.width,
            screen_height: screen.height,
            viewport_width: window.innerWidth,
            viewport_height: window.innerHeight,
            device_pixel_ratio: window.devicePixelRatio,
            color_depth: screen.colorDepth,
            touch_support: ('ontouchstart' in window) || (navigator.maxTouchPoints > 0),

            // Connection info (if available)
            connection_type: getConnectionType(),

            // Cookies that might be useful
            cookies: collectTrackingCookies()
        };

        // Try to detect device type
        data.device_type = detectDeviceType(data.user_agent, data.touch_support, data.screen_width);

        return data;
    }

    /**
     * Get URL parameter value
     */
    function getUrlParam(param) {
        var urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param) || '';
    }

    /**
     * Get connection type if available
     */
    function getConnectionType() {
        if (navigator.connection) {
            return {
                type: navigator.connection.effectiveType || '',
                downlink: navigator.connection.downlink || '',
                rtt: navigator.connection.rtt || ''
            };
        }
        return null;
    }

    /**
     * Collect tracking cookies that might help enrich lead data
     */
    function collectTrackingCookies() {
        var cookies = {};
        var cookieNames = [
            // Google Analytics
            '_ga', '_gid', '_gat',
            // Facebook
            '_fbp', '_fbc',
            // HubSpot
            'hubspotutk', '__hstc', '__hssc',
            // LinkedIn
            'li_sugr', 'bcookie', 'lidc',
            // General tracking
            '__utma', '__utmb', '__utmc', '__utmz',
            // Session identifiers
            'PHPSESSID', 'session_id'
        ];

        cookieNames.forEach(function(name) {
            var value = getCookie(name);
            if (value) {
                cookies[name] = value;
            }
        });

        return cookies;
    }

    /**
     * Get cookie value by name
     */
    function getCookie(name) {
        var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
        return match ? match[2] : null;
    }

    /**
     * Detect device type from user agent and screen info
     */
    function detectDeviceType(userAgent, hasTouch, screenWidth) {
        var ua = userAgent.toLowerCase();

        // Check for mobile devices
        if (/mobile|android|iphone|ipod|blackberry|iemobile|opera mini/i.test(ua)) {
            return 'mobile';
        }

        // Check for tablets
        if (/tablet|ipad|playbook|silk/i.test(ua)) {
            return 'tablet';
        }

        // Fallback based on screen width and touch
        if (hasTouch && screenWidth < 768) {
            return 'mobile';
        }
        if (hasTouch && screenWidth >= 768 && screenWidth < 1024) {
            return 'tablet';
        }

        return 'desktop';
    }

    /**
     * Fire tracking events for analytics platforms
     */
    function fireTrackingEvents(formType, eventData) {
        // Google Analytics 4 (gtag.js)
        if (typeof gtag === 'function') {
            gtag('event', 'generate_lead', {
                event_category: 'LeadMachine',
                event_label: formType,
                value: 1,
                form_type: formType,
                page_url: eventData.page_url
            });

            // Also fire a custom event for more granular tracking
            gtag('event', 'leadmachine_form_submit', {
                form_type: formType,
                page_url: eventData.page_url,
                tags: eventData.tags
            });
        }

        // Google Analytics Universal (analytics.js) - legacy
        if (typeof ga === 'function') {
            ga('send', 'event', 'LeadMachine', 'FormSubmit', formType);
        }

        // Facebook Pixel
        if (typeof fbq === 'function') {
            fbq('track', 'Lead', {
                content_name: formType,
                content_category: 'LeadMachine Form'
            });

            // Also track CompleteRegistration for newsletter signups
            if (formType === 'newsletter') {
                fbq('track', 'CompleteRegistration', {
                    content_name: 'Newsletter Signup'
                });
            }
        }

        // LinkedIn Insight Tag
        if (typeof lintrk === 'function') {
            lintrk('track', { conversion_id: 'leadmachine_' + formType });
        }

        // Twitter/X Pixel
        if (typeof twq === 'function') {
            twq('event', 'tw-leadmachine-lead', {
                form_type: formType
            });
        }

        // TikTok Pixel
        if (typeof ttq === 'function') {
            ttq.track('SubmitForm', {
                content_type: formType,
                content_name: 'LeadMachine Lead'
            });
        }

        // Microsoft/Bing UET
        if (typeof uetq !== 'undefined') {
            uetq.push('event', 'lead', {
                event_category: 'LeadMachine',
                event_label: formType
            });
        }

        // Google Tag Manager dataLayer
        if (typeof dataLayer !== 'undefined' && Array.isArray(dataLayer)) {
            dataLayer.push({
                event: 'leadmachine_form_submit',
                formType: formType,
                pageUrl: eventData.page_url,
                tags: eventData.tags
            });
        }
    }

    $(document).ready(function() {
        // Track form views/impressions
        $('.leadmachine-form').each(function() {
            var $form = $(this);
            var formType = $form.data('form-type') || 'contact';

            // Fire impression event
            if (typeof gtag === 'function') {
                gtag('event', 'leadmachine_form_view', {
                    form_type: formType,
                    page_url: window.location.href
                });
            }

            if (typeof dataLayer !== 'undefined' && Array.isArray(dataLayer)) {
                dataLayer.push({
                    event: 'leadmachine_form_view',
                    formType: formType,
                    pageUrl: window.location.href
                });
            }
        });

        // Handle contact form submission
        $('.leadmachine-form:not(.leadmachine-newsletter-form)').on('submit', function(e) {
            e.preventDefault();
            handleFormSubmit($(this), 'contact');
        });

        // Handle newsletter form submission
        $('.leadmachine-newsletter-form').on('submit', function(e) {
            e.preventDefault();
            handleFormSubmit($(this), 'newsletter');
        });

        /**
         * Handle form submission
         */
        function handleFormSubmit($form, formType) {
            var $button = $form.find('.leadmachine-submit-button');
            var $buttonText = $form.find('.leadmachine-button-text');
            var $buttonSpinner = $form.find('.leadmachine-button-spinner');
            var $messagesContainer = $form.find('.leadmachine-form-messages');

            // Clear previous messages
            $messagesContainer.empty();

            // Disable button and show spinner
            $button.prop('disabled', true);
            $buttonText.hide();
            $buttonSpinner.show();

            // Collect analytics data
            var analyticsData = collectAnalyticsData();

            // Build form data based on form type
            var formData = {
                action: formType === 'newsletter' ? 'leadmachine_newsletter_submit' : 'leadmachine_submit',
                nonce: $form.find('input[name="nonce"]').val(),
                email: $form.find('input[name="email"]').val(),
                source_url: $form.find('input[name="source_url"]').val(),
                tags: $form.find('input[name="tags"]').val(),
                // Spam protection fields
                website_url: $form.find('input[name="website_url"]').val(),
                form_token: $form.find('input[name="form_token"]').val(),
                // Analytics data (JSON encoded)
                analytics_data: JSON.stringify(analyticsData),
                form_type: formType
            };

            // Add form-specific fields
            if (formType === 'newsletter') {
                formData.full_name = $form.find('input[name="full_name"]').val();
                formData.optin = $form.find('input[name="optin"]').is(':checked') ? '1' : '0';
            } else {
                formData.first_name = $form.find('input[name="first_name"]').val();
                formData.last_name = $form.find('input[name="last_name"]').val();
                formData.phone = $form.find('input[name="phone"]').val();
                formData.company = $form.find('input[name="company"]').val();
                formData.message = $form.find('textarea[name="message"]').val();
            }

            // Submit via AJAX
            $.ajax({
                url: leadmachineData.ajax_url,
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        // Fire tracking events on successful submission
                        fireTrackingEvents(formType, {
                            page_url: formData.source_url,
                            tags: formData.tags
                        });

                        // Show success message
                        showMessage('success', response.data.message);

                        // Hide the form fields and show only success message
                        $form.find('.leadmachine-form-row').hide();
                        $form.closest('.leadmachine-form-container').find('.leadmachine-form-header').hide();

                        // Scroll to message
                        $('html, body').animate({
                            scrollTop: $messagesContainer.offset().top - 100
                        }, 500);
                    } else {
                        // Show error message
                        showMessage('error', response.data.message || 'An error occurred. Please try again.');
                    }
                },
                error: function() {
                    showMessage('error', 'Failed to submit form. Please check your internet connection and try again.');
                },
                complete: function() {
                    // Re-enable button and hide spinner
                    $button.prop('disabled', false);
                    $buttonText.show();
                    $buttonSpinner.hide();
                }
            });

            function showMessage(type, message) {
                var messageClass = type === 'success' ? 'leadmachine-message-success' : 'leadmachine-message-error';
                var messageHtml = '<div class="leadmachine-message ' + messageClass + '">' + message + '</div>';
                $messagesContainer.html(messageHtml);
            }
        }
    });

})(jQuery);
