// Analytics tracking
(function() {
    // Generate or retrieve visitor ID
    function getVisitorId() {
        let visitorId = localStorage.getItem('visitorId');
        if (!visitorId) {
            visitorId = 'visitor_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('visitorId', visitorId);
        }
        return visitorId;
    }

    // Track page view
    function trackPageView() {
        const visitorId = getVisitorId();
        const page = window.location.pathname + window.location.hash;
        
        fetch('/api/track.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                type: 'pageview',
                page: page,
                visitorId: visitorId
            })
        }).catch(err => console.error('Analytics error:', err));
    }

    // Track page view on load
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', trackPageView);
    } else {
        trackPageView();
    }
    
    // Track RSS link clicks
    const rssLink = document.getElementById('rssLink');
    if (rssLink) {
        rssLink.addEventListener('click', function() {
            const visitorId = getVisitorId();
            fetch('/api/track.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    type: 'rss_click',
                    page: '/blog/feed.xml',
                    visitorId: visitorId
                })
            }).catch(err => console.error('RSS tracking error:', err));
        });
    }
})();
