{% load djinsight_tags %}
{% if no_permission %}
    <!-- djinsight: Access denied -->
{% else %}
<div class="djinsight-live-counter" id="djinsight-live-{{ obj.id }}" data-object-id="{{ obj.id }}" data-content-type="{{ content_type }}" data-refresh-interval="{{ refresh_interval }}">
    <div class="djinsight-counter-display">
        <div class="djinsight-total-counter">
            <span class="djinsight-counter-label">Total Views:</span>
            <span class="djinsight-counter-value" id="total-{{ obj.id }}">{{ obj.total_views|default:0|format_view_count }}</span>
        </div>
        {% if show_unique %}
        <div class="djinsight-unique-counter">
            <span class="djinsight-counter-label">Unique Views:</span>
            <span class="djinsight-counter-value" id="unique-{{ obj.id }}">{{ obj.unique_views|default:0|format_view_count }}</span>
        </div>
        {% endif %}
    </div>
    <div class="djinsight-counter-status" id="status-{{ obj.id }}">
        <span class="djinsight-status-indicator">●</span>
        <span class="djinsight-status-text">Live</span>
    </div>
</div>

<script>
(function() {
    const counterId = 'djinsight-live-{{ obj.id }}';
    const counter = document.getElementById(counterId);
    if (!counter) return;
    
    const objectId = counter.dataset.objectId;
    const contentType = counter.dataset.contentType;
    const refreshInterval = parseInt(counter.dataset.refreshInterval) * 1000 || 30000;
    
    const totalElement = document.getElementById('total-{{ obj.id }}');
    const uniqueElement = document.getElementById('unique-{{ obj.id }}');
    const statusElement = document.getElementById('status-{{ obj.id }}');
    
    function formatCount(count) {
        if (count < 1000) return count.toString();
        if (count < 1000000) return (count / 1000).toFixed(1) + 'K';
        return (count / 1000000).toFixed(1) + 'M';
    }
    
    function updateStats() {
        fetch('{% url "djinsight:get_page_stats" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
            },
            body: JSON.stringify({
                page_id: objectId,
                content_type: contentType
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                if (totalElement) totalElement.textContent = formatCount(data.total_views);
                if (uniqueElement) uniqueElement.textContent = formatCount(data.unique_views);
                statusElement.className = 'djinsight-counter-status djinsight-status-success';
            } else {
                statusElement.className = 'djinsight-counter-status djinsight-status-error';
            }
        })
        .catch(error => {
            console.error('djinsight: Error updating stats:', error);
            statusElement.className = 'djinsight-counter-status djinsight-status-error';
        });
    }
    
    // Update immediately and then on interval
    updateStats();
    setInterval(updateStats, refreshInterval);
})();
</script>
{% endif %}

<style>
.djinsight-live-counter {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 1rem;
    margin: 1rem 0;
}

.djinsight-live-title {
    margin-bottom: 0.5rem;
    color: #495057;
    font-size: 0.9rem;
}

.djinsight-page-stats {
    background: white;
    padding: 0.75rem;
    border-radius: 4px;
    border: 1px solid #e9ecef;
    margin-top: 0.5rem;
}

.djinsight-page-stats span {
    margin-right: 1rem;
    color: #495057;
}

.djinsight-total-count,
.djinsight-unique-count {
    font-weight: 600;
    color: #007bff !important;
}
</style> 