/**
 * Global Activity Logger
 * Tracks user interactions and sends them to the backend.
 */
const Logger = {
    endpoint: '?api=log_client_event',
    
    init: function() {
        document.addEventListener('click', this.handleClick.bind(this), true); // Capture phase
        console.log('Logger initialized');
    },

    handleClick: function(event) {
        try {
            const target = event.target;
            const element = target.closest('button, a, .btn, input[type="submit"], input[type="button"]');
            
            if (!element) return;

            // Get useful info
            const text = element.innerText || element.value || element.title || element.getAttribute('aria-label') || 'Unknown Element';
            const id = element.id || '';
            const classes = element.className || '';
            const tagName = element.tagName;
            
            // Avoid logging generic clicks on containers if possible, focus on interactive elements
            // Also debounce or ignore if it's a super frequent action? 
            // For "every click", we log it.

            this.log('Click', {
                text: text.trim().substring(0, 50),
                element: tagName,
                id: id,
                classes: classes.substring(0, 50),
                path: window.location.search || 'dashboard'
            }, 'ui_element', id);

        } catch (e) {
            console.error('Logger error:', e);
        }
    },

    log: function(action, details = {}, entityType = 'client_ui', entityId = null) {
        // Use navigator.sendBeacon if available for reliability on unload, 
        // but fetch is fine for general use.
        
        const formData = new FormData();
        formData.append('action', action);
        formData.append('entity_type', entityType);
        if (entityId) formData.append('entity_id', entityId);
        formData.append('details', JSON.stringify(details));

        // Try to find related person ID from context
        let relatedPersonId = null;
        try {
            // Check global app state if available
            if (window.app && window.app.state && window.app.state.currentLead) {
                relatedPersonId = window.app.state.currentLead.didar_contact_id || window.app.state.currentLead.contact_id;
            }
            // Check for hidden inputs often used in forms
            if (!relatedPersonId) {
                const el = document.getElementById('contact-id') || document.querySelector('input[name="contact_id"]');
                if (el) relatedPersonId = el.value;
            }
            // Check URL parameters
            if (!relatedPersonId) {
                const urlParams = new URLSearchParams(window.location.search);
                relatedPersonId = urlParams.get('contact_id');
            }
        } catch(e) {}

        if (relatedPersonId) {
            formData.append('related_person_id', relatedPersonId);
        }

        // Fire and forget
        fetch(this.endpoint, {
            method: 'POST',
            body: formData
        }).catch(() => { /* Ignore logging errors */ });
    }
};

// Expose globally
window.Logger = Logger;
