/**
 * ProRank Link Click Tracker
 * 
 * Tracks clicks on internal links for analytics
 */

(function($) {
    'use strict';
    
    // Only run if we have the required data
    if (typeof prorankLinkTracker === 'undefined') {
        return;
    }
    
    $(document).ready(function() {
        // Track clicks on all internal links
        $('a[href]').on('click', function(e) {
            const $link = $(this);
            const href = $link.attr('href');
            
            // Skip if not a valid link
            if (!href || href === '#' || href.indexOf('javascript:') === 0) {
                return;
            }
            
            // Check if it's an internal link
            const isInternal = isInternalLink(href);
            
            if (isInternal) {
                // Track the click
                trackLinkClick(href);
            }
        });
    });
    
    /**
     * Check if a URL is internal
     */
    function isInternalLink(url) {
        const resolvedUrl = resolveTrackedUrl(url);
        if (!resolvedUrl) {
            return false;
        }

        try {
            const site = new URL(prorankLinkTracker.siteUrl);
            const target = new URL(resolvedUrl);
            return normalizeHost(site.hostname) === normalizeHost(target.hostname);
        } catch (err) {
            return false;
        }
    }
    
    /**
     * Track a link click
     */
    function trackLinkClick(targetUrl) {
        targetUrl = resolveTrackedUrl(targetUrl);

        if (!targetUrl) {
            return;
        }

        // Send AJAX request to track the click
        $.ajax({
            url: prorankLinkTracker.ajaxUrl,
            type: 'POST',
            data: {
                action: 'prorank_track_link_click',
                nonce: prorankLinkTracker.nonce,
                source_id: prorankLinkTracker.postId,
                target_url: targetUrl
            },
            // Don't wait for response - let the link navigation continue
            async: true,
            timeout: 1000
        });
    }

    function resolveTrackedUrl(targetUrl) {
        if (!targetUrl) {
            return null;
        }

        let normalized = String(targetUrl).trim();
        if (!normalized) {
            return null;
        }

        if (/^[a-z0-9.-]+\.[a-z]{2,}(\/|$)/i.test(normalized) && normalized.indexOf('http://') !== 0 && normalized.indexOf('https://') !== 0 && normalized.indexOf('//') !== 0) {
            const site = new URL(prorankLinkTracker.siteUrl);
            normalized = `${site.protocol}//${normalized.replace(/^\/+/, '')}`;
        }

        try {
            return new URL(normalized, window.location.href).toString();
        } catch (err) {
            return null;
        }
    }

    function normalizeHost(hostname) {
        return String(hostname || '').replace(/^www\./i, '').toLowerCase();
    }
    
})(jQuery);
