/**
 * NordaBiz Analytics Tracker
 * Tracks user clicks, time on page, and session heartbeats
 * Created: 2026-01-13
 */
(function() {
    'use strict';

    const HEARTBEAT_INTERVAL = 30000; // 30 seconds
    const TRACK_ENDPOINT = '/api/analytics/track';
    const HEARTBEAT_ENDPOINT = '/api/analytics/heartbeat';

    let pageStartTime = Date.now();
    let currentPageViewId = null;

    // Get page view ID from meta tag (set by Flask)
    function init() {
        const pageViewMeta = document.querySelector('meta[name="page-view-id"]');
        if (pageViewMeta && pageViewMeta.content) {
            currentPageViewId = parseInt(pageViewMeta.content, 10);
        }

        // Start heartbeat
        setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);

        // Track clicks
        document.addEventListener('click', handleClick, true);

        // Track time on page before leaving
        window.addEventListener('beforeunload', handleUnload);

        // Also track visibility change (tab switch)
        document.addEventListener('visibilitychange', handleVisibilityChange);
    }

    function handleClick(e) {
        // Find the closest interactive element
        const target = e.target.closest('a, button, [data-track], input[type="submit"], .clickable, .company-card, nav a');
        if (!target) return;

        const data = {
            type: 'click',
            page_view_id: currentPageViewId,
            element_type: getElementType(target, e),
            element_id: target.id || null,
            element_text: (target.textContent || '').trim().substring(0, 100) || null,
            element_class: target.className || null,
            target_url: target.href || target.closest('a')?.href || null,
            x: e.clientX,
            y: e.clientY
        };

        sendTracking(data);
    }

    function getElementType(target, e) {
        // Determine element type more precisely
        if (target.closest('nav')) return 'nav';
        if (target.closest('.company-card')) return 'company_card';
        if (target.closest('form')) return 'form';
        if (target.closest('.sidebar')) return 'sidebar';
        if (target.closest('.dropdown')) return 'dropdown';
        if (target.closest('.modal')) return 'modal';
        if (target.tagName === 'A') return 'link';
        if (target.tagName === 'BUTTON') return 'button';
        if (target.tagName === 'INPUT') return 'input';
        if (target.hasAttribute('data-track')) return target.getAttribute('data-track');
        return target.tagName.toLowerCase();
    }

    function handleUnload() {
        if (!currentPageViewId) return;

        const timeOnPage = Math.round((Date.now() - pageStartTime) / 1000);

        // Use sendBeacon for reliable tracking on page exit
        const data = JSON.stringify({
            type: 'page_time',
            page_view_id: currentPageViewId,
            time_seconds: timeOnPage
        });

        navigator.sendBeacon(TRACK_ENDPOINT, data);
    }

    function handleVisibilityChange() {
        if (document.visibilityState === 'hidden' && currentPageViewId) {
            // Send page time when tab becomes hidden
            const timeOnPage = Math.round((Date.now() - pageStartTime) / 1000);
            sendTracking({
                type: 'page_time',
                page_view_id: currentPageViewId,
                time_seconds: timeOnPage
            });
        }
    }

    function sendHeartbeat() {
        fetch(HEARTBEAT_ENDPOINT, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'same-origin'
        }).catch(function() {
            // Silently fail
        });
    }

    function sendTracking(data) {
        fetch(TRACK_ENDPOINT, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
            credentials: 'same-origin'
        }).catch(function() {
            // Silently fail
        });
    }

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