<script>
(function() {
    {% if debug %}
    console.log('[djinsight] Object view tracking enabled');
    {% endif %}
    
    function trackObjectView() {
        var objectData = {{ object_data|safe }};
        objectData.referrer = document.referrer;
        objectData.user_agent = navigator.userAgent;
        
        fetch('{{ record_url }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(objectData),
            credentials: 'same-origin'
        })
        .then(function(response) {
            if (!response.ok) {
                console.error('{% if debug %}[djinsight] {% endif %}Error recording object view:', response.status, response.statusText);
            }
            return response.json();
        })
        .then(function(data) {
            if (data.success) {
                {% if debug %}
                console.log('[djinsight] Object view recorded successfully:', data);
                {% endif %}
            } else if (data.status === 'ignored') {
                {% if debug %}
                console.log('[djinsight] View ignored:', data.message);
                {% endif %}
            } else {
                console.error('{% if debug %}[djinsight] {% endif %}Error recording object view:', data.error || data.message);
            }
        })
        .catch(function(error) {
            console.error('{% if debug %}[djinsight] {% endif %}Network error recording object view:', error);
        });
    }
    
    {% if async_load %}
    window.addEventListener('load', function() {
        trackObjectView();
    });
    {% else %}
    trackObjectView();
    {% endif %}
})();
</script> 