/**
 * SPAI Marketing Data Tracker
 * Site-wide UTM parameter and marketing data capture
 * First-touch attribution with 30-day cookie persistence
 */

(function() {
    'use strict';
    
    // Cookie names for marketing data
    const COOKIE_NAMES = {
        UTM_SOURCE: 'spai_utm_source',
        UTM_CAMPAIGN: 'spai_utm_campaign', 
        UTM_MEDIUM: 'spai_utm_medium',
        REFERRER: 'spai_referrer',
        LANDING_PAGE: 'spai_landing_page',
        FIRST_VISIT: 'spai_first_visit'
    };
    
    // Cookie expiration: 30 days
    const COOKIE_EXPIRES_DAYS = 30;
    
    /**
     * Get URL parameter value
     */
    function getUrlParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }
    
    /**
     * Set cookie with expiration
     */
    function setCookie(name, value, days) {
        const expires = new Date();
        expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = name + '=' + encodeURIComponent(value) + ';expires=' + expires.toUTCString() + ';path=/';
    }
    
    /**
     * Get cookie value
     */
    function getCookie(name) {
        const nameEQ = name + '=';
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
        }
        return null;
    }
    
    /**
     * Check if this is the first visit (no existing marketing cookies)
     */
    function isFirstVisit() {
        return !getCookie(COOKIE_NAMES.FIRST_VISIT);
    }
    
    /**
     * Parse referrer to get clean domain
     */
    function parseReferrer(referrer) {
        if (!referrer || referrer === '') {
            return '(direct)';
        }
        
        try {
            const url = new URL(referrer);
            return url.hostname;
        } catch (e) {
            return referrer;
        }
    }
    
    /**
     * Get current page path for landing page
     */
    function getCurrentPagePath() {
        return window.location.pathname + window.location.search;
    }
    
    /**
     * Format marketing data as human-readable string
     * Only include labels when data exists
     */
    function formatMarketingData() {
        const data = [];
        
        const source = getCookie(COOKIE_NAMES.UTM_SOURCE);
        const campaign = getCookie(COOKIE_NAMES.UTM_CAMPAIGN);
        const medium = getCookie(COOKIE_NAMES.UTM_MEDIUM);
        const referrer = getCookie(COOKIE_NAMES.REFERRER);
        const landingPage = getCookie(COOKIE_NAMES.LANDING_PAGE);
        
        if (source) data.push('Source: ' + source);
        if (campaign) data.push('Campaign: ' + campaign);
        if (medium) data.push('Medium: ' + medium);
        if (referrer) data.push('Referrer: ' + referrer);
        if (landingPage) data.push('Landing: ' + landingPage);
        
        return data.join(', ');
    }
    
    /**
     * Main tracking function - runs on every page load
     */
    function trackMarketingData() {
        console.log('SPAI Marketing Tracker: Starting data capture');
        
        // Check if this is first visit or if we have UTM parameters
        const hasUtmParams = getUrlParameter('utm_source') || getUrlParameter('utm_campaign') || getUrlParameter('utm_medium');
        const firstVisit = isFirstVisit();
        
        console.log('First visit:', firstVisit);
        console.log('Has UTM params:', hasUtmParams);
        
        // For first-touch attribution: only capture UTM data on first visit OR if no UTM data exists yet
        if (firstVisit || hasUtmParams) {
            
            // Capture UTM parameters (only if they exist and we don't have them yet)
            const existingSource = getCookie(COOKIE_NAMES.UTM_SOURCE);
            if (!existingSource) {
                const utmSource = getUrlParameter('utm_source');
                const utmCampaign = getUrlParameter('utm_campaign');
                const utmMedium = getUrlParameter('utm_medium');
                
                if (utmSource) {
                    setCookie(COOKIE_NAMES.UTM_SOURCE, utmSource, COOKIE_EXPIRES_DAYS);
                    console.log('Captured UTM Source:', utmSource);
                }
                if (utmCampaign) {
                    setCookie(COOKIE_NAMES.UTM_CAMPAIGN, utmCampaign, COOKIE_EXPIRES_DAYS);
                    console.log('Captured UTM Campaign:', utmCampaign);
                }
                if (utmMedium) {
                    setCookie(COOKIE_NAMES.UTM_MEDIUM, utmMedium, COOKIE_EXPIRES_DAYS);
                    console.log('Captured UTM Medium:', utmMedium);
                }
            } else {
                console.log('UTM data already exists, preserving first-touch attribution');
            }
            
            // Capture referrer (only on first visit)
            if (firstVisit) {
                const referrer = parseReferrer(document.referrer);
                setCookie(COOKIE_NAMES.REFERRER, referrer, COOKIE_EXPIRES_DAYS);
                console.log('Captured Referrer:', referrer);
                
                // Capture landing page (only on first visit)
                const landingPage = getCurrentPagePath();
                setCookie(COOKIE_NAMES.LANDING_PAGE, landingPage, COOKIE_EXPIRES_DAYS);
                console.log('Captured Landing Page:', landingPage);
                
                // Mark that we've had our first visit
                setCookie(COOKIE_NAMES.FIRST_VISIT, 'true', COOKIE_EXPIRES_DAYS);
            }
        }
        
        // Always log current marketing data for debugging
        const marketingData = formatMarketingData();
        console.log('Current Marketing Data:', marketingData);
        
        // Make marketing data globally available for forms
        window.spaiMarketingData = {
            formatted: marketingData,
            raw: {
                source: getCookie(COOKIE_NAMES.UTM_SOURCE),
                campaign: getCookie(COOKIE_NAMES.UTM_CAMPAIGN),
                medium: getCookie(COOKIE_NAMES.UTM_MEDIUM),
                referrer: getCookie(COOKIE_NAMES.REFERRER),
                landingPage: getCookie(COOKIE_NAMES.LANDING_PAGE)
            }
        };
    }
    
    /**
     * Initialize tracking when DOM is ready
     */
    function initializeTracking() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', trackMarketingData);
        } else {
            trackMarketingData();
        }
    }
    
    // Start tracking immediately
    initializeTracking();
    
    // Export functions for external use
    window.SPAIMarketingTracker = {
        getMarketingData: formatMarketingData,
        getRawData: function() {
            return {
                source: getCookie(COOKIE_NAMES.UTM_SOURCE),
                campaign: getCookie(COOKIE_NAMES.UTM_CAMPAIGN),
                medium: getCookie(COOKIE_NAMES.UTM_MEDIUM),
                referrer: getCookie(COOKIE_NAMES.REFERRER),
                landingPage: getCookie(COOKIE_NAMES.LANDING_PAGE)
            };
        }
    };
    
})();