/**
 * Activity Guard - Visitor Tracking active only admin wants 
 * Lightweight visitor tracking script for frontend
 */
(function() {
    'use strict';

    // Get or create session ID
    function getSessionId() {
        let sessionId = sessionStorage.getItem('wpnts_session_id');
        if (!sessionId) {
            sessionId = 'wpnts_' + Date.now() + '_' + Math.random().toString(36).substring(2, 11);
            sessionStorage.setItem('wpnts_session_id', sessionId);
        }
        return sessionId;
    }

    // Get IP address from frontend
    async function getClientIP() {
        try {
            // Try multiple IP detection services
            const ipServices = [
                'https://api.ipify.org?format=json',
                'https://ipapi.co/json/',
                'https://ipinfo.io/json',
                'https://api.ip.sb/jsonip'
            ];

            for (const service of ipServices) {
                try {
                    const response = await fetch(service, { timeout: 3000 });
                    const data = await response.json();
                    
                    // Different services return IP in different fields
                    const ip = data.ip || data.query || data.ipAddress;
                    if (ip && isValidIP(ip)) {
                        return ip;
                    }
                } catch (e) {
                    console.log('IP service failed:', service, e.message);
                    continue;
                }
            }
        } catch (error) {
            console.log('Frontend IP detection failed:', error);
        }
        return null;
    }

    // Validate IP address format
    function isValidIP(ip) {
        const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
        return ipv4Regex.test(ip) || ipv6Regex.test(ip);
    }

    // Track visitor
    async function trackVisitor() {
        // Check if already tracked in this session
        if (sessionStorage.getItem('wpnts_tracked')) {
            return;
        }

        // Verify that the tracking configuration is available
        if (typeof wpntsVisitorTracking === 'undefined' || !wpntsVisitorTracking.nonce) {
            return;
        }

        const sessionId = getSessionId();
        
        // Get IP from frontend
        const frontendIP = await getClientIP();
        
        // Prepare data with proper validation
        const data = new FormData();
        data.append('action', 'wpnts_track_visitor');
        data.append('nonce', wpntsVisitorTracking.nonce);
        data.append('session_id', sessionId);
        data.append('page_url', window.location.href);
        
        // Handle referrer safely - use empty string if not available
        const referrer = document.referrer || '';
        data.append('referrer', referrer);
        
        data.append('user_agent', navigator.userAgent);
        data.append('screen_resolution', screen.width + 'x' + screen.height);
        data.append('language', navigator.language);
        
        // Add frontend IP if detected
        if (frontendIP) {
            data.append('frontend_ip', frontendIP);
        }


        // Send tracking request with error handling
        fetch(wpntsVisitorTracking.ajaxUrl, {
            method: 'POST',
            body: data,
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                sessionStorage.setItem('wpnts_tracked', '1');
            } 
            /* else {
                console.log('Visitor tracking failed:', result.data?.message || 'Unknown error');
            } */
        })
        .catch(error => {
            console.error('Visitor tracking error:', error);
        });
    }

    // Track on page load
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', trackVisitor);
    } else {
        trackVisitor();
    }
})();
