/**
 * Link Tracker - Tracks clicks on internal links
 */

document.addEventListener('DOMContentLoaded', function() {
    // Track clicks on all links
    document.body.addEventListener('click', function(e) {
        // Find the closest anchor element
        let link = e.target.closest('a[href]');
        
        // Only process if it's a valid link
        if (link) {
            // Skip if it's an external link, download link, or has no-track class
            if (link.href.startsWith('http') && !isInternalLink(link.href)) {
                return true;
            }
            
            // Skip tracking for specific cases
            if (link.classList.contains('no-track') || 
                link.hasAttribute('download') || 
                link.getAttribute('target') === '_blank' ||
                link.href.startsWith('tel:') ||
                link.href.startsWith('mailto:') ||
                link.href.startsWith('javascript:') ||
                link.href.startsWith('#')) {
                return true;
            }
            
            // Prevent the default action temporarily
            e.preventDefault();
            
            // Get link data
            const linkData = {
                url: link.href,
                title: link.innerText.trim() || link.title || link.href
            };
            
            // Send the tracking data
            trackLinkClick(linkData, function() {
                // After tracking is complete, follow the link
                window.location.href = link.href;
            });
        }
    }, true); // Use capture phase to catch all clicks
    
    // Track clicks on buttons with data-track-url attribute
    document.body.addEventListener('click', function(e) {
        const button = e.target.closest('[data-track-url]');
        
        if (button) {
            const url = button.getAttribute('data-track-url');
            if (url && isInternalLink(url)) {
                const linkData = {
                    url: url,
                    title: button.innerText.trim() || button.title || button.getAttribute('aria-label') || url
                };
                
                trackLinkClick(linkData);
            }
        }
    });
});

/**
 * Check if a URL is an internal link
 */
function isInternalLink(url) {
    try {
        // Skip if URL is empty or just a hash
        if (!url || url.startsWith('#')) {
            return false;
        }
        
        // Handle relative URLs (they are always internal)
        if (url.startsWith('/') || !url.includes('://')) {
            return true;
        }
        
        // Check if the URL has the same origin as the current page
        const urlObj = new URL(url, window.location.origin);
        return urlObj.hostname === window.location.hostname;
    } catch (e) {
        return false;
    }
}

/**
 * Send tracking data to the server
 */
function trackLinkClick(linkData, callback) {
    // Use the Beacon API if available for better reliability
    if (navigator.sendBeacon) {
        const data = new FormData();
        data.append('url', linkData.url);
        data.append('title', linkData.title);
        
        const success = navigator.sendBeacon('track_click.php', data);
        
        if (success && typeof callback === 'function') {
            callback();
        }
        
        return success;
    }
    
    // Fallback to fetch API
    fetch('track_click.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(linkData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success' && typeof callback === 'function') {
            callback();
        }
    })
    .catch(error => {
        console.error('Error tracking link click:', error);
        // Still execute callback even if tracking fails
        if (typeof callback === 'function') {
            callback();
        }
    });
    
    return true;
}
