/**
 * AuctionForge Site Statistics - Frontend Tracker
 * Lightweight page view, search, outbound click, and session tracking.
 */
(function() {
    'use strict';

    if (typeof window.af_stats_config === 'undefined') return;

    var config = window.af_stats_config;
    var VID_KEY = 'af_vid';
    var SID_KEY = 'af_sid';
    var SID_TS_KEY = 'af_sid_ts';
    var SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes
    var HEARTBEAT_INTERVAL = 30000; // 30 seconds
    var currentPvId = 0;
    var pageStartTime = Date.now();
    var heartbeatTimer = null;

    // Generate random hash
    function genHash() {
        var s = '';
        var chars = 'abcdef0123456789';
        for (var i = 0; i < 32; i++) s += chars.charAt(Math.floor(Math.random() * chars.length));
        return s;
    }

    // Get or create visitor ID (persistent via localStorage)
    function getVisitorId() {
        var vid = null;
        try { vid = localStorage.getItem(VID_KEY); } catch(e) {}
        if (!vid) {
            vid = genHash();
            try { localStorage.setItem(VID_KEY, vid); } catch(e) {}
        }
        return vid;
    }

    // Get or create session ID (expires after 30min inactivity)
    function getSessionId() {
        var sid = null;
        var ts = 0;
        try {
            sid = sessionStorage.getItem(SID_KEY);
            ts = parseInt(sessionStorage.getItem(SID_TS_KEY) || '0', 10);
        } catch(e) {}

        var now = Date.now();
        if (!sid || (now - ts) > SESSION_TIMEOUT) {
            sid = genHash();
            try { sessionStorage.setItem(SID_KEY, sid); } catch(e) {}
        }
        try { sessionStorage.setItem(SID_TS_KEY, now.toString()); } catch(e) {}
        return sid;
    }

    // Parse UTM params from URL
    function getUtmParams() {
        var params = {};
        var search = window.location.search;
        if (!search) return params;
        var utmKeys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
        for (var i = 0; i < utmKeys.length; i++) {
            var match = search.match(new RegExp('[?&]' + utmKeys[i] + '=([^&]*)'));
            if (match) params[utmKeys[i]] = decodeURIComponent(match[1]);
        }
        return params;
    }

    // Get page load time
    function getLoadTime() {
        if (window.performance && window.performance.timing) {
            var t = window.performance.timing;
            if (t.loadEventEnd > 0 && t.navigationStart > 0) {
                return t.loadEventEnd - t.navigationStart;
            }
        }
        return 0;
    }

    // Send tracking data
    function track(event, extraData, useBeacon) {
        var vid = getVisitorId();
        var sid = getSessionId();
        var utm = getUtmParams();

        var data = {
            action: 'af_stats_track',
            _nonce: config.nonce,
            event: event,
            vid: vid,
            sid: sid,
            url: window.location.href,
            title: document.title,
            ref: document.referrer,
            sw: screen.width,
            sh: screen.height
        };

        // Add UTM params
        for (var k in utm) {
            if (utm.hasOwnProperty(k)) data[k] = utm[k];
        }

        // Add extra data
        if (extraData) {
            for (var key in extraData) {
                if (extraData.hasOwnProperty(key)) data[key] = extraData[key];
            }
        }

        if (useBeacon && navigator.sendBeacon) {
            var formData = new FormData();
            for (var p in data) {
                if (data.hasOwnProperty(p)) formData.append(p, data[p]);
            }
            navigator.sendBeacon(config.ajax_url, formData);
        } else {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', config.ajax_url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            var encoded = [];
            for (var q in data) {
                if (data.hasOwnProperty(q)) {
                    encoded.push(encodeURIComponent(q) + '=' + encodeURIComponent(data[q]));
                }
            }
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.success && resp.data && resp.data.pv_id) {
                            currentPvId = resp.data.pv_id;
                        }
                    } catch(e) {}
                }
            };
            xhr.send(encoded.join('&'));
        }
    }

    // Track pageview
    function trackPageview() {
        var lt = getLoadTime();
        track('pageview', { lt: lt, pv_id: currentPvId });
    }

    // Track outbound links
    function initOutboundTracking() {
        document.addEventListener('click', function(e) {
            var link = e.target.closest ? e.target.closest('a') : null;
            if (!link) {
                var el = e.target;
                while (el && el.tagName !== 'A') el = el.parentElement;
                link = el;
            }
            if (!link || !link.href) return;

            try {
                var url = new URL(link.href);
                if (url.hostname !== window.location.hostname && url.protocol.indexOf('http') === 0) {
                    track('outbound', {
                        to_url: link.href,
                        link_text: (link.textContent || '').substring(0, 200).trim()
                    });
                }
            } catch(err) {}
        }, true);
    }

    // Track internal searches
    function initSearchTracking() {
        // WordPress search
        var searchInput = document.querySelector('.search-form input[name="s"], form[role="search"] input[name="s"]');
        if (searchInput && searchInput.form) {
            searchInput.form.addEventListener('submit', function() {
                if (searchInput.value.trim()) {
                    track('search', { query: searchInput.value.trim(), stype: 'wordpress' });
                }
            });
        }

        // Auction search (if present)
        var auctionSearch = document.querySelector('.bp-form_search input[name="search"], #search-in-auction input');
        if (auctionSearch) {
            var auctionForm = auctionSearch.closest('form');
            if (auctionForm) {
                auctionForm.addEventListener('submit', function() {
                    if (auctionSearch.value.trim()) {
                        track('search', { query: auctionSearch.value.trim(), stype: 'auction' });
                    }
                });
            }
        }
    }

    // Heartbeat - keeps session alive and tracks time on page
    function startHeartbeat() {
        heartbeatTimer = setInterval(function() {
            var timeOnPage = Math.round((Date.now() - pageStartTime) / 1000);
            track('heartbeat', { pv_id: currentPvId, top: timeOnPage });
        }, HEARTBEAT_INTERVAL);
    }

    // Track page unload
    function initUnloadTracking() {
        var handler = function() {
            var timeOnPage = Math.round((Date.now() - pageStartTime) / 1000);
            track('unload', { pv_id: currentPvId, top: timeOnPage }, true);
            if (heartbeatTimer) clearInterval(heartbeatTimer);
        };

        window.addEventListener('pagehide', handler);
        window.addEventListener('beforeunload', handler);
    }

    // Init
    function init() {
        // Delay slightly so page load time is available
        setTimeout(function() {
            trackPageview();
            initOutboundTracking();
            initSearchTracking();
            startHeartbeat();
            initUnloadTracking();
        }, 100);
    }

    // Wait for DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
