var Telemetry = (function() {
    'use strict';

    var sessionId = '';
    var pageStartTime = 0;
    var clickCount = 0;
    var sendInterval = 60000; // 60 seconds
    var intervalId = null;

    function init() {
        sessionId = generateFingerprint();
        pageStartTime = Date.now();
        clickCount = 0;

        document.addEventListener('click', function() {
            clickCount++;
        });

        intervalId = setInterval(sendTelemetry, sendInterval);
    }

    function generateFingerprint() {
        var parts = [
            screen.width + 'x' + screen.height,
            Intl.DateTimeFormat().resolvedOptions().timeZone || '',
            navigator.language || '',
            navigator.platform || ''
        ];
        return simpleHash(parts.join('|'));
    }

    function simpleHash(str) {
        var hash = 0;
        for (var i = 0; i < str.length; i++) {
            var chr = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + chr;
            hash |= 0;
        }
        return Math.abs(hash).toString(36);
    }

    function trackPage(pageName) {
        pageStartTime = Date.now();
        clickCount = 0;

        sendTelemetry(pageName);
    }

    function sendTelemetry(pageName) {
        var data = {
            csrf: getCsrf(),
            action: 'telemetry',
            telemetry: {
                session_id: sessionId,
                page: pageName || getCurrentPage(),
                time_on_page: Math.round((Date.now() - pageStartTime) / 1000),
                clicks: clickCount
            }
        };

        fetch('/api/router.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        }).catch(function() {
        });
    }

    function getCurrentPage() {
        if (typeof Router !== 'undefined' && Router.currentPage) {
            return Router.currentPage();
        }
        return window.location.hash.replace('#', '') || 'home';
    }

    var getCsrf = Bridge.getCsrf;

    document.addEventListener('DOMContentLoaded', init);

    return {
        trackPage: trackPage,
        getSessionId: function() { return sessionId; }
    };
})();
