// Initialize Chart.js pageviews chart
document.addEventListener('DOMContentLoaded', function () {
    const ctx = document.getElementById('pagevicoPageviewsChart');
    if (!ctx) return;
  
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: pagevicoTracker.chart_labels,
        datasets: [
          {
            label: 'Pageviews',
            data: pagevicoTracker.chart_values,
            borderColor: 'rgba(255, 107, 0, 1)',
            backgroundColor: 'rgba(255, 107, 0, 0.1)',
            fill: true,
            tension: 0.5
          },
          {
            label: 'Sessions',
            data: pagevicoTracker.session_values,
            borderColor: 'rgba(255, 176, 0, 1)',
            backgroundColor: 'rgba(255, 176, 0, 0.1)',
            fill: true,
            tension: 0.5
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
          mode: 'index',
          intersect: false
        },
        scales: {
          y: {
            beginAtZero: true,
            ticks: { precision: 0 }
          }
        },
        layout: {
          padding: {
            left: 10,
            right: 10,
            top: 20,
            bottom: 10
          }
        }
      }
    });
  });
  

// Add navigation functionality
document.addEventListener('DOMContentLoaded', function() {
    const navItems = document.querySelectorAll('.pagevico-nav li a');
    
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            navItems.forEach(i => i.parentElement.classList.remove('active'));
            this.parentElement.classList.add('active');
        });
    });
    
    // Date range selector
    const dateRange = document.getElementById('pagevico-date-range');
    if (dateRange) {
        dateRange.addEventListener('change', function() {
            // TODO: Implement date range filtering
        });
    }
    
    // Refresh button
    const refreshBtn = document.getElementById('pagevico-refresh');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            fetchRealtimeVisitors();
            // TODO: Refresh other data
        });
    }
});

// Realtime visitors counter with enhanced animation
function fetchRealtimeVisitors() {
  const url = new URL(pagevicoTracker.realtime_url);
  url.searchParams.append('_wpnonce', pagevicoTracker.nonce);

  fetch(url, {
      method: 'GET',
      credentials: 'include'
  })
  .then(res => {
      if (!res.ok) {
          throw new Error(`HTTP error: ${res.status}`);
      }
      return res.json();
  })
  .then(data => {
      const counter = document.getElementById('pagevico-realtime-count');
      if (counter && data && data.active_visitors !== undefined) {
          const currentValue = parseInt(counter.textContent);
          const newValue = parseInt(data.active_visitors);

          if (currentValue !== newValue) {
              counter.classList.add('highlight');
              counter.textContent = newValue;
              setTimeout(() => counter.classList.remove('highlight'), 1000);
          }
      }
  })
  .catch(err => console.error('Error fetching realtime visitors:', err));
}


// Fetch realtime data every 10 seconds
setInterval(fetchRealtimeVisitors, 10000);
fetchRealtimeVisitors(); // Initial fetch