<h1>Analytics Dashboard</h1>

<div class="analytics-container">
  <div class="panel">
    <h2>Overall Statistics</h2>
    <div class="stats-grid">
      <div class="stat-box">
        <h3>Total Clicks</h3>
        <p id="total-clicks">Loading...</p>
      </div>
      <div class="stat-box">
        <h3>Total URLs</h3>
        <p id="total-urls">Loading...</p>
      </div>
      <div class="stat-box">
        <h3>Average CTR</h3>
        <p id="average-ctr">Loading...</p>
      </div>
    </div>
  </div>

  <div class="panel">
    <h2>Clickthrough Rates Over Time</h2>
    <canvas id="ctrChart"></canvas>
  </div>

  <div class="panel">
    <h2>URL Statistics</h2>
    <div id="url-list"></div>
  </div>

  <div class="panel" class="statsChart">
    <h2>Device Statistics</h2>
    <canvas id="deviceChart"></canvas>
  </div>

  <div class="panel" class="statsChart">
    <h2>Browser Statistics</h2>
    <canvas id="browserChart"></canvas>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
  fetch('/api/analytics')
    .then(response => response.json())
    .then(data => {
      updateOverallStats(data);
      createCTRChart(data.ctrOverTime);
      createDeviceChart(data.deviceStats);
      createBrowserChart(data.browserStats);
      fetchUrlList();
    })
    .catch(error => console.error('Error fetching analytics data:', error));
});

function updateOverallStats(data) {
  document.getElementById('total-clicks').textContent = data.totalClicks;
  document.getElementById('total-urls').textContent = data.totalUrls;
  document.getElementById('average-ctr').textContent = (data.averageCTR * 100).toFixed(2) + '%';
}

function createCTRChart(ctrData) {
  const ctx = document.getElementById('ctrChart').getContext('2d');
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: ctrData.map(d => d._id),
      datasets: [{
        label: 'CTR',
        data: ctrData.map(d => d.ctr * 100),
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: function(value) {
              return value + '%';
            }
          }
        }
      }
    }
  });
}

function fetchUrlList() {
  fetch('/dashboard')
    .then(response => response.text())
    .then(html => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const urlItems = doc.querySelectorAll('.url-item');
      const urlListContainer = document.getElementById('url-list');

      urlItems.forEach(item => {
        const shortCode = item.querySelector('.short-url a').textContent.trim();
        const originalUrl = item.querySelector('.original-url').textContent;

        const urlPanel = document.createElement('div');
        urlPanel.className = 'panel url-panel';
        urlPanel.innerHTML = `
          <h3 class="url-title">${originalUrl}</h3>
          <p class="short-url-display">Short URL: <a href="/${shortCode}" target="_blank">${shortCode}</a></p>
          <h4 class="country-stats-title">Country Statistics</h4>
          <div class="country-list" id="country-list-${shortCode}">
            <div class="loading-spinner"></div>
          </div>
        `;

        urlListContainer.appendChild(urlPanel);

        fetchCountryStats(shortCode);
      });
    })
    .catch(error => console.error('Error fetching URL list:', error));
}

function fetchCountryStats(shortCode) {
  fetch(`/api/country-stats/${shortCode}`)
    .then(response => response.json())
    .then(data => {
      const countryList = document.getElementById(`country-list-${shortCode}`);
      let listHtml = '<ul class="country-stats">';
      data.forEach(({ _id, count }) => {
        listHtml += `
          <li class="country-stat-item">
            <span class="country-name">${_id}</span>
            <span class="country-clicks">${count} click${count !== 1 ? 's' : ''}</span>
          </li>
        `;
      });
      listHtml += '</ul>';
      countryList.innerHTML = listHtml;
    })
    .catch(error => console.error(`Error fetching country stats for ${shortCode}:`, error));
}

function createDeviceChart(deviceData) {
  const ctx = document.getElementById('deviceChart').getContext('2d');
  new Chart(ctx, {
    type: 'pie',
    data: {
      labels: deviceData.map(d => d._id),
      datasets: [{
        data: deviceData.map(d => d.count),
        backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56']
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: 'Device Usage'
        }
      }
    }
  });
}

function createBrowserChart(browserData) {
  const ctx = document.getElementById('browserChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: browserData.map(d => d._id),
      datasets: [{
        label: 'Usage',
        data: browserData.map(d => d.count),
        backgroundColor: 'rgba(75, 192, 192, 0.6)',
        borderColor: 'rgba(75, 192, 192, 1)',
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
}
</script>

<style>
.url-panel {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.url-panel:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.url-title {
  font-size: 1.2em;
  color: var(--primary-color);
  margin-bottom: 10px;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 10px;
}

.short-url-display {
  font-size: 0.9em;
  color: var(--secondary-color);
  margin-bottom: 15px;
}

.short-url-display a {
  color: var(--primary-color);
  text-decoration: none;
  font-weight: bold;
}

.short-url-display a:hover {
  text-decoration: underline;
}

.country-stats-title {
  font-size: 1em;
  color: var(--text-color);
  margin-bottom: 10px;
}

.country-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid var(--border-color);
  border-radius: 4px;
}

.country-stats {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.country-stat-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 12px;
  border-bottom: 1px solid var(--border-color);
  transition: background-color 0.2s ease;
}

.country-stat-item:last-child {
  border-bottom: none;
}

.country-stat-item:hover {
  background-color: rgba(var(--primary-color-rgb), 0.05);
}

.country-name {
  font-weight: bold;
}

.country-clicks {
  color: var(--secondary-color);
}

.loading-spinner {
  border: 4px solid var(--border-color);
  border-top: 4px solid var(--primary-color);
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 20px auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>